
    9i7                    J   d Z ddlmZ ddlZddlmZmZ ddlmZ ddl	m
Z
mZmZmZmZmZmZmZ ddlmZmZ ddlmZmZ dd	lmZmZ e
rdd
lmZmZ ddlmZ  ed      Z ed   Z! G d de"      Z# G d de#      Z$ G d de#      Z%	 	 	 	 	 	 	 	 d#dZ& ed       G d dee                 Z' ed       G d dee                 Z( ed       G d dee                 Z)e G d dee                 Z*e G d d ee                 Z+ G d! d"ee          Z,e(e    e)e    z  e,e    z  Z-y)$z)Types for setting agent response formats.    )annotationsN)	dataclassis_dataclass)	UnionType)TYPE_CHECKINGAnyGenericLiteralTypeVarUnionget_args
get_origin)BaseToolStructuredTool)	BaseModelTypeAdapter)Selfis_typeddict)CallableIterable)	AIMessageSchemaT)pydanticr   	typeddictjson_schemac                      e Zd ZU dZded<   y)StructuredOutputErrorz(Base class for structured output errors.r   
ai_messageN)__name__
__module____qualname____doc____annotations__     l/var/www/html/backtest/airagagent/rag_env/lib/python3.12/site-packages/langchain/agents/structured_output.pyr   r   "   s    2r%   r   c                  $     e Zd ZdZd fdZ xZS )MultipleStructuredOutputsErrorzZRaised when model returns multiple structured output tool calls when only one is expected.c                f    || _         || _        t        |   ddj	                  |       d       y)zInitialize `MultipleStructuredOutputsError`.

        Args:
            tool_names: The names of the tools called for structured output.
            ai_message: The AI message that contained the invalid multiple tool calls.
        z:Model incorrectly returned multiple structured responses (z, z) when only one is expected.N)
tool_namesr   super__init__join)selfr*   r   	__class__s      r&   r,   z'MultipleStructuredOutputsError.__init__+   s=     %$		*%&&BD	
r%   )r*   z	list[str]r   r   returnNoner   r    r!   r"   r,   __classcell__r/   s   @r&   r(   r(   (   s    d
 
r%   r(   c                  $     e Zd ZdZd fdZ xZS )StructuredOutputValidationErrorzXRaised when structured output tool call arguments fail to parse according to the schema.c                \    || _         || _        || _        t        |   d| d| d       y)a  Initialize `StructuredOutputValidationError`.

        Args:
            tool_name: The name of the tool that failed.
            source: The exception that occurred.
            ai_message: The AI message that contained the invalid structured output.
        z,Failed to parse structured output for tool 'z': .N)	tool_namesourcer   r+   r,   )r.   r9   r:   r   r/   s       r&   r,   z(StructuredOutputValidationError.__init__>   s;     #$G	{RUV\U]]^_`r%   )r9   strr:   	Exceptionr   r   r0   r1   r2   r4   s   @r&   r6   r6   ;   s    ba ar%   r6   c                    |dk(  r|S 	 t        |       }|j                  |      S # t        $ r/}t        | dt	        |             }d| d| }t        |      |d}~ww xY w)a  Parse data using for any supported schema type.

    Args:
        schema: The schema type (Pydantic model, `dataclass`, or `TypedDict`)
        schema_kind: One of `"pydantic"`, `"dataclass"`, `"typeddict"`, or
            `"json_schema"`
        data: The data to parse

    Returns:
        The parsed instance according to the schema type

    Raises:
        ValueError: If parsing fails
    r   r   zFailed to parse data to z: N)r   validate_pythonr<   getattrr;   
ValueError)schemaschema_kinddataadaptereschema_namemsgs          r&   _parse_with_schemarH   L   sq    " m#%(3F(;&&t,, %fj#f+>(Rs;o1$%s   % 	A*AAF)initc                      e Zd ZU dZded<   	 ded<   	 ded<   	 ded<   	 d	ed
<   	 dZded<   	 dddd	 	 	 	 	 	 	 	 	 ddZy)_SchemaSpecz%Describes a structured output schema.type[SchemaT]rA   r;   namedescription
SchemaKindrB   dict[str, Any]r   FboolstrictN)rM   rN   rR   c               v   || _         |r|| _        nt        |t              rBt	        |j                  ddt	        t        j                               dd              | _        n<t	        t        |ddt	        t        j                               dd              | _        |xs3 t        |t              r|j                  dd      nt        |dd      xs d| _	        || _
        t        |t              rd	| _        || _        yt        |t              r-t        |t              rd
