
    g3fiI                        d Z ddlmZ ddlZddlZddlmZmZ ddlm	Z	 erddl
mZ ddZddZd	d
ddZ ej                  dej                         Zed	 	 	 	 	 ddZdZed	 	 	 	 	 ddZddZy)zUtilities for JSON.    )annotationsN)TYPE_CHECKINGAny)OutputParserException)Callablec                (   | j                  d      }t        j                  dd|      }t        j                  dd|      }t        j                  dd|      }t        j                  dd	|      }| j                  d
      |z   | j                  d      z   S )zReplace newline characters in a regex match with escaped sequences.

    Args:
        match: Regex match object containing the string to process.

    Returns:
        String with newlines, carriage returns, tabs, and quotes properly escaped.
       \nz\\nz\rz\\rz\tz\\tz(?<!\\)"z\"      )groupresub)matchvalues     W/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/utils/json.py_replace_new_liner      sy     KKNEFF5&%(EFF5&%(EFF5&%(EFF;u-E;;q>E!EKKN22    c                    t        | t        t        f      r| j                         } t	        j
                  dt        | t        j                        S )at  Custom parser for multiline strings.

    The LLM response for `action_input` may be a multiline
    string containing unescaped newlines, tabs or quotes. This function
    replaces those characters with their escaped counterparts.
    (newlines in JSON must be double-escaped: `\\n`).

    Returns:
        The modified string with escaped newlines, tabs and quotes.
    z("action_input"\:\s*")(.*?)("))flags)
isinstancebytes	bytearraydecoder   r   r   DOTALL)multiline_strings    r   _custom_parserr   !   sD     "UI$67+22466)ii	 r   Fstrictc                  	 t        j                  | |      S # t         j                  $ r Y nw xY wg }g }d}d}| D ]  }|}|r |dk(  r|sd}no|dk(  r|sd}ne|dk(  r| }n\d}nY|dk(  rd}d}nO|dk(  r|j                  d	       n8|d
k(  r|j                  d       n!|dv r|r|d   |k(  r|j	                          n y|j                  |        |r#|r|j	                          |j                  d       |j                          |rV	 t        j                  dj                  ||z         |      S # t         j                  $ r |j	                          Y nw xY w|rVt        j                  | |      S )zParse a JSON string that may be missing closing braces.

    Args:
        s: The JSON string to parse.
        strict: Whether to use strict parsing.

    Returns:
        The parsed JSON object as a Python dictionary.
    r   F"
r
   \T{}[]>   r'   r%   N )jsonloadsJSONDecodeErrorappendpopreversejoin)sr   	new_charsstackis_inside_stringescapedcharnew_chars           r   parse_partial_jsonr8   ;   s   zz!F++  IEG  #s{7#( g  %+S[#GS[LLS[LLZrd*		  	"9#@ MMO 
MMO 	::bggi%&78HH## 	 MMO	  ::a''s    //(D0 0#EEz```(json)?(.*)parserc                   	 t        | |      S # t        j                  $ r- t        j	                  |       }|| n|j                  d      }Y nw xY wt        ||      S )zParse a JSON string from a Markdown string.

    Args:
        json_string: The Markdown string.
        parser: The parser to use. Defaults to `parse_partial_json`.

    Returns:
        The parsed JSON object as a Python dictionary.
    r9   r	   )_parse_jsonr*   r,   _json_markdown_researchr   )json_stringr:   r   json_strs       r   parse_json_markdownrA      s`    D;v66 D!((5 #(-;U[[^D x//s    =AAz 
	`c               R    | j                  t              } t        |       }  ||       S )a  Parse a JSON string, handling special characters and whitespace.

    Strips whitespace, newlines, and backticks from the start and end of the string,
    then processes special characters before parsing.

    Args:
        json_str: The JSON string to parse.
        parser: Optional custom parser function.

            Defaults to `parse_partial_json`.

    Returns:
        Parsed JSON object.
    )strip_json_strip_charsr   )r@   r:   s     r   r<   r<      s,    $ ~~/0H h'H (r   c                   	 t        |       }t	        |t
              s&dt        |      j                   d}t        ||       |D ]  }||vsd| d| }t        |       |S # t        j                  $ r}d| }t        |      |d}~ww xY w)a  Parse and check a JSON string from a Markdown string.

    Checks that it contains the expected keys.

    Args:
        text: The Markdown string.
        expected_keys: The expected keys in the JSON string.

    Returns:
        The parsed JSON object as a Python dictionary.

    Raises:
        OutputParserException: If the JSON string is invalid or does not contain
            the expected keys.
    z Got invalid JSON object. Error: Nz&Expected JSON object (dict), but got: z. )
llm_outputz)Got invalid return object. Expected key `z` to be present, but got )rA   r*   r,   r   r   dicttype__name__)textexpected_keysjson_objemsgerror_messagekeys          r   parse_and_check_json_markdownrQ      s     0&t, h%4T(^5L5L4MRP 	 $MdCC -h;C5 A**25  (,,- O!  004#C(a/0s   A# #B6BB)r   zre.Match[str]returnstr)r   zstr | bytes | bytearrayrR   rS   )r1   rS   r   boolrR   r   )r?   rS   r:   Callable[[str], Any]rR   r   )r@   rS   r:   rU   rR   r   )rJ   rS   rK   z	list[str]rR   rG   )__doc__
__future__r   r*   r   typingr   r   langchain_core.exceptionsr   collections.abcr   r   r   r8   compiler   r=   rA   rD   r<   rQ    r   r   <module>r]      s     "  	 % ;(3$4 27 N(b BJJ0"))<  9K00!5000   6H26"r   