
    =i                    `   S r SSKJr  SSKrSSKJrJrJrJrJ	r	J
r
Jr  SSKJr  SSKJrJrJrJr  SSKJr  SSKJr  SS	KJrJr  SS
KJr  SSKJrJr  SSKJ r   SSK!J"r"J#r#  SSK$J%r%  SSK&J'r'J(r(J)r)  SSK*J+r+J,r,J-r-J.r.J/r/J0r0J1r1J2r2J3r3J4r4  SSK5J6r6J7r7J8r8J9r9J:r:J;r;J<r<J=r=J>r>  SSK?J@r@  \(       a0  SSKAJBrBJCrCJDrD  SSKEJFrF  SSKGJHrH  SSKJIrI  SSKJJKrK  SSK!JLrL  SSK*JMrMJNrN  SrOS0S jrP    S1S jrQ    S2S jrRS3S4S jjrSS5S jrTS6S  jrUS7S! jrV      S8S" jrW    S9S# jrX    S:S$ jrY S3SS%SSSSSSSS&SSS'.                             S;S( jjjrZ        S<S) jr[    S=S* jr\        S>S+ jr]      S?S, jr^          S@S- jr_              SAS. jr`S//rag)Bz:Agent factory for creating agents with middleware support.    )annotationsN)TYPE_CHECKING	AnnotatedAnycastget_args
get_originget_type_hints)BaseChatModel)	AIMessage
AnyMessageSystemMessageToolMessage)BaseTool)RunnableCallable)ENDSTART)
StateGraph)ToolCallWithContextToolNode)Runtime)CommandSend)ContextT)NotRequiredRequired	TypedDict)
AgentMiddleware
AgentStateJumpToModelRequestModelResponseOmitFromSchema	ResponseT	StateT_co_InputAgentState_OutputAgentState)	AutoStrategyMultipleStructuredOutputsErrorOutputToolBindingProviderStrategyProviderStrategyBindingResponseFormatStructuredOutputErrorStructuredOutputValidationErrorToolStrategy)init_chat_model)	AwaitableCallableSequence)Runnable)	BaseCache)CompiledStateGraph)	BaseStore)Checkpointer)ToolCallRequestToolCallWrapperz)Error: {error}
 Please fix your mistakes.c                F    [        U [        5      (       a  [        U /SS9$ U $ )z3Normalize middleware return value to ModelResponse.Nresultstructured_response)
isinstancer   r"   )r>   s    h/home/dmtnaga/Documents/work/airagagent/rag_env/lib/python3.13/site-packages/langchain/agents/factory.py_normalize_to_model_responserB   C   s#    &)$$VH$GGM    c                   ^^ U (       d  g[        U 5      S:X  a  U S   m      SU4S jjnU$       S	S jnU S   m[        U SS 5       H  nU" UT5      mM           SU4S jjnU$ )
a  Compose multiple wrap_model_call handlers into single middleware stack.

Composes handlers so first in list becomes outermost layer. Each handler
receives a handler callback to execute inner layers.

Args:
    handlers: List of handlers. First handler wraps all others.

Returns:
    Composed handler, or `None` if handlers empty.

Example:
    ```python
    # handlers=[auth, retry] means: auth wraps retry
    # Flow: auth calls retry, retry calls base handler
    def auth(req, state, runtime, handler):
        try:
            return handler(req)
        except UnauthorizedError:
            refresh_token()
            return handler(req)


    def retry(req, state, runtime, handler):
        for attempt in range(3):
            try:
                return handler(req)
            except Exception:
                if attempt == 2:
                    raise


    handler = _chain_model_call_handlers([auth, retry])
    ```
N   r   c                *   > T" X5      n[        U5      $ NrB   requesthandlerr>   single_handlers      rA   normalized_single5_chain_model_call_handlers.<locals>.normalized_single   s     $G5F/77rC   c                (   ^ ^       SUU 4S jjnU$ )z-Compose two handlers where outer wraps inner.c                >   >^ SUU4S jjnT" X5      n[        U5      $ )Nc                ,   > T" U T5      n[        U5      $ rG   rH   reqinner_resultrK   inners     rA   inner_handlerX_chain_model_call_handlers.<locals>.compose_two.<locals>.composed.<locals>.inner_handler   s    $S'23LAArC   rS   r!   returnr"   rH   rJ   rK   rV   outer_resultrU   outers    `  rA   composedA_chain_model_call_handlers.<locals>.compose_two.<locals>.composed   s&    
B B
 !8L/==rC   rJ   r!   rK   z'Callable[[ModelRequest], ModelResponse]rY   r"    r\   rU   r]   s   `` rA   compose_two/_chain_model_call_handlers.<locals>.compose_two   s.    	>!	><	> 	> 	> rC   c                *   > T" X5      n[        U5      $ rG   rH   rJ   rK   final_resultr>   s      rA   final_normalized4_chain_model_call_handlers.<locals>.final_normalized   s    
 g/+L99rC   r_   )r\   \Callable[[ModelRequest, Callable[[ModelRequest], ModelResponse]], ModelResponse | AIMessage]rU   rj   rY   zPCallable[[ModelRequest, Callable[[ModelRequest], ModelResponse]], ModelResponse]lenreversedhandlersrM   rb   rK   rh   r>   rL   s        @@rA   _chain_model_call_handlersrp   J   s    b 
8}!!	8!	8<	8 	8 ! 



> b\FHSbM*Wf- +::8: 
: rC   c                   ^^ U (       d  g[        U 5      S:X  a  U S   m      SU4S jjnU$       S	S jnU S   m[        U SS 5       H  nU" UT5      mM           SU4S jjnU$ )
zCompose multiple async `wrap_model_call` handlers into single middleware stack.

Args:
    handlers: List of async handlers. First handler wraps all others.

Returns:
    Composed async handler, or `None` if handlers empty.
NrE   r   c                F   >#    T" X5      I S h  vN n[        U5      $  N7frG   rH   rI   s      rA   rM   ;_chain_async_model_call_handlers.<locals>.normalized_single   s%      *';;F/77 <   !!c                (   ^ ^       SUU 4S jjnU$ )z3Compose two async handlers where outer wraps inner.c                Z   >^#    SUU4S jjnT" X5      I S h  vN n[        U5      $  N7f)Nc                H   >#    T" U T5      I S h  vN n[        U5      $  N7frG   rH   rR   s     rA   rV   ^_chain_async_model_call_handlers.<locals>.compose_two.<locals>.composed.<locals>.inner_handler   s%     %*3%883LAA  9s   " "rX   rH   rZ   s    `  rA   r]   G_chain_async_model_call_handlers.<locals>.compose_two.<locals>.composed   s1     
B B
 "'w!>>L/== ?s   +)+rJ   r!   rK   z2Callable[[ModelRequest], Awaitable[ModelResponse]]rY   r"   r`   ra   s   `` rA   rb   5_chain_async_model_call_handlers.<locals>.compose_two   s.    	>!	>G	> 	> 	> rC   rd   c                F   >#    T" X5      I S h  vN n[        U5      $  N7frG   rH   rf   s      rA   rh   :_chain_async_model_call_handlers.<locals>.final_normalized  s%     
 $G55+L99 6rt   rz   )r\   rCallable[[ModelRequest, Callable[[ModelRequest], Awaitable[ModelResponse]]], Awaitable[ModelResponse | AIMessage]]rU   r~   rY   zfCallable[[ModelRequest, Callable[[ModelRequest], Awaitable[ModelResponse]]], Awaitable[ModelResponse]]rk   rn   s        @@rA    _chain_async_model_call_handlersr      s    , 
8}!!	8!	8G	8 	8 ! 



> b\FHSbM*Wf- +::C: 
: rC   c                   0 nU  Hy  n[        USS9nUR                  5        HX  u  pgSnU(       a=  [        U5      n	U	 H,  n
[        U
[        5      (       d  M  [        X5      SL d  M*  Sn  O   U(       a  MT  XsU'   MZ     M{     [        X5      $ )a  Resolve schema by merging schemas and optionally respecting `OmitFromSchema` annotations.

Args:
    schemas: List of schema types to merge
    schema_name: Name for the generated `TypedDict`
    omit_flag: If specified, omit fields with this flag set (`'input'` or
        `'output'`)
T)include_extrasF)r
   items_extract_metadatar@   r#   getattrr   )schemasschema_name	omit_flagall_annotationsschemahints
field_name
field_typeshould_omitmetadatametas              rA   _resolve_schemar     s     Ovd;&+kkm"JK,Z8$D!$77GD<TX\<\&* %
 ;.8
+ '4 " [22rC   c                    [        U 5      [        [        4;   a:  [        U 5      S   n[        U5      [        L a  [        [        U5      SS 5      $  / $ [        U 5      [        L a  [        [        U 5      SS 5      $ / $ )zYExtract metadata from a field type, handling Required/NotRequired and Annotated wrappers.r   rE   N)r	   r   r   r   r   list)type_
inner_types     rA   r   r   .  s~     %X{33e_Q'
j!Y.,QR011 / I 
E	i	'HUOAB'((IrC   c                R   [        [        US5      n[        [        SU 3S5      n[        U R                  US5      nU(       a!  XBLa  [        US5      (       a  UR                  $ [        U R                  SU 3S5      nU(       a!  XSLa  [        US5      (       a  UR                  $ / $ )a  Get the `can_jump_to` list from either sync or async hook methods.

Args:
    middleware: The middleware instance to inspect.
    hook_name: The name of the hook (`'before_model'` or `'after_model'`).

Returns:
    List of jump destinations, or empty list if not configured.
Na__can_jump_to__)r   r   	__class__hasattrr   )
middleware	hook_namebase_sync_methodbase_async_methodsync_methodasync_methods         rA   _get_can_jump_tor   =  s     	4@1YK$G *..	4@K/K!233*** ://1YK$GL1L"344+++IrC   c                   ^ Sm[        U [        5      (       a  U mO"[        U [        5      (       a  [        U SS5      mT(       a/  STR	                  5       ;   =(       d    [        U4S jS 5       5      $ S$ )zCheck if a model supports provider-specific structured output.

Args:
    model: Model name string or `BaseChatModel` instance.

Returns:
    `True` if the model supports provider-specific structured output, `False` otherwise.
N
model_namegrokc              3  ,   >#    U  H	  oT;   v   M     g 7frG   r`   ).0partr   s     rA   	<genexpr>._supports_provider_strategy.<locals>.<genexpr>q  s     c.bdz!.bs   )zgpt-5zgpt-4.1zgpt-osszo3-prozo3-miniF)r@   strr   r   lowerany)modelr   s    @rA   _supports_provider_strategyr   `  ss     "J%
	E=	)	)UL$7

  	*""$$ 	dc.bcc 	rC   c                R  ^  [        U[        5      (       d  gUR                  nUSL a  gUSL a  S[        R	                  [        T 5      S94$ [        U[
        5      (       a  SU4$ [        U[        5      (       aE  [        U[        5      (       a0  [        T U5      (       a  S[        R	                  [        T 5      S94$ g[        U[        5      (       a9  [        U 4S jU 5       5      (       a  S[        R	                  [        T 5      S94$ g[        U5      (       a
  SU" T 5      4$ g)zMHandle structured output error. Returns `(should_retry, retry_tool_message)`.)F FT)errorc              3  <   >#    U  H  n[        TU5      v   M     g 7frG   )r@   )r   exc_type	exceptions     rA   r   2_handle_structured_output_error.<locals>.<genexpr>  s     M}8z)X..}s   )r@   r0   handle_errors STRUCTURED_OUTPUT_ERROR_TEMPLATEformatr   type
issubclass	Exceptiontupler   callable)r   response_formatr   s   `  rA   _handle_structured_output_errorr   w  s   
 o|44#11M5<<3y><RRR-%%]""-&&:mY+O+Oi//9@@s9~@VVV-''M}MMM9@@s9~@VVV]9---rC   c                    U (       d  g[        U 5      S:X  a  U S   $ SS jnU S   n[        U SS 5       H  nU" X25      nM     U$ )aT  Compose wrappers into middleware stack (first = outermost).

