
    Wg0                         d dl Z d dlZd dlZd dlmZ  ej                  e      Zd Z	d Z
dedefdZdedefd	Zd
edefdZ
y)    N)repair_jsonc                    t         j                  d|         | rt        | t              s+t         j	                  dt        |               t               S | j                         st         j	                  d       t               S d}t        j                  |d|       } | j                         } d| v rt         j	                  d       t               S | j                  d      | j                  d	      kD  r	 | j                  dd	      } 	 t        j                  |       }t        |t              rOt         j	                  d       |rt        |d   t               r|d   }nt         j	                  d       t               S t        |t               s+t         j	                  dt        |              t               S d|vr t         j	                  d       dddddd|d<   d|vrt         j	                  d       dddiig|d<   t        |d   t               s t         j	                  d       dddddd|d<   |d   }dD ]  }||vsd||<    t        |d   t              s=t         j	                  d       t        |d   t               r|d   g|d<   |S dddiig|d<   |S # t        $ r#}t         j	                  d
|        Y d}~d}~ww xY w# t        j"                  $ r}t         j	                  d|        d}t        j$                  ||       }|r<|D ]7  }	 t        j                  |      c cY d}~S # t        j"                  $ r Y 5w xY w t               cY d}~S d}~ww xY w)z
    Enhanced function to repair JSON strings from LLM responses.
    Handles various issues like markdown code blocks, lists instead of dicts, etc.
    zInput to enhanced_repair_json: z'Invalid input to enhanced_repair_json: zEmpty JSON string receivedz```(?:json)?([\s\S]*?)```z\1z	function(z%Function call syntax detected in JSON'"zError replacing quotes: Nz:JSON was parsed as a list, attempting to convert to objectr   z Could not convert list to objectz!Parsed JSON is not a dictionary: current_statezMissing 'current_state' fieldUnknown prev_action_evaluationimportant_contentstask_progressfuture_plansthoughtactionzMissing 'action' field	go_to_urlurlabout:blankz#'current_state' is not a dictionaryz'action' is not a listzJSON decode error: z{[^{}]*})loggerdebug
isinstancestrwarningtypecreate_fallback_jsonstripresubcountreplace	ExceptionjsonloadslistdictJSONDecodeErrorfindall)	json_strpatterneparsedcsfieldjson_patternmatchesmatchs	            L/Users/kosar/src/browser-use-projects/web-ui/src/agent/custom_json_repair.pyenhanced_repair_jsonr1      sG   
 LL28*=>:h4@h@PQR#%% >>34#%% +Gvvguh/H~~H h>?#%% ~~cX^^C00	;''S1H
K&H% fd#NNWX*VAY5AB+-- &$'NN>tF|nMN')) &(NN:;*3&(!# "'F?# 6!NN34!,um.D EFF8 &148NN@A*3&(!# "'F?# O$q 	EB5		
 &*D1NN34&*D1$*8$4#5x   &15-2H$I#Jx {  	;NN5aS9::	;~  &,QC01 #**\84  ::e,,++  $%%!&s{   5J A3K <:K 7BK  AK K 	K"K  KM7ML/'M)M/MMMMMMc                  "    ddddddddd	iigd
S )z3Create a fallback JSON structure when repair fails.Failedr	   z Error in processing model outputzRetry with proper formattingz The model generated invalid JSONr
   r   r   r   r   r    r5       r0   r   r   y   s;     '/"$?:9
 =
 r6   textreturnc                    t         j                  d       ddddddd}i }g d}|D ]O  \  }}t        j                  || t        j                        }|s.|j                  d      j                         ||<   Q |j                         D ]   \  }}|s	|j                         dvs|||<   " |sd}t        j                  ||       }	|	rt         j                  d	t        |	       d
       |	D ]o  \  }}|j                         j                         }|j                         }|dv r||d<   >|dv r||d<   H|dv r||d<   R|dv r||d<   \|dv r||d<   f|dv sk||d<   q g }