| _        |j!                         | _        yt#        |      r&d| _        t%        |      j                         | _        yt'        |      r&d| _        t%        |      j                         | _        ydt        |       d}t)        |      )z:Initialize SchemaSpec with schema and optional parameters.titleresponse_format_N   r   rN    r"   r   r   r   r   zUnsupported schema type: zS. Supported types: Pydantic models, dataclasses, TypedDicts, and JSON schema dicts.)rA   rM   
isinstancedictr;   getuuiduuid4r?   rN   rR   rB   r   type
issubclassr   model_json_schemar   r   r   r@   )r.   rA   rM   rN   rR   rG   s         r&   r,   z_SchemaSpec.__init__   s    DI%FJJw2B3tzz|CTUWVWCXBY0Z[\DIGFJ:J3tzz|K\]_^_K`Ja8bcdDI& 
&$' JJ}b)D17R 	 fd#,D%D%*VY*G)D%779D&!*D*62>>@D&!*D*62>>@D ,DL> :d e  S/!r%   )
rA   rL   rM   
str | NonerN   r`   rR   rQ   r0   r1   )r   r    r!   r"   r#   rR   r,   r$   r%   r&   rK   rK   h   s    / I 
 1FD=  "&+"+" 	+"
  +" +" 
+"r%   rK   c                  `    e Zd ZU dZded<   	 ded<   	 ded<   	 ded	<   	 d
dd	 	 	 	 	 	 	 ddZy
)ToolStrategyz0Use a tool calling strategy for model responses.rL   rA   zlist[_SchemaSpec[SchemaT]]schema_specsr`   tool_message_contentWbool | str | type[Exception] | tuple[type[Exception], ...] | Callable[[Exception], str]handle_errorsNT)rd   rf   c                   || _         || _        || _        dfd |      D cg c]  }t        |       c}| _        yc c}w )zInitialize `ToolStrategy`.

        Initialize `ToolStrategy` with schemas, tool message content, and error handling
        strategy.
        c              3    K   t        |       t        t        fv r!t        |       D ]  } |      E d{     yt	        | t
              r,d| v r(| j                  dg       D ]  } |      E d{     y|  y7 H7 w)z5Yield leaf variants from Union and JSON Schema oneOf.NoneOf)r   r   r   r   rX   rY   rZ   )rA   argsub_iter_variantss      r&   rl   z-ToolStrategy.__init__.<locals>._iter_variants   s     &!i%77#F+ 3C-c2223&$'Gv,=!::gr2 3C-c2223L 3
 3s!   1BA=;B0A?1B?BN)rA   r   r0   zIterable[Any])rA   rd   rf   rK   rc   )r.   rA   rd   rf   srl   s        @r&   r,   zToolStrategy.__init__   sC      $8!*	 6DF5KL[^LLs   A)rA   rL   rd   r`   rf   re   r0   r1   r   r    r!   r"   r#   r,   r$   r%   r&   rb   rb      sl    :$,,*$$- 	`	 ,0
 (,"M"M )	"M
%"M 
"Mr%   rb   c                  B    e Zd ZU dZded<   	 ded<   	 	 	 	 	 d	dZd
dZy)ProviderStrategyz9Use the model provider's native structured output method.rL   rA   _SchemaSpec[SchemaT]schema_specc                2    || _         t        |      | _        y)z(Initialize ProviderStrategy with schema.N)rA   rK   rr   r.   rA   s     r&   r,   zProviderStrategy.__init__   s    
 &v.r%   c                j    d| j                   j                  | j                   j                  dd}d|iS )z@Convert to kwargs to bind to a model to force structured output.r   )rM   rA   )r]   r   response_format)rr   rM   r   )r.   rv   s     r&   to_model_kwargsz ProviderStrategy.to_model_kwargs  s>    
 "((--**66
 "?33r%   NrA   rL   r0   r1   )r0   rP   )r   r    r!   r"   r#   r,   rw   r$   r%   r&   rp   rp      s3    C!%%&// 
/4r%   rp   c                  P    e Zd ZU dZded<   	 ded<   	 ded<   	 edd       Zdd	Zy
)OutputToolBindinga*  Information for tracking structured output tool metadata.

    This contains all necessary information to handle structured responses
    generated via tool calls, including the original schema, its type classification,
    and the corresponding tool implementation used by the tools strategy.
    rL   rA   rO   rB   r   toolc           	          | |j                   |j                  t        |j                  |j                  |j
                              S )zCreate an `OutputToolBinding` instance from a `SchemaSpec`.

        Args:
            schema_spec: The `SchemaSpec` to convert

        Returns:
            An `OutputToolBinding` instance with the appropriate tool created
        )args_schemarM   rN   )rA   rB   r{   )rA   rB   r   r   rM   rN   clsrr   s     r&   from_schema_specz"OutputToolBinding.from_schema_spec(  sF     %%#//'33 %%'33
 	