Args:
    wrappers: Wrappers in middleware order.

Returns:
    Composed wrapper, or `None` if empty.

Example:
    wrapper = _chain_tool_call_wrappers([auth, cache, retry])
    # Request flows: auth -> cache -> retry -> tool
    # Response flows: tool -> retry -> cache -> auth
NrE   r   c                (   ^ ^       SUU 4S jjnU$ )z-Compose two wrappers where outer wraps inner.c                (   >^ SUU4S jjnT" X5      $ )Nc                   > T" U T5      $ rG   r`   rS   executerU   s    rA   
call_innerT_chain_tool_call_wrappers.<locals>.compose_two.<locals>.composed.<locals>.call_inner  s    S'**rC   rS   r:   rY   ToolMessage | Commandr`   rJ   r   r   rU   r\   s    ` rA   r]   @_chain_tool_call_wrappers.<locals>.compose_two.<locals>.composed  s    
+ + --rC   )rJ   r:   r   z2Callable[[ToolCallRequest], ToolMessage | Command]rY   r   r`   ra   s   `` rA   rb   ._chain_tool_call_wrappers.<locals>.compose_two  s.    		.$		.G		. #		. 		. rC   rd   )r\   r;   rU   r;   rY   r;   rk   wrappersrb   r>   wrappers       rA   _chain_tool_call_wrappersr     sV      
8}{" b\FHSbM*W- + MrC   c                    U (       d  g[        U 5      S:X  a  U S   $       SS jnU S   n[        U SS 5       H  nU" X25      nM     U$ )zCompose async wrappers into middleware stack (first = outermost).