d}t        j                  ||       }|r|
j                  dd|d   ii       d}t        j                  || t        j                        }|r(|D ]#  \  }}|
j                  ddt        |      ii       % d}t        j                  || t        j                        }|r8|D ]3  \  }}}|
j                  dt        |      |j                         d i       5 ||
d!}t        j                  |      S )"z
    Attempt to extract key-value pairs from text and construct a valid JSON.
    
    Args:
        text: The text to extract from
        
    Returns:
        A JSON string with the extracted information
    z/Attempting to extract key-value pairs from textr   r	   r   r   r   r   r   summary))z=prev_action_evaluation[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r   )z9important_contents[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r   )z4task_progress[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r   )z3future_plans[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r   )z.thought[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r   )z.summary[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r;   )z1evaluation[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r   )z/contents[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r   )z/progress[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r   )z,plans[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r   )z/thinking[\"']?\s*[:=]\s*[\"']?([^\"'\n]+)[\"']?r      )nonenull	undefinedz4(?:\"?([a-zA-Z_]+)\"?\s*[:=]\s*\"?([^\"\'\n,}]+)\"?)zFound z key-value pairsr   
evaluationaction_evaluationr   r   contentsr   r   progressr   r   plansr   r   thinkingr   r;   r;   zhttps?://[^\s"]+r   r   r   z=click[_\s]*(element|button)?[_\s]*.*?index[_\s]*[:=]?\s*(\d+)click_elementindexz]input[_\s]*(text)?[_\s]*.*?index[_\s]*[:=]?\s*(\d+).*?text[_\s]*[:=]?\s*["\']?([^"\']+)["\']?
input_text)rM   r7   r4   )r   r   r   search
IGNORECASEgroupr   itemslowerr&   lenappendintr!   dumps)r7   r   sectionssection_patternsr(   keyr/   valuekey_value_patternr.   r   url_patternurlsclick_patternclick_matches_rM   input_patterninput_matchesrN   results                        r0   extract_and_construct_jsonre      s    LLBC #, M H" ) 3		'47!KKN002HSM3 nn& '
UU[[]*GG!&M#'
  T**.5LL6#g,/?@A% 5
Uiik'') WW>CM":;>>:?M"67995:M/25549M.133/4M),K'/4M),!5& F &K::k4(D{UDG$456 UMJJ}dBMMBM% 	DHAuMM?Wc%j,ABC	D uMJJ}dBMMBM$1 	] AujMM<3u:zGWGWGY)Z[\	]
 'F
 ::fr6   datac                    t         j                  d       dddddddg d}d| v r3t        | d   t              r |d   D ]  }|| d   v s| d   |   |d   |<    d| v rt        | d   t              r| d   |d<   | j                         D ]X  \  }}|dvs|dv r	||d   d	<   |d
v r	||d   d<   %|dv r	||d   d<   2|dv r	||d   d<   ?|dv r	||d   d<   L|dv sQ||d   d<   Z t        j                  |      S )z
    Construct a valid JSON structure from a dictionary that may be missing required fields.
    
    Args:
        data: The dictionary to construct from
        
    Returns:
        A valid JSON string
    z/Constructing valid JSON from partial dictionaryr   r	   r:   r4   r   r   r@   r   rC   r   rE   r   rG   r   rI   r   rK   r;   )r   r   r   r$   r#   rR   r!   rW   )rf   rd   rZ   r[   s       r0   construct_valid_json_from_dictrh      su    LLBC
 '0"$
 
F $:d?.CT#J/* 	JCd?++/3O/DS/I',	J
 4JtH~t<>x jjl ;
U11SSDI'(@A::@E'(<=55;@'811:?'7//5:'	2#5:'	2;  ::fr6   error_messagec                     t         j                  d|         d|  dddd|  ddg d	}t        j                  |      S )
z
    Create a fallback JSON with an error message.
    
    Args:
        error_message: The error message to include
        
    Returns:
        A valid JSON string
    zCreating fallback JSON: z	Failed - r	   z.Attempting to recover from invalid JSON formatz!Retry with proper JSON formattingz)The model generated an invalid response: z Invalid response format detectedr:   r4   )r   r   r!   rW   )ri   fallbacks     r0   r   r   0  s\     NN-m_=> )2-&A"$M?B=/R9
 
H ::hr6   )r!   loggingr   json_repairr   original_repair_json	getLogger__name__r   r1   r   r   re   r$   rh   r5   r6   r0   <module>rq      sm      	 ;			8	$o&b$mS mS m^4 4# 4l     r6   