r%   c                D    t        | j                  | j                  |      S )a  Parse tool arguments according to the schema.

        Args:
            tool_args: The arguments from the tool call

        Returns:
            The parsed response according to the schema type

        Raises:
            ValueError: If parsing fails
        )rH   rA   rB   )r.   	tool_argss     r&   parsezOutputToolBinding.parse<  s     "$++t/?/?KKr%   Nrr   rq   r0   r   )r   rP   r0   r   )r   r    r!   r"   r#   classmethodr   r   r$   r%   r&   rz   rz     s@     D M
NL
 
&Lr%   rz   c                  L    e Zd ZU dZded<   	 ded<   	 ed
d       ZddZddZy	)ProviderStrategyBindinga   Information for tracking native structured output metadata.

    This contains all necessary information to handle structured responses
    generated via native provider output, including the original schema,
    its type classification, and parsing logic for provider-enforced JSON.
    rL   rA   rO   rB   c                >     | |j                   |j                        S )zCreate a `ProviderStrategyBinding` instance from a `SchemaSpec`.

        Args:
            schema_spec: The `SchemaSpec` to convert

        Returns:
            A `ProviderStrategyBinding` instance for parsing native structured output
        rA   rB   r   r~   s     r&   r   z(ProviderStrategyBinding.from_schema_spec[  s#     %%#//
 	
r%   c                   | j                  |      }ddl}	 |j                  |      }t        | j
                  | j                  |      S # t        $ r1}t	        | j
                  dd      }d| d| d}t        |      |d}~ww xY w)a@  Parse `AIMessage` content according to the schema.

        Args:
            response: The `AIMessage` containing the structured output

        Returns:
            The parsed response according to the schema

        Raises:
            ValueError: If text extraction, JSON parsing or schema validation fails
        r   Nr   rv   z1Native structured output expected valid JSON for z, but parsing failed: r8   )	"_extract_text_content_from_messagejsonloadsr<   r?   rA   r@   rH   rB   )r.   responseraw_textr   rC   rE   rF   rG   s           r&   r   zProviderStrategyBinding.parsej  s     ::8D	)::h'D "$++t/?/?FF  	)!$++z;LMKCK= Q''(c,  S/q(	)s   A	 		B,A>>Bc                   |j                   }t        |t              r|S t        |t              rg }|D ]  }t        |t              rd|j                  d      dk(  r"d|v r|j                  t        |d                Id|v sNt        |d   t              sb|j                  |d          w|j                  t        |              dj                  |      S t        |      S )zExtract text content from an AIMessage.

        Args:
            message: The AI message to extract text from

        Returns:
            The extracted text content
        r]   textcontentrW   )r   rX   r;   listrY   rZ   appendr-   )r.   messager   partscs        r&   r   z:ProviderStrategyBinding._extract_text_content_from_message  s     //gs#Ngt$!E )a&uuV}.6Q;S6^4"aJq|S,IQy\2LLQ() 775>!7|r%   Nr   )r   r   r0   r   )r   r   r0   r;   )	r   r    r!   r"   r#   r   r   r   r   r$   r%   r&   r   r   K  s=     H M
 
G<r%   r   c                  .    e Zd ZU dZded<   	 	 	 	 	 ddZy)AutoStrategyz=Automatically select the best strategy for structured output.rL   rA   c                    || _         y)z$Initialize AutoStrategy with schema.N)rA   rt   s     r&   r,   zAutoStrategy.__init__  s    
 r%   Nrx   rn   r$   r%   r&   r   r     s%    G$ 
r%   r   )rA   ztype[SchemaT] | dictrB   rO   rC   rP   r0   r   ).r"   
__future__r   r[   dataclassesr   r   typesr   typingr   r   r	   r
   r   r   r   r   langchain_core.toolsr   r   r   r   r   typing_extensionsr   r   collections.abcr   r   langchain_core.messagesr   r   rO   r<   r   r(   r6   rH   rK   rb   rp   rz   r   r   ResponseFormatr$   r%   r&   <module>r      s   / "  / 	 	 	 : + 021 )
HI
I 
%: 
&a&; a"% %/9%AO%%8 H"''" H" H"V =M77# =M =M@ 4ww' 4 4> 2L( 2L 2Lj Sgg. S Sl77#  g&)9')BB\RYEZZr%   