Args:
    wrappers: Async wrappers in middleware order.

Returns:
    Composed async wrapper, or `None` if empty.
NrE   r   c                (   ^ ^       SUU 4S jjnU$ )z3Compose two async wrappers where outer wraps inner.c                D   >^#    SUU4S jjnT" X5      I S h  vN $  N7f)Nc                2   >#    T" U T5      I S h  vN $  N7frG   r`   r   s    rA   r   Z_chain_async_tool_call_wrappers.<locals>.compose_two.<locals>.composed.<locals>.call_inner  s     "30000s   r   r`   r   s    ` rA   r]   F_chain_async_tool_call_wrappers.<locals>.compose_two.<locals>.composed  s#     
1 1 w3333s     )rJ   r:   r   z=Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]rY   r   r`   ra   s   `` rA   rb   4_chain_async_tool_call_wrappers.<locals>.compose_two  s.    		4$		4R		4 #		4 		4 rC   rd   )r\   |Callable[[ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]], Awaitable[ToolMessage | Command]]rU   r   rY   r   rk   r   s       rA   _chain_async_tool_call_wrappersr     st    , 
8}{



: b\FHSbM*W- + MrC   r`   F)system_promptr   r   state_schemacontext_schemacheckpointerstoreinterrupt_beforeinterrupt_afterdebugnamecachec                 ^ ^^B^C^D^E^F^G^H^I^J^K [        T [        5      (       a  [        T 5      m Uc  / nUc  SmHO?[        U[        [        45      (       a  UmHO![        U[
        5      (       a  UmHO	[        US9mHSn[        TH[
        5      (       a  [        THR                  S9nO[        TH[        5      (       a  THn0 mIU(       aB  UR                   H2  n[        R                  " U5      nUTIUR                  R                  '   M4     U VVs/ s H  n[        US/ 5        H  nUPM     M     nnnU Vs/ s HU  nUR                  R                  [        R                  Ld)  UR                  R                   [        R                   Ld  MS  UPMW     nnSnU(       a'  U Vs/ s H  nUR                  PM     nn[#        U5      nU Vs/ s HU  nUR                  R                   [        R                   Ld)  UR                  R                  [        R                  Ld  MS  UPMW     nnSnU(       a'  U Vs/ s H  nUR                   PM     nn[%        U5      nSmJU Vs/ s H  n[        U[&        5      (       d  M  UPM     nnU Vs/ s H  n[        U[&        5      (       a  M  UPM     nnUU-   nU(       a  [)        UUUS9OSmJTJ(       a'  [+        TJR,                  R/                  5       5      U-   mGO[+        U5      mG[1        U Vs1 s H  nUR                  iM     sn5      [1        U5      :X  d   S5       eU Vs/ s HU  nUR                  R2                  [        R2                  Ld)  UR                  R4                  [        R4                  Ld  MS  UPMW     nnU Vs/ s HU  nUR                  R6                  [        R6                  Ld)  UR                  R8                  [        R8                  Ld  MS  UPMW     nnU Vs/ s HU  nUR                  R:                  [        R:                  Ld)  UR                  R<                  [        R<                  Ld  MS  UPMW     nnU Vs/ s HU  nUR                  R>                  [        R>                  Ld)  UR                  R@                  [        R@                  Ld  MS  UPMW     n nU Vs/ s HU  nUR                  RB                  [        RB                  Ld)  UR                  RD                  [        RD                  Ld  MS  UPMW     n!nU Vs/ s HU  nUR                  RD                  [        RD                  Ld)  UR                  RB                  [        RB                  Ld  MS  UPMW     n"nSmKU!(       a'  U! Vs/ s H  nURB                  PM     n#n[G        U#5      mKSmFU"(       a'  U" Vs/ s H  nURD                  PM     n$n[I        U$5      mFU Vs1 s H  nURJ                  iM     n%nUb  UO[L        n&U%RO                  U&5        [Q        U%SS5      n'[Q        U%SS5      n([Q        U%S	S
5      n)[S        U'U(U)US9n*      S)UI4S jjmES*UIUJ4S jjmDS+UDUE4S jjmCS,UCUGUHU UUK4S jjn+S+UDUE4S jjmBS,UBUFUGUHU U4S jjn,U*RU                  S[W        U+U,SS95        TJb  U*RU                  STJ5        U GH  nUR                  R2                  [        R2                  Ld'  UR                  R4                  [        R4                  La  UR                  R2                  [        R2                  La  UR2                  OSn-UR                  R4                  [        R4                  La  UR4                  OSn.[W        U-U.SS9n/U*RU                  UR                   S3U/U'S9  UR                  R6                  [        R6                  Ld'  UR                  R8                  [        R8                  La  UR                  R6                  [        R6                  La  UR6                  OSn0UR                  R8                  [        R8                  La  UR8                  OSn1[W        U0U1SS9n2U*RU                  UR                   S3U2U'S9  UR                  R:                  [        R:                  Ld'  UR                  R<                  [        R<                  La  UR                  R:                  [        R:                  La  UR:                  OSn3UR                  R<                  [        R<                  La  UR<                  OSn4[W        U3U4SS9n5U*RU                  UR                   S3U5U'S9  UR                  R>                  [        R>                  Ld*  UR                  R@                  [        R@                  Ld  GM  UR                  R>                  [        R>                  La  UR>                  OSn6UR                  R@                  [        R@                  La  UR@                  OSn7[W        U6U7SS9n8U*RU                  UR                   S3U8U'S9  GM     U(       a  US   R                   S3n9OU(       a  US   R                   S3n9OSn9U(       a  US   R                   S3n:OSn:U(       a  US   R                   S3n;OSn;U (       a  U S   R                   S3n<O[X        n<U*R[                  [\        U95        TJb  U:/n=[_        S TJR,                  R/                  5        5       5      (       d  TI(       a  U=Ra                  U<5        U*Rc                  S[W        [e        TJU:TIU<S9SS9U=5        SU</n>U(       d  U;S:w  a  U>Ra                  U:5        U*Rc                  U;[W        [g        U:TIU<S9SS9U>5        Oy[1        TI5      S:  a&  U*Rc                  U;[W        [i        U:U<S9SS9U:U</5        ODU;S:X  a  U*R[                  U;U<5        O+[k        U*US   R                   S3U<U:U<[m        US   S 5      S!9  U(       a}  [n        Rp                  " U5       H8  u  n?n@[k        U*U?R                   S3U@R                   S3U:U<[m        U?S"5      S!9  M:     [k        U*US   R                   S3U:U:U<[m        US   S"5      S!9  U(       a}  [n        Rp                  " U5       H8  u  n?n@[k        U*U?R                   S3U@R                   S3U:U<[m        U?S#5      S!9  M:     [k        U*US   R                   S3SU:U<[m        US   S#5      S!9  U(       a  U*R[                  SUS   R                   S35        [s        [1        U5      S$-
  SS5       HB  nAUUA   n?UUAS$-
     n@[k        U*U?R                   S3U@R                   S3U:U<[m        U?S 5      S!9  MD     U (       a  [s        [1        U 5      S$-
  SS5       HB  nAU UA   n?U UAS$-
     n@[k        U*U?R                   S3U@R                   S3U:U<[m        U?S%5      S!9  MD     [k        U*U S   R                   S3[X        U:U<[m        U S   S%5      S!9  U*Ru                  UUU	U
UUUS&9Rw                  S'S(05      $ s  snnf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf s  snf )-af  Creates an agent graph that calls tools in a loop until a stopping condition is met.

For more details on using `create_agent`,
visit the [Agents](https://docs.langchain.com/oss/python/langchain/agents) docs.

Args:
    model: The language model for the agent. Can be a string identifier
        (e.g., `"openai:gpt-4"`) or a direct chat model instance (e.g.,
        [`ChatOpenAI`][langchain_openai.ChatOpenAI] or other another
        [chat model](https://docs.langchain.com/oss/python/integrations/chat)).

        For a full list of supported model strings, see
        [`init_chat_model`][langchain.chat_models.init_chat_model(model_provider)].
    tools: A list of tools, `dicts`, or `Callable`.

        If `None` or an empty list, the agent will consist of a model node without a
        tool calling loop.
    system_prompt: An optional system prompt for the LLM.

        Prompts are converted to a
        [`SystemMessage`][langchain.messages.SystemMessage] and added to the
        beginning of the message list.
    middleware: A sequence of middleware instances to apply to the agent.

        Middleware can intercept and modify agent behavior at various stages. See
        the [full guide](https://docs.langchain.com/oss/python/langchain/middleware).
    response_format: An optional configuration for structured responses.

        Can be a `ToolStrategy`, `ProviderStrategy`, or a Pydantic model class.

        If provided, the agent will handle structured output during the
        conversation flow. Raw schemas will be wrapped in an appropriate strategy
        based on model capabilities.
    state_schema: An optional `TypedDict` schema that extends `AgentState`.

        When provided, this schema is used instead of `AgentState` as the base
        schema for merging with middleware state schemas. This allows users to
        add custom state fields without needing to create custom middleware.
        Generally, it's recommended to use `state_schema` extensions via middleware
        to keep relevant extensions scoped to corresponding hooks / tools.

        The schema must be a subclass of `AgentState[ResponseT]`.
    context_schema: An optional schema for runtime context.
    checkpointer: An optional checkpoint saver object.

        Used for persisting the state of the graph (e.g., as chat memory) for a
        single thread (e.g., a single conversation).
    store: An optional store object.

        Used for persisting data across multiple threads (e.g., multiple
        conversations / users).
    interrupt_before: An optional list of node names to interrupt before.

        Useful if you want to add a user confirmation or other interrupt
        before taking an action.
    interrupt_after: An optional list of node names to interrupt after.

        Useful if you want to return directly or run additional processing
        on an output.
    debug: Whether to enable verbose logging for graph execution.

        When enabled, prints detailed information about each node execution, state
        updates, and transitions during agent runtime. Useful for debugging
        middleware behavior and understanding agent execution flow.
    name: An optional name for the `CompiledStateGraph`.

        This name will be automatically used when adding the agent graph to
        another graph as a subgraph node - particularly useful for building
        multi-agent systems.
    cache: An optional `BaseCache` instance to enable caching of graph execution.

Returns:
    A compiled `StateGraph` that can be used for chat interactions.

The agent node calls the language model with the messages list (after applying
the system prompt). If the resulting [`AIMessage`][langchain.messages.AIMessage]
contains `tool_calls`, the graph will then call the tools. The tools node executes
the tools and adds the responses to the messages list as
[`ToolMessage`][langchain.messages.ToolMessage] objects. The agent node then calls
the language model again. The process repeats until no more `tool_calls` are present
in the response. The agent then returns the full list of messages.

Example:
    ```python
    from langchain.agents import create_agent


    def check_weather(location: str) -> str:
        '''Return the weather forecast for the specified location.'''
        return f"It's always sunny in {location}"


    graph = create_agent(
        model="anthropic:claude-sonnet-4-5-20250929",
        tools=[check_weather],
        system_prompt="You are a helpful assistant",
    )
    inputs = {"messages": [{"role": "user", "content": "what is the weather in sf"}]}
    for chunk in graph.stream(inputs, stream_mode="updates"):
        print(chunk)
    ```
Nr   tools)r   wrap_tool_callawrap_tool_callz-Please remove duplicate middleware instances.StateSchemaInputSchemainputOutputSchemaoutput)r   input_schemaoutput_schemar   c           	     z  > [        U[        5      (       aN  U R                  (       d8  [        R                  " UR
                  5      n UR                  U 5      nU /US.$ SU /0$ [        U[        5      (       Ga  [        U [        5      (       Ga  U R                  (       a  U R                   Vs/ s H  owS   T;   d  M  UPM     nnU(       a  Sn	[        U5      S:  a]  U Vs/ s H  owS   PM	     n
n[        X5      n	[        X5      u  pU(       d  U	eU Vs/ s H  n[!        UUS   US   S	9PM     nnSU /UQ0$ US
   n TUS      nUR                  US   5      nUR"                  (       a  UR"                  OSU 3nU [!        UUS   US   S	9/US.$ SU /0$ ! [         a4  n[        UR
                  R                  SS5      n[        XTU 5      nUeSnAff = fs  snf s  snf s  snf ! [         aD  n[        US   X@5      n	[        X5      u  pU(       d  U	eSU [!        UUS   US   S	9/0s SnA$ SnAff = f)zHandle model output including structured responses.

Args:
    output: The AI message output from the model.
    effective_response_format: The actual strategy used
        (may differ from initial if auto-detected).
)messagesr?   __name__r   Nr   r   rE   id)contenttool_call_idr   r   argszReturning structured response: )r@   r+   
tool_callsr,   from_schema_specschema_specparser   r   r   r/   r0   r   rl   r)   r   r   tool_message_content)r   effective_response_formatprovider_strategy_bindingr?   excr   validation_errortcstructured_tool_callsr   
tool_namesshould_retryerror_messagetool_messages	tool_callstructured_tool_bindingr   structured_output_toolss                    rA   _handle_model_output*create_agent.<locals>._handle_model_output/  s    /1ABB$$,C,T,T-99-)	^*C*I*I&*Q' *0I\]])) 0,??69--!! $..%.rV*@W2W. " % %:>	,-17L!M7LV*7LJ!M >z RI2Q!3/L (' #8% #8B $$1)+D!#F
 #8 " % '(@-(@AA 2!4	&.EiPVFW.X+*A*G*G	RXHY*Z' 5II 2FF>?R>ST ) #'(<-6t_%.v%6% 0C
 
< VH%%k ! +")1==DDjRc#K (G{Y_'`$**+ % "N%B !  ?	&@QSV _I2Q!3/L (' #"'(5-6t_%.v%6%	 	sO   	F 0G G$G"G'AG, 
G&/GG,
H:69H5/H:5H:c                  > 0 nT(       a  TR                   R                  5       n/ nU R                   H^  n[        U[        5      (       a  M  [        U[
        5      (       d  M1  UR                  U;  d  MC  UR                  UR                  5        M`     U(       a-  [        UR                  5       5      nSU SU S3n[        U5      e[        U R                  [        5      (       aV  [        U R                  5      (       a  [        U R                  R                   S9nO*[#        U R                  R                   S9nOU R                  n[%        U R                  5      n[        U["        5      (       a:  TR'                  5        Vs/ s H  oR(                  PM     n	nUR+                  U	5        [        U[        5      (       a=  UR-                  5       n
U R                  R.                  " U4SS0U
DU R0                  D6U4$ [        U["        5      (       a~  UR2                   H.  nUR                  T;  d  M  SUR                   S3n[        U5      e   T(       a  S	OU R4                  nU R                  R.                  " U4S
U0U R0                  D6U4$ U(       a5  U R                  R.                  " U4S
U R4                  0U R0                  D6S4$ U R                  R6                  " S0 U R0                  D6S4$ s  snf )a  Get the model with appropriate tool bindings.

Performs auto-detection of strategy if needed based on model capabilities.

Args:
    request: The model request containing model, tools, and response format.

Returns:
    Tuple of `(bound_model, effective_response_format)` where
    `effective_response_format` is the actual strategy used (may differ from
    initial if auto-detected).
z(Middleware returned unknown tool names: z

Available client-side tools: aZ  

To fix this issue:
1. Ensure the tools are passed to create_agent() via the 'tools' parameter
2. If using custom middleware with tools, ensure they're registered via middleware.tools attribute
3. Verify that tool names in ModelRequest.tools match the actual tool.name values
Note: Built-in provider tools (dict format) can be added dynamically.r   strictTzToolStrategy specifies tool 'zP' which wasn't declared in the original response format when creating the agent.r   tool_choiceNr`   )tools_by_namecopyr   r@   dictr   r   appendsortedkeys
ValueErrorr   r(   r   r   r+   r   r0   r   valuestoolextendto_model_kwargs
bind_toolsmodel_settingsschema_specsr  bind)rJ   available_tools_by_nameunknown_tool_namestavailable_tool_namesmsgr   final_toolsinfostructured_toolskwargsr   r  r  	tool_nodes                rA   _get_bound_model&create_agent.<locals>._get_bound_model  s     #%&/&=&=&B&B&D#  A!T""!X&&1669P+P"))!&&1  #)*A*F*F*H#I :;M:N O00D/E FX	X  S/! g--|<<*7==99,<GD[D[DbDb,c) -9@W@W@^@^,_) )0(?(?%
 7==)/>>6M6T6T6VW6Vd		6VW/0 /1ABB.>>@F(((,06:A:P:P *	  />> 0<<77"997y AC C 
 %S/) = $;%@S@SK((-8<C<R<R *	  ((-4-@-@DKDZDZ 	  }}!!;G$:$:;TAA_  Xs   K7c                   > T" U 5      u  pU R                   nU R                  (       a  [        U R                  5      /UQnUR                  U5      nT	" XB5      nUS   nUR	                  S5      n[        UUS9$ )zExecute model and return response.

This is the core model execution logic wrapped by `wrap_model_call` handlers.
Raises any exceptions that occur during model invocation.
r   r?   r=   )r   r   r   invokegetr"   
rJ   model_r   r   r   handled_outputmessages_listr?   r&  r  s
           rA   _execute_model_sync)create_agent.<locals>._execute_model_sync
  s     -=W,E)##  %g&;&;<HxHHx( .fP&z2,001FG  3
 	
rC   c                   > [        TTT	TU S   SU US9nT
c	  T" U5      nO	T
" UT5      nSUR                  0nUR                  b  UR                  US'   U$ )zASync model request handler with sequential middleware processing.r   Nr   r   r   r   r   r  stateruntimer?   r!   r>   r?   )r3  r4  rJ   responsestate_updatesr/  default_toolsinitial_response_formatr   r   wrap_model_call_handlers        rA   
model_node create_agent.<locals>.model_node"  s~    '3:&	
 #**73H /w8KLH $X__5''33;3O3OM/0rC   c                  >#    T" U 5      u  pU R                   nU R                  (       a  [        U R                  5      /UQnUR                  U5      I Sh  vN nT	" XB5      nUS   nUR	                  S5      n[        UUS9$  N,7f)zExecute model asynchronously and return response.

This is the core async model execution logic wrapped by `wrap_model_call`
handlers.

Raises any exceptions that occur during model invocation.
Nr   r?   r=   )r   r   r   ainvoker*  r"   r+  s
           rA   _execute_model_async*create_agent.<locals>._execute_model_async=  s      -=W,E)##  %g&;&;<HxHH~~h// .fP&z2,001FG  3
 	
 0s   ABB-Bc                   >#    [        T	TT
TU S   SU US9nTc  T" U5      I Sh  vN nOT" UT5      I Sh  vN nSUR                  0nUR                  b  UR                  US'   U$  NB N27f)zBAsync model request handler with sequential middleware processing.r   Nr2  r?   r5  )r3  r4  rJ   r6  r7  r?  awrap_model_call_handlerr8  r9  r   r   s        rA   amodel_node!create_agent.<locals>.amodel_nodeW  s     '3:&	
 $+1'::H 6g?STTH $X__5''33;3O3OM/0 ; Us   "A,A(A,A*1A,*A,r   Ftracez.before_agent)r   z.before_modelz.after_modelz.after_agentr   rd   c              3  8   #    U  H  oR                   v   M     g 7frG   )return_direct)r   r  s     rA   r   create_agent.<locals>.<genexpr>  s     P/Ot""/Os   )r%  model_destinationr  end_destination)rJ  r  rK  rJ  rK  after_model)r   default_destinationrJ  rK  can_jump_tobefore_agentbefore_modelrE   after_agent)r   r   r   r   r   r   r   recursion_limiti'  )r   r   r   zResponseFormat | NonerY   dict[str, Any])rJ   r!   rY   z&tuple[Runnable, ResponseFormat | None])rJ   r!   rY   r"   )r3  r   r4  zRuntime[ContextT]rY   rT  )<r@   r   r1   r0   r+   r(   r   r  r*   r   r  r   r   r   r   r   r   r   r   r  r   r   r  r  rl   rP  abefore_agentrQ  abefore_modelrM  aafter_modelrR  aafter_agentwrap_model_callawrap_model_callrp   r   r   r   addr   r   add_noder   r   add_edger   r   r  add_conditional_edges_make_tools_to_model_edge_make_model_to_tools_edge_make_model_to_model_edge_add_middleware_edger   	itertoolspairwiserangecompilewith_config)Lr   r   r   r   r   r   r   r   r   r   r   r   r   r   tool_strategy_for_setupresponse_schemastructured_tool_infomr  middleware_toolsmiddleware_w_wrap_tool_callwrap_tool_call_wrapperr   middleware_w_awrap_tool_callawrap_tool_call_wrapperasync_wrappersbuilt_in_toolsregular_toolsavailable_toolsmiddleware_w_before_agentmiddleware_w_before_modelmiddleware_w_after_modelmiddleware_w_after_agentmiddleware_w_wrap_model_callmiddleware_w_awrap_model_callsync_handlersasync_handlersstate_schemas
base_stateresolved_state_schemar   r   graphr;  rC  sync_before_agentasync_before_agentbefore_agent_nodesync_beforeasync_beforebefore_node
sync_afterasync_after
after_nodesync_after_agentasync_after_agentafter_agent_node
entry_nodeloop_entry_nodeloop_exit_node	exit_nodetools_to_model_destinationsmodel_to_tools_destinationsm1m2idxr?  r/  r&  r  rB  r8  r9  r  r%  r:  sL   ` `                                                               @@@@@@@@@@rA   create_agentr    sd   t %& } "&	Ol4D%E	F	F"1	O\	2	2"1 #/o"F 48)<88".6M6T6T"U	+\	:	:"9<>6CCO#4#E#Eo#V FZ#$8$=$=$B$BC  D $.O:awq'27N!7N:O #A;;%%_-K-KK;;&&o.M.MM 	
   # "".IJ.IA$$.IJ!:8!D $A;;&&o.M.MM;;%%_-K-KK 	
 ! $ ##5QR5Q!++5QR"A."Q "&I!&>A*Q*=aN> %A1Z4-@QMA '6O  	!13	
   Y44;;=>O^, 
+
1
+,J? 7?
 !A;;##?+G+GG;;$$O,I,II 	
  ! !A;;##?+G+GG;;$$O,I,II 	
  !  A;;""/*E*EE;;##?+G+GG 	
     A;;""/*E*EE;;##?+G+GG 	
    $A;;&&o.M.MM;;''/O/OO 	
 ! $ %A;;''/O/OO;;&&o.M.MM 	
 " % ##4PQ4Pq**4PQ"<]"K  $$6ST6S!,,6ST#CN#S 8BC
1
MC!-!9zJj!+M=$O"=-IL#M>8LM
 	*!#%		 
g&g&6Kg&	g&RpB pBd
 
0 6
 
4 8 
NN7,ZERS w	* KK$$O,H,HH{{((0M0MM ;;++?3O3OO   ;;,,O4Q4QQ  
 !11BDV^c dNN66(-(*;J_  
 KK$$O,H,HH{{((0M0MM ;;++?3O3OO   ;;,,O4Q4QQ  
 +;ERKNN66(-(+DY  
 KK##?+F+FF{{''/K/KK ;;**/2M2MM   ;;++?3O3OO  
 **kOJNNaffX\2JMbNc KK##?+F+FF{{''/K/KK ;;**/2M2MM   ;;++?3O3OO  
  00@BS[`aNN66(,')9H]  _ h !1!499:-H
	"1!499:-H

 !6q9>>?}M!  4Q7<<=\J   /3889F			NN5*% (7&7#Py/F/F/M/M/OPPP&'..y9##)'&5,C$-	  (	
( (/	&:#n7'..?##)&5,C$-
  (	
 
$	%	)##)&5$-  i(
	
 
7	"~y1 	,Q/445\B )-%()A!)DmT	
 !(()BCFB y.')wwi}$="1 ),R@ D 	-b1667}E /-%()B2)FW	
 !(()BCFB y.')wwi}$="1 ),R@ D 	-b1667}E '-%()B2)FW	
  w#;B#?#D#D"E\ RS56:ArBC)#.B)#'2B y-')wwi|$<"1 ),R? C  56:ArBC)#.B)#'2B y-')wwi|$<"1 ),R? C 	,Q/445\B #-%()A!)DmT	
 ==!)'   k$f-./K P
# K$ S ?A4 ,!!  $% R U  Ds   	!y.1Ay4y4y9Ay>y>.zz4z zz z5AzzAz-z9Az!z!Az&1z&=Az+z+Az05z0
z5:z:!z?c               2    U S:X  a  U$ U S:X  a  U$ U S:X  a  gg )Nr   endr   r`   )jump_torJ  rK  s      rA   _resolve_jumpr    s.     '  %'rC   c                   [        [        U 5      S-
  SS5       H,  n[        X   [        5      (       d  M  Un[	        SX   5      n  O   U WS-   S   Vs/ s H  n[        U[
        5      (       d  M  UPM     nnWU4$ s  snf )NrE   rd   r   )re  rl   r@   r   r   r   )r   ilast_ai_indexlast_ai_messagerk  r  s         rA    _fetch_last_ai_and_tool_messagesr    s     3x=1$b"-hk9--M";<O	 . !)):)< =\ =1A{A[Q =M\M)) ]s   A=1A=c                (   ^ ^^     SUU U4S jjnU$ )Nc                  > U R                  S5      =n(       a  [        UT
T	S9$ [        U S   5      u  p#U Vs/ s H  oDR                  PM     nn[	        UR
                  5      S:X  a  T	$ UR
                   Vs/ s H  nUS   U;  d  M  US   T;  d  M  UPM     nnU(       a&  U Vs/ s H  n[        S[        SUU S	95      PM     sn$ S
U ;   a  T	$ T
$ s  snf s  snf s  snf )Nr  rL  r   r   r   r   r   tool_call_with_context)__typer  r3  r?   )r*  r  r  r   rl   r   r   r   )r3  r  r  r  rk  tool_message_idscpending_tool_callsr  rK  rJ  r  s            rA   model_to_tools1_make_model_to_tools_edge.<locals>.model_to_tools  s+    ii	**7* "3 /  *J%PZJ[)\&4ABMqNNMB ))*a/"" %//
/w.. 34V9D[3[ / 	 
  "4
 "4I '7"+# "4
 
 !E)"" ! C C

s   C9C
CC(Cr3  rT  rY   zstr | list[Send] | Noner`   )rJ  r  rK  r  s   ``` rA   r`  r`    s&    -!-!	 -! -!^ rC   c                $   ^ ^     SUU 4S jjnU$ )Nc                ^   > U R                  S5      =n(       a  [        UTTS9$ SU ;   a  T$ T$ )Nr  rL  r?   )r*  r  )r3  r  rK  rJ  s     rA   model_to_model1_make_model_to_model_edge.<locals>.model_to_model  sG     ii	**7* "3 /  !E)"" ! rC   r  r`   )rJ  rK  r  s   `` rA   ra  ra    s%    
!!	 ! !& rC   c                $   ^ ^^^ SUUUU 4S jjnU$ )Nc                  > [        U S   5      u  pUR                   Vs/ s H  o3S   TR                  ;   d  M  UPM     nnU(       a  [        U4S jU 5       5      (       a  T$ [	        U4S jU 5       5      (       a  T$ T$ s  snf )Nr   r   c              3  \   >#    U  H!  nTR                   US       R                  v   M#     g7f)r   N)r  rH  )r   r  r%  s     rA   r   D_make_tools_to_model_edge.<locals>.tools_to_model.<locals>.<genexpr>  s*      *
F\I##AfI.<<F\s   ),c              3  @   >#    U  H  oR                   T;   v   M     g 7frG   )r   )r   r  r  s     rA   r   r    s     H-Qvv00-s   )r  r   r  allr   )	r3  r  r  r  client_side_tool_callsrK  rJ  r  r%  s	        rA   tools_to_model1_make_tools_to_model_edge.<locals>.tools_to_model  s    )I%PZJ[)\&
 '11"
1!vY)BYBY5YA1 	 "
 "c *
F\*
 '
 '
 #" H-HHH""
 ! "
s
   BB)r3  rT  rY   
str | Noner`   )r%  rJ  r  rK  r  s   ```` rA   r_  r_    s    ! !, rC   c               $  ^^^ U(       at  SUUU4S jjnT/nSU;   a  UR                  T5        SU;   a  UR                  S5        SU;   a  UT:w  a  UR                  T5        U R                  U[        USS9U5        gU R                  UT5        g)	a  Add an edge to the graph for a middleware node.

Args:
    graph: The graph to add the edge to.
    name: The name of the middleware node.
    default_destination: The default destination for the edge.
    model_destination: The destination for the edge to the model.
    end_destination: The destination for the edge to the end.
    can_jump_to: The conditionally jumpable destinations for the edge.
c                J   > [        U R                  S5      TTS9=(       d    T$ )Nr  rL  )r  r*  )r3  rN  rK  rJ  s    rA   	jump_edge'_add_middleware_edge.<locals>.jump_edge;  s,    IIi(&7$3 '
 'rC   r  r   r   FrE  N)r3  rT  rY   r   )r  r^  r   r]  )r  r   rN  rJ  rK  rO  r  destinationss     ```   rA   rb  rb  $  s    * 	 	 ,,K0k!(k!d.?&? 12##D*:9E*RT`a 	t01rC   r  )r>   zModelResponse | AIMessagerY   r"   )ro   zfSequence[Callable[[ModelRequest, Callable[[ModelRequest], ModelResponse]], ModelResponse | AIMessage]]rY   zWCallable[[ModelRequest, Callable[[ModelRequest], ModelResponse]], ModelResponse] | None)ro   z|Sequence[Callable[[ModelRequest, Callable[[ModelRequest], Awaitable[ModelResponse]]], Awaitable[ModelResponse | AIMessage]]]rY   zmCallable[[ModelRequest, Callable[[ModelRequest], Awaitable[ModelResponse]]], Awaitable[ModelResponse]] | NonerG   )r   z	set[type]r   r   r   r  rY   r   )r   r   rY   r   )r   zAgentMiddleware[Any, Any]r   r   rY   zlist[JumpTo])r   str | BaseChatModelrY   bool)r   r   r   r-   rY   ztuple[bool, str])r   zSequence[ToolCallWrapper]rY   zToolCallWrapper | None)r   zSequence[Callable[[ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]], Awaitable[ToolMessage | Command]]]rY   zCallable[[ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]]], Awaitable[ToolMessage | Command]] | None)r   r  r   z5Sequence[BaseTool | Callable | dict[str, Any]] | Noner   r  r   z.Sequence[AgentMiddleware[StateT_co, ContextT]]r   z2ResponseFormat[ResponseT] | type[ResponseT] | Noner   z"type[AgentState[ResponseT]] | Noner   ztype[ContextT] | Noner   zCheckpointer | Noner   zBaseStore | Noner   list[str] | Noner   r  r   r  r   r  r   zBaseCache | NonerY   zcCompiledStateGraph[AgentState[ResponseT], ContextT, _InputAgentState, _OutputAgentState[ResponseT]])r  zJumpTo | NonerJ  r   rK  r   rY   r  )r   zlist[AnyMessage]rY   z#tuple[AIMessage, list[ToolMessage]])rJ  r   r  dict[str, OutputToolBinding]rK  r   rY   3Callable[[dict[str, Any]], str | list[Send] | None])rJ  r   rK  r   rY   r  )
r%  r   rJ  r   r  r  rK  r   rY   z&Callable[[dict[str, Any]], str | None])r  z[StateGraph[AgentState[ResponseT], ContextT, _InputAgentState, _OutputAgentState[ResponseT]]r   r   rN  r   rJ  r   rK  r   rO  zlist[JumpTo] | NonerY   None)b__doc__
__future__r   rc  typingr   r   r   r   r   r	   r
   *langchain_core.language_models.chat_modelsr   langchain_core.messagesr   r   r   r   langchain_core.toolsr   langgraph._internal._runnabler   langgraph.constantsr   r   langgraph.graph.stater   langgraph.prebuilt.tool_noder   r   langgraph.runtimer   langgraph.typesr   r   langgraph.typingr   typing_extensionsr   r   r   !langchain.agents.middleware.typesr   r   r    r!   r"   r#   r$   r%   r&   r'   "langchain.agents.structured_outputr(   r)   r*   r+   r,   r-   r.   r/   r0   langchain.chat_modelsr1   collections.abcr2   r3   r4   langchain_core.runnablesr5   langgraph.cache.baser6   r7   langgraph.store.baser8   r9   r:   r;   r   rB   rp   r   r   r   r   r   r   r   r   r  r  r  r`  ra  r_  rb  __all__r`   rC   rA   <module>r     s%   @ "    E U U ) : * , F % ) % > >  
 
 
 2==1.8.,R#O  mmm`RRRj3> F.# <+'++\===D DHL/ !%ACJN7;,0(,")-(,"L/L/@L/ 	L/
 ?L/ HL/ 5L/ *L/ &L/ L/ 'L/ &L/ L/ L/ L/ !L/^  	
 **(* 55 :5 	5
 95p  9	6  :	
  ,@-2-2
 -2 -2 -2 -2 %-2 
-2b rC   