
    fi	                   h   d Z ddlmZ ddlZddlmZmZmZmZm	Z	m
Z
mZ ddlmZ ddlmZmZmZmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$m%Z% ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z: ddl;m<Z< er>ddl=m>Z>m?Z?m@Z@ ddlAmBZBmCZC ddlDmEZE ddlmFZF ddlGmHZH ddlImJZJ ddlmKZK ddlLmMZM ddl&mNZNmOZO dZPdj                         ZRg dZSd2dZT	 	 	 	 d3dZU	 	 	 	 d4dZVd5d6d ZWd7d!ZXd8d"ZY	 d5	 	 	 	 	 d9d#ZZ	 	 	 	 	 	 d:d$Z[	 	 	 	 d;d%Z\	 	 	 	 d<d&Z]	 d5dd'dddddddd(ddd)	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d=d*Z^	 	 	 	 	 	 	 	 d>d+Z_	 	 	 	 d?d,Z`	 	 	 	 	 	 	 	 d@d-Za	 	 	 	 	 	 dAd.Zb	 	 	 	 	 	 	 	 	 	 dBd/Zc	 	 	 	 	 	 	 	 	 	 	 	 	 	 dCd0Zdd1gZey)Dz: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)CommandSend)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RunnableConfig)	BaseCache)CompiledStateGraph)Runtime)	BaseStore)Checkpointer)ContextT)ToolCallRequestToolCallWrapperz)Error: {error}
 Please fix your mistakes.a  
Middleware added tools that the agent doesn't know how to execute.

Unknown tools: {unknown_tool_names}
Registered tools: {available_tool_names}

This happens when middleware modifies `request.tools` in `wrap_model_call` to include
tools that weren't passed to `create_agent()`.

How to fix this:

Option 1: Register tools at agent creation (recommended for most cases)
    Pass the tools to `create_agent(tools=[...])` or set them on `middleware.tools`.
    This makes tools available for every agent invocation.

Option 2: Handle dynamic tools in middleware (for tools created at runtime)
    Implement `wrap_tool_call` to execute tools that are added dynamically:

    class MyMiddleware(AgentMiddleware):
        def wrap_tool_call(self, request, handler):
            if request.tool_call["name"] == "dynamic_tool":
                # Execute the dynamic tool yourself or override with tool instance
                return handler(request.override(tool=my_dynamic_tool))
            return handler(request)
)grokzgpt-5zgpt-4.1zgpt-4ozgpt-osszo3-prozo3-minic                B    t        | t              rt        | gd      S | S )z3Normalize middleware return value to ModelResponse.Nresultstructured_response)
isinstancer   r    )r@   s    b/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/langchain/agents/factory.py_normalize_to_model_responserD   i   s     &)$VH$GGM    c                    | syt        |       dk(  r| d   	 	 	 	 	 	 dfd}|S 	 	 	 	 	 	 d	d}| d   t        | dd       D ]  } ||       	 	 	 	 	 	 dfd}|S )
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        |      S NrD   requesthandlerr@   single_handlers      rC   normalized_singlez5_chain_model_call_handlers.<locals>.normalized_single   s     $GW5F/77rE   c                $     	 	 	 	 	 	 d fd}|S )z-Compose two handlers where outer wraps inner.c                <    dfd} | |      }t        |      S )Nc                ,     |       }t        |      S rI   rJ   reqinner_resultrM   inners     rC   inner_handlerzX_chain_model_call_handlers.<locals>.compose_two.<locals>.composed.<locals>.inner_handler   s    $S'23LAArE   rT   r   returnr    rJ   rL   rM   rW   outer_resultrV   outers    `  rC   composedzA_chain_model_call_handlers.<locals>.compose_two.<locals>.composed   s"    
B
 !-8L/==rE   rL   r   rM   z'Callable[[ModelRequest], ModelResponse]rY   r     r\   rV   r]   s   `` rC   compose_twoz/_chain_model_call_handlers.<locals>.compose_two   s)    	>!	><	> 	> rE   c                ,     | |      }t        |      S rI   rJ   rL   rM   final_resultr@   s      rC   final_normalizedz4_chain_model_call_handlers.<locals>.final_normalized   s    
 gw/+L99rE   r^   )r\   \Callable[[ModelRequest, Callable[[ModelRequest], ModelResponse]], ModelResponse | AIMessage]rV   rg   rY   zPCallable[[ModelRequest, Callable[[ModelRequest], ModelResponse]], ModelResponse]lenreversedhandlersrO   ra   rM   rf   r@   rN   s        @@rC   _chain_model_call_handlersrm   p   s    f 
8}!!	8!	8<	8 	8 ! 



> b\FHSbM* .Wf-.::8: 
: rE   c                    | syt        |       dk(  r| d   	 	 	 	 	 	 dfd}|S 	 	 	 	 	 	 d	d}| d   t        | dd       D ]  } ||       	 	 	 	 	 	 dfd}|S )
a  Compose 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.
    NrG   r   c                H   K    | |       d {   }t        |      S 7 wrI   rJ   rK   s      rC   rO   z;_chain_async_model_call_handlers.<locals>.normalized_single  s(      *'7;;F/77 <   " "c                $     	 	 	 	 	 	 d fd}|S )z3Compose two async handlers where outer wraps inner.c                X   K   dfd} | |       d {   }t        |      S 7 w)Nc                H   K    |        d {   }t        |      S 7 wrI   rJ   rS   s     rC   rW   z^_chain_async_model_call_handlers.<locals>.compose_two.<locals>.composed.<locals>.inner_handler  s&     %*3%883LAA  9rp   rX   rJ   rZ   s    `  rC   r]   zG_chain_async_model_call_handlers.<locals>.compose_two.<locals>.composed  s.     
B
 "'w!>>L/== ?s   *(*rL   r   rM   z2Callable[[ModelRequest], Awaitable[ModelResponse]]rY   r    r_   r`   s   `` rC   ra   z5_chain_async_model_call_handlers.<locals>.compose_two
  s)    	>!	>G	> 	> rE   rb   c                H   K    | |       d {   }t        |      S 7 wrI   rJ   rd   s      rC   rf   z:_chain_async_model_call_handlers.<locals>.final_normalized.  s(     
 $GW55+L99 6rp   rt   )r\   rCallable[[ModelRequest, Callable[[ModelRequest], Awaitable[ModelResponse]]], Awaitable[ModelResponse | AIMessage]]rV   rv   rY   zfCallable[[ModelRequest, Callable[[ModelRequest], Awaitable[ModelResponse]]], Awaitable[ModelResponse]]rh   rk   s        @@rC    _chain_async_model_call_handlersrw      s    0 
8}!!	8!	8G	8 	8 ! 



> b\FHSbM* .Wf-.::C: 
: rE   c                    i }| D ]h  }t        |d      }|j                         D ]F  \  }}d}|r5t        |      }	|	D ]%  }
t        |
t              st        |
|      du s#d} n |rB|||<   H j t        ||      S )ai  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'`)

    Returns:
        Merged schema as `TypedDict`
    T)include_extrasF)r
   items_extract_metadatarB   r!   getattrr   )schemasschema_name	omit_flagall_annotationsschemahints
field_name
field_typeshould_omitmetadatametas              rC   _resolve_schemar   9  s     O 9vd;&+kkm 	9"J
K,Z8$ D!$7GD)<TX\<\&*
 .8
+	99" [/22rE   c                    t        |       t        t        hv r8t        |       d   }t        |      t        u rt        t        |      dd       S g S t        |       t        u rt        t        |       dd       S g S )z_Extract metadata from a field type, handling `Required`/`NotRequired` and `Annotated` wrappers.r   rG   N)r	   r   r   r   r   list)type_
inner_types     rC   r{   r{   [  sy     %X{33e_Q'
j!Y.,QR011 I 
E	i	'HUOAB'((IrE   c                *   t        t        |d      }t        t        d| d      }t        | j                  |d      }|r||urt        |d      r|j                  S t        | j                  d| d      }|r||urt        |d      r|j                  S g S )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         rC   _get_can_jump_tor   j  s     	4@1YK$G *..	4@K//K!23*** ://1YK$GL 11L"34+++IrE   c                d   dt        | t              r| nt        | t              rot        | dd      xs t        | dd      xs t        | dd      | j                  }|6|j                  d      r%|r"t        t              rdj                         v syrt        fd	t        D              S d
S )a  Check if a model supports provider-specific structured output.

    Args:
        model: Model name string or `BaseChatModel` instance.
        tools: Optional list of tools provided to the agent.

            Needed because some models don't support structured output together with tool calling.

    Returns:
        `True` if the model supports provider-specific structured output, `False` otherwise.
    N
model_namemodelmodel_id structured_outputgeminiTc              3  B   K   | ]  }|j                         v   y wrI   )lower).0partr   s     rC   	<genexpr>z._supports_provider_strategy.<locals>.<genexpr>  s     Z4DJ$$&&Zs   F)	rB   strr   r|   profilegetr   any&FALLBACK_MODELS_WITH_STRUCTURED_OUTPUT)r   toolsmodel_profiler   s      @rC   _supports_provider_strategyr     s     "J%
	E=	)E<. .ugt,.uj"- 	
 %!!"56 z*c:x:K[K[K]?]  	Z3YZZ rE   c                    t        |t              sy|j                  }|du ry|du r!dt        j	                  t                     fS t        |t
              rd|fS t        |t              r>t        |t              r-t         |      r!dt        j	                  t                     fS yt        |t              r6t         fd|D              r!dt        j	                  t                     fS yd |       fS )zWHandle structured output error.

    Returns `(should_retry, retry_tool_message)`.
    )Fr   FT)errorc              3  6   K   | ]  }t        |        y wrI   )rB   )r   exc_type	exceptions     rC   r   z2_handle_structured_output_error.<locals>.<genexpr>  s     M8z)X.Ms   )rB   r.   handle_errors STRUCTURED_OUTPUT_ERROR_TEMPLATEformatr   type
issubclass	Exceptiontupler   )r   response_formatr   s   `  rC   _handle_structured_output_errorr     s     o|4#11M5<<3y><RRR-%]""-&mY/Jy-4X9@@s9~@VVV-'M}MM9@@s9~@VVVy)))rE   c                |    | syt        |       dk(  r| d   S dd}| d   }t        | dd       D ]  } |||      } |S )a  Compose wrappers into middleware stack (first = outermost).

    Args:
        wrappers: Wrappers in middleware order.

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

    Example:
        ```python
        wrapper = _chain_tool_call_wrappers([auth, cache, retry])
        # Request flows: auth -> cache -> retry -> tool
        # Response flows: tool -> retry -> cache -> auth
        ```
    NrG   r   c                $     	 	 	 	 	 	 d fd}|S )z-Compose two wrappers where outer wraps inner.c                &    dfd} | |      S )Nc                     |       S rI   r_   rT   executerV   s    rC   
call_innerzT_chain_tool_call_wrappers.<locals>.compose_two.<locals>.composed.<locals>.call_inner  s    S'**rE   rT   r;   rY   ToolMessage | Command[Any]r_   rL   r   r   rV   r\   s    ` rC   r]   z@_chain_tool_call_wrappers.<locals>.compose_two.<locals>.composed  s    
+ *--rE   )rL   r;   r   z7Callable[[ToolCallRequest], ToolMessage | Command[Any]]rY   r   r_   r`   s   `` rC   ra   z._chain_tool_call_wrappers.<locals>.compose_two  s)    		.$		.L		. (		. rE   rb   )r\   r<   rV   r<   rY   r<   rh   wrappersra   r@   wrappers       rC   _chain_tool_call_wrappersr     s]    $ 
8}{" b\FHSbM* .Wf-. MrE   c                    | syt        |       dk(  r| d   S 	 	 	 	 	 	 dd}| d   }t        | dd       D ]  } |||      } |S )zCompose async wrappers into middleware stack (first = outermost).

    Args:
        wrappers: Async wrappers in middleware order.

    Returns:
        Composed async wrapper, or `None` if empty.
    NrG   r   c                $     	 	 	 	 	 	 d fd}|S )z3Compose two async wrappers where outer wraps inner.c                B   K   dfd} | |       d {   S 7 w)Nc                2   K    |        d {   S 7 wrI   r_   r   s    rC   r   zZ_chain_async_tool_call_wrappers.<locals>.compose_two.<locals>.composed.<locals>.call_inner3  s     "30000s   r   r_   r   s    ` rC   r]   zF_chain_async_tool_call_wrappers.<locals>.compose_two.<locals>.composed.  s!     
1 w
3333s   )rL   r;   r   zBCallable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]rY   r   r_   r`   s   `` rC   ra   z4_chain_async_tool_call_wrappers.<locals>.compose_two  s)    		4$		4W		4 (		4 rE   rb   )r\   Callable[[ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]], Awaitable[ToolMessage | Command[Any]]]rV   r   rY   r   rh   r   s       rC   _chain_async_tool_call_wrappersr     s{    , 
8}{



: b\FHSbM* .Wf-. MrE   r_   F)system_promptr   r   state_schemacontext_schemacheckpointerstoreinterrupt_beforeinterrupt_afterdebugnamecachec                  ABCDEFGHIJKLMN t         t              rt                dJ|t        |t              r|Jnt        |      J|g }|dHn8t        |t        t
        f      r|Hnt        |t              r|Hnt        |      HdLt        Ht              rt	        Hj                        Lnt        Ht              rHLi ILr?Lj                  D ]0  }t        j                  |      }|I|j                  j                  <   2 |D cg c]  }t        |dg       D ]  }|  }}}|D cg c]P  }|j                  j                  t         j                  us&|j                  j"                  t         j"                  ur|R }}dN|r$|D cg c]  }|j                   }}t%        |      N|D cg c]P  }|j                  j"                  t         j"                  us&|j                  j                  t         j                  ur|R }}dF|r$|D cg c]  }|j"                   }}t'        |      FdK|D cg c]  }t        |t(              s| }}|D cg c]  }t        |t(              r| }}||z   }|sNsFrt+        |NF      ndKKr't-        Kj.                  j1                               |z   Gnt-        |      Gt3        |D ch c]  }|j                   c}      t3        |      k7  rd}t5        |      |D cg c]P  }|j                  j6                  t         j6                  us&|j                  j8                  t         j8                  ur|R }}|D cg c]P  }|j                  j:                  t         j:                  us&|j                  j<                  t         j<                  ur|R }}|D cg c]P  }|j                  j>                  t         j>                  us&|j                  j@                  t         j@                  ur|R }}|D cg c]P  }|j                  jB                  t         jB                  us&|j                  jD                  t         jD                  ur|R }}|D cg c]P  }|j                  jF                  t         jF                  us&|j                  jH                  t         jH                  ur|R }}|D cg c]P  }|j                  jH                  t         jH                  us&|j                  jF                  t         jF                  ur|R } }dM|r$|D cg c]  }|jF                   }!}tK        |!      MdE| r$| D cg c]  }|jH                   }"}tM        |"      E|D ch c]  }|jN                   }#}||ntP        }$|#jS                  |$       tU        |#dd      }%tU        |#dd	      }&tU        |#d
d      }'tW        |%|&|'|      }(	 	 	 	 	 	 d,IfdD	 	 	 	 d-FHIKLNfdCd.CDfdBd/BGH JMfd})d.CDfdAd/AEGH Jfd}*|(jY                  dt[        |)|*d             K|(jY                  dK       |D ]  }|j                  j6                  t         j6                  us&|j                  j8                  t         j8                  ur|j                  j6                  t         j6                  ur|j6                  nd}+|j                  j8                  t         j8                  ur|j8                  nd},t[        |+|,d      }-|(jY                  |j                   d|-|%       |j                  j:                  t         j:                  us&|j                  j<                  t         j<                  ur|j                  j:                  t         j:                  ur|j:                  nd}.|j                  j<                  t         j<                  ur|j<                  nd}/t[        |.|/d      }0|(jY                  |j                   d|0|%       |j                  j>                  t         j>                  us&|j                  j@                  t         j@                  ur|j                  j>                  t         j>                  ur|j>                  nd}1|j                  j@                  t         j@                  ur|j@                  nd}2t[        |1|2d      }3|(jY                  |j                   d|3|%       |j                  jB                  t         jB                  us(|j                  jD                  t         jD                  us|j                  jB                  t         jB                  ur|jB                  nd}4|j                  jD                  t         jD                  ur|jD                  nd}5t[        |4|5d      }6|(jY                  |j                   d|6|%        |r|d   j                   d}7n|r|d   j                   d}7nd}7|r|d   j                   d}8nd}8|r|d   j                   d}9nd}9|r|d   j                   d}:nt\        }:|(j_                  t`        |7       K|8g};tc        d Kj.                  j1                         D              sIr|;je                  |:       |(jg                  dt[        ti        K|8I|:      d      |;       d|:g}<|s|9dk7  r|<je                  |8       |(jg                  |9t[        tk        |8I|:      d      |<       nt3        I      dkD  r,|(jg                  |9t[        tm        |8|:       d      |8|:g       nF|9dk(  r|(j_                  |9|:       n.to        |(|d   j                   d|:|8|:tq        |d   d!      "       |rts        jt                  |      D ]:  \  }=}>to        |(|=j                   d|>j                   d|8|:tq        |=d#      "       < to        |(|d   j                   d|8|8|:tq        |d   d#      "       |rts        jt                  |      D ]:  \  }=}>to        |(|=j                   d|>j                   d|8|:tq        |=d$      "       < to        |(|d   j                   dd|8|:tq        |d   d$      "       |r|(j_                  d|d   j                   d       tw        t3        |      d%z
  dd      D ]D  }?||?   }=||?d%z
     }>to        |(|=j                   d|>j                   d|8|:tq        |=d!      "       F |rtw        t3        |      d%z
  dd      D ]D  }?||?   }=||?d%z
     }>to        |(|=j                   d|>j                   d|8|:tq        |=d&      "       F to        |(|d   j                   dt\        |8|:tq        |d   d&      "       d'd(i}@rd)i@d*<   |(jy                  |||	|
||+      j{                  @      S c c}}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w )0a7  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
            [LangChain 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)].

            !!! tip ""

                See the [Models](https://docs.langchain.com/oss/python/langchain/models)
                docs for more information.
        tools: A list of tools, `dict`, or `Callable`.

            If `None` or an empty list, the agent will consist of a model node without a
            tool calling loop.


            !!! tip ""

                See the [Tools](https://docs.langchain.com/oss/python/langchain/tools)
                docs for more information.
        system_prompt: An optional system prompt for the LLM.

            Can be a `str` (which will be converted to a `SystemMessage`) or a
            `SystemMessage` instance directly. The system message is added to the
            beginning of the message list when calling the model.
        middleware: A sequence of middleware instances to apply to the agent.

            Middleware can intercept and modify agent behavior at various stages.

            !!! tip ""

                See the [Middleware](https://docs.langchain.com/oss/python/langchain/middleware)
                docs for more information.
        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.

            !!! tip ""

                See the [Structured output](https://docs.langchain.com/oss/python/langchain/structured-output)
                docs for more information.
        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.
        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.

    Raises:
        AssertionError: If duplicate middleware instances are provided.

    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)contentr   r   )r   wrap_tool_callawrap_tool_callz-Please remove duplicate middleware instances.StateSchemaInputSchemainputOutputSchemaoutput)r   input_schemaoutput_schemar   c           	        t        |t              rH| j                  s7t        j                  |j
                        }	 |j                  |       }| g|dS d| giS t        |t              rt        | t              r| j                  r| j                  D cg c]  }|d   v s| }}|rd}	t        |      dkD  rY|D cg c]  }|d   	 }
}t        |
|       }	t        |	|      \  }}|s|	|D cg c]  }t!        ||d   |d   	       }}d| g|iS |d
   }	 |d      }|j                  |d         }|j"                  xs d| }| t!        ||d   |d   	      g|dS d| giS # t        $ r6}t        |j
                  j                  dd      }t        |||       }||d}~ww xY wc c}w c c}w c c}w # t        $ rF}t        |d   ||       }	t        |	|      \  }}|s|	|d| t!        ||d   |d   	      gicY d}~S d}~ww xY w)a  Handle 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).
        )messagesrA   __name__r   Nr   r   rG   id)r   tool_call_idr   r   argszReturning structured response: )rB   r)   
tool_callsr*   from_schema_specschema_specparser   r|   r   r-   r.   r   ri   r'   r   r   tool_message_content)r   effective_response_formatprovider_strategy_bindingrA   excr~   validation_errortcstructured_tool_callsr   
tool_namesshould_retryerror_messagetool_messages	tool_callstructured_tool_bindingr   structured_output_toolss                    rC   _handle_model_outputz*create_agent.<locals>._handle_model_output  s    /1AB$$,C,T,T-99-)	^*C*I*I&*Q' *0I\]])) 0,?69-!! $..%"V*@W2W%! % %:>	,-17L!M"V*!MJ!M >z6 RI2Q!#<3/L- (' #8%  $$1)+D!#F%M % '(@-(@AA 2!4	%.EiPVFW.X+*A*G*G	RXHY*Z' 2FF S<=P<QR ) #'(<-6t_%.v%6% 0C
 
< VH%%i ! 4")1==DDjRc#K (G{TWY_'`$*34 % "N%@ !  ?	&@QSVX^ _I2Q!#<3/L- ('S0 #"'(5-6t_%.v%6%	 	sN   E% F'!F'=F,.F1AF6 %	F$.1FF$6	H?;H :H Hc                   xs }i }rj                   j                         }|sg }| j                  D ]N  }t        |t              rt        |t
              s%|j                  |vs4|j                  |j                         P |r;t        |j                               }t        j                  ||      }t        |      t        | j                  t              rvt        | j                   | j                        r!t#        | j                  j$                        }n@| j                  u r}n-t'        | j                  j$                        }n| j                  }t)        | j                        }t        |t&              r8j+                         D 	cg c]  }	|	j,                   }
}	|j/                  |
       t        |t"              r=|j1                         } | j                   j2                  |fddi|| j4                  |fS t        |t&              ru|j6                  D ]+  }|j                  vsd|j                   d}t        |       rd	n| j8                  } | j                   j2                  |fd
|i| j4                  |fS |r5 | j                   j2                  |fd
| j8                  i| j4                  dfS  | j                   j:                  di | j4                  dfS c c}	w )ar  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).

        Raises:
            ValueError: If middleware returned unknown client-side tool names.
            ValueError: If `ToolStrategy` specifies tools not declared upfront.
        )unknown_tool_namesavailable_tool_names)r   r   NstrictTzToolStrategy specifies tool 'zP' which wasn't declared in the original response format when creating the agent.r   tool_choicer_   )tools_by_namecopyr   rB   dictr   r   appendsortedkeysDYNAMIC_TOOL_ERROR_TEMPLATEr   
ValueErrorr   r&   r   r   r)   r   r.   r   valuestoolextendto_model_kwargs
bind_toolsmodel_settingsschema_specsr  bind)rL   has_wrap_tool_callavailable_tools_by_namer   tr   msgr   final_toolsinfostructured_toolskwargsr   r  awrap_tool_call_wrapperinitial_response_formatr   	tool_nodetool_strategy_for_setupwrap_tool_call_wrappers                 rC   _get_bound_modelz&create_agent.<locals>._get_bound_model  s
   , 4N7N #%&/&=&=&B&B&D# "!#]] 6a&a*qvv=T/T&--aff56 "'-.E.J.J.L'M$188'9)= 9  !o% g--|<*7==N,<GD[D[DbDb,c)''+BB+7 -D),8@W@W@^@^,_) )0(?(?%
 7==)/>6M6T6T6VWd		WW/0 /1AB.>>@F((((,06:A:P:P *	  /> 0<< *77"997y AC C 
 %S/)* $;%@S@SK(((-8<C<R<R *	  (((-4-@-@DKDZDZ 	  "w}}!!;G$:$:;TAA_  Xs   K.c                     |       \  }}| j                   }| j                  r| j                  g|}|j                  |      }
r
|_         	||      }|d   }|j	                  d      }t        ||      S )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   rA   r?   )r   system_messageinvoker   r   r    rL   model_r   r   r   handled_outputmessages_listrA   r   r   r   s           rC   _execute_model_syncz)create_agent.<locals>._execute_model_syncu  s     -=W,E))##!!..::Hx(FK .f6OP&z2,001FG  3
 	
rE   c           
         t        	| d   d| |      }
	 |      }n	 
|      }d|j                  i}|j                  |j                  |d<   |S )zASync model request handler with sequential middleware processing.r   Nr   r   r"  r   r   r  stateruntimerA   r   r@   rA   )r+  r,  rL   responsestate_updatesr(  default_toolsr  r   r"  wrap_model_call_handlers        rC   
model_nodez create_agent.<locals>.model_node  s~    )3:&	
 #**73H /w8KLH $X__5''33;3O3OM/0rE   c                  K    |       \  }}| j                   }| j                  r| j                  g|}|j                  |       d{   }
r
|_         	||      }|d   }|j	                  d      }t        ||      S 7 9w)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   rA   r?   )r   r"  ainvoker   r   r    r$  s           rC   _execute_model_asyncz*create_agent.<locals>._execute_model_async  s      -=W,E))##!!..::H~~h//FK .f6OP&z2,001FG  3
 	
 0s   AB
B:Bc           
        K   t        	
| d   d| |      } |       d{   }n |       d{   }d|j                  i}|j                  |j                  |d<   |S 7 A7 1w)zBAsync model request handler with sequential middleware processing.r   Nr*  rA   r-  )r+  r,  rL   r.  r/  r5  awrap_model_call_handlerr0  r  r   r"  s        rC   amodel_nodez!create_agent.<locals>.amodel_node  s     )3:&	
 $+1'::H 6g?STTH $X__5''33;3O3OM/0 ; Us   $A-A)A-A+0A-+A-r   Ftracez.before_agent)r   z.before_modelz.after_modelz.after_agentr   rb   c              3  4   K   | ]  }|j                     y wrI   )return_direct)r   r  s     rC   r   zcreate_agent.<locals>.<genexpr>`  s     Pt""Ps   )r  model_destinationr   end_destination)r=  r   r>  r=  r>  after_model)r   default_destinationr=  r>  can_jump_tobefore_agentbefore_modelrG   after_agentrecursion_limiti'  lc_agent_namer   )r   r   r   r   r   r   r   )r   r   r   zResponseFormat[Any] | NonerY   dict[str, Any])rL   r   rY   z5tuple[Runnable[Any, Any], ResponseFormat[Any] | None])rL   r   rY   r    )r+  zAgentState[Any]r,  zRuntime[ContextT]rY   rH  )>rB   r   r/   r   r.   r)   r&   r   r  r(   r   r  r   r|   r   r   r   r   r   r   r  r   r   r  r  ri   AssertionErrorrC  abefore_agentrD  abefore_modelr@  aafter_modelrE  aafter_agentwrap_model_callawrap_model_callrm   rw   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)Or   r   r   r   r   r   r   r   r   r   r   r   r   r   response_schemastructured_tool_infomr  middleware_toolsmiddleware_w_wrap_tool_callr   middleware_w_awrap_tool_callasync_wrappersbuilt_in_toolsregular_toolsavailable_toolsr  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   graphr2  r8  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idxconfigr5  r(  r   r   r7  r  r0  r  r   r"  r  r  r1  r  sO   `           `                                                    @@@@@@@@@@@@@@rC   create_agentr  C  s   f %& ,0N m]3*N*=AN } "&	Ol4D%E	F"1	O\	2"1 #/o"F 9=)<8".6M6T6T"U	+\	:"9AC6CC 	[O#4#E#Eo#V FZ#$8$=$=$B$BC	[ $.Oawq'27NO!OOO #;;%%_-K-KK;;&&o.M.MM 	
# # "".IJA$$JJ!:8!D $;;&&o.M.MM;;%%_-K-KK 	
$  $ ##5QR!++RR"A."Q "&I!&>A*Q*=a>N> %A1Z4-@QAMA '6O 48O 	!13	
   Y44;;=>O^, J'qAFF'(C
O;=S!! !;;##?+G+GG;;$$O,I,II 	
! ! !;;##?+G+GG;;$$O,I,II 	
! !  ;;""/*E*EE;;##?+G+GG 	
     ;;""/*E*EE;;##?+G+GG 	
    $;;&&o.M.MM;;''/O/OO 	
$  $ %;;''/O/OO;;&&o.M.MM 	
%! % ##4PQq**QQ"<]"K  $$6ST!,,TT#CN#S 8BC1CMC!-!9zJj!+M=$O"=-IL#M>8LM
 	*!#%		 
f&f&6Pf&	f&PzBzB	>zB zBx
6 6
8 8 
NN7,ZERS w	*  Q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]  _Q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&'..y9##)'&5,C$-	  (	
( (/	&:#n7'..?##)&5,C$-
  (	
 
$	%	)##)&5$-  i(
	
 
7	"~y1 	,Q/445\B )-%()A!)DmT	
 !(()BC 	FB y.')wwi}$="1 ),R@	 	-b1667}E /-%()B2)FW	
 !(()BC 	FB y.')wwi}$="1 ),R@	 	-b1667}E '-%()B2)FW	
  w#;B#?#D#D"E\ RS56:ArB 
	C)#.B)#'2B y-')wwi|$<"1 ),R?
	  56:ArB 
	C)#.B)#'2B y-')wwi|$<"1 ),R?
	 	,Q/445\B #-%()A!)DmT	
 08F-t4z==!)'   k&q P
# K$ S ?A6 (!!  $% R U  Dsz   w95Aw?x8Ax	x=xxx3xxAx"#Ax'>Ax,Ax14Ax6Ax;.y y:y
c               ,    | dk(  r|S | dk(  r|S | dk(  ryy )Nr   endr   r_   )jump_tor=  r>  s      rC   _resolve_jumpr    s.     '  %'rE   c                    t        t        |       dz
  dd      D ](  }t        | |   t              s|}t	        d| |         } n | dz   d  D cg c]  }t        |t
              s| }}|fS c c}w )NrG   rb   r   )rZ  ri   rB   r   r   r   )r   ilast_ai_indexlast_ai_messager_  r   s         rC    _fetch_last_ai_and_tool_messagesr    s     3x=1$b"- hqk9-M";<O	 !)):)< =\1A{A[Q\M\M)) ]s   A/%A/c                $     	 	 	 	 d fd}|S )Nc                   | j                  d      x}rt        |
	      S t        | d         \  }}|D cg c]  }|j                   }}t	        |j
                        dk(  r	S |j
                  D cg c]  }|d   |vr	|d   vr| }}|r&|D cg c]  }t        dt        d|| 	             c}S d
| v r	S 
S c c}w c c}w c c}w )Nr  r?  r   r   r   r   r   tool_call_with_context)__typer   r+  rA   )r   r  r  r   ri   r   r   r   )r+  r  r  r   r_  tool_message_idscpending_tool_callsr   r>  r=  r   s            rC   model_to_toolsz1_make_model_to_tools_edge.<locals>.model_to_tools+  s    ii	**7* "3 /  *J%PZJ[)\&4ABqANNBB ))*a/"" %//
w..1V9D[3[ 
 
  "4
  '7"+#
 
 !E)"" ! C C

s   B>5CCr+  rH  rY   zstr | list[Send] | Noner_   )r=  r   r>  r  s   ``` rC   rU  rU  %  s!    -!-!	 -!^ rE   c                      	 	 	 	 d fd}|S )Nc                V    | j                  d      x}rt        |      S d| v rS S )Nr  r?  rA   )r   r  )r+  r  r>  r=  s     rC   model_to_modelz1_make_model_to_model_edge.<locals>.model_to_modelb  sG     ii	**7* "3 /  !E)"" ! rE   r  r_   )r=  r>  r  s   `` rC   rV  rV  ]  s     
!!	 !& rE   c                      d fd}|S )Nc                    t        | d         \  }}|j                  D cg c]  }|d   j                  v s| }}|rt        fd|D              rS t	        fd|D              rS S c c}w )Nr   r   c              3  V   K   | ]   }j                   |d       j                   " yw)r   N)r  r<  )r   r  r  s     rC   r   zD_make_tools_to_model_edge.<locals>.tools_to_model.<locals>.<genexpr>  s+      *
ABI##AfI.<<*
s   &)c              3  :   K   | ]  }|j                   v   y wrI   )r   )r   r  r   s     rC   r   zD_make_tools_to_model_edge.<locals>.tools_to_model.<locals>.<genexpr>  s     HQqvv00Hs   )r  r   r  allr   )	r+  r  r   r  client_side_tool_callsr>  r=  r   r  s	        rC   tools_to_modelz1_make_tools_to_model_edge.<locals>.tools_to_model  s    )I%PZJ[)\&
 '11"
QvY)BYBY5YA"
 "
 "c *
F\*
 '
 #" H-HH""
 ! "
s
   A.A.)r+  rH  rY   
str | Noner_   )r  r=  r   r>  r  s   ```` rC   rT  rT  x  s    ! !, rE   c                  |rndfd}g}d|v r|j                         d|v r|j                  d       d|v r|k7  r|j                         | j                  |t        |d      |       y| j                  |       y)	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                F    t        | j                  d            xs S )Nr  r?  )r  r   )r+  rA  r>  r=  s    rC   	jump_edgez'_add_middleware_edge.<locals>.jump_edge  s,    IIi(&7$3 '
 'rE   r  r   r   Fr9  N)r+  rH  rY   r   )r  rS  r   rR  )rr  r   rA  r=  r>  rB  r  destinationss     ```   rC   rW  rW    s    * 	 ,,K0k!(k!d.?&? 12##D*:9E*RT`a 	t01rE   r  )r@   zModelResponse | AIMessagerY   r    )rl   zfSequence[Callable[[ModelRequest, Callable[[ModelRequest], ModelResponse]], ModelResponse | AIMessage]]rY   zWCallable[[ModelRequest, Callable[[ModelRequest], ModelResponse]], ModelResponse] | None)rl   z|Sequence[Callable[[ModelRequest, Callable[[ModelRequest], Awaitable[ModelResponse]]], Awaitable[ModelResponse | AIMessage]]]rY   zmCallable[[ModelRequest, Callable[[ModelRequest], Awaitable[ModelResponse]]], Awaitable[ModelResponse]] | NonerI   )r}   z	set[type]r~   r   r   r  rY   r   )r   r   rY   z	list[Any])r   zAgentMiddleware[Any, Any]r   r   rY   zlist[JumpTo])r   str | BaseChatModelr   z&list[BaseTool | dict[str, Any]] | NonerY   bool)r   r   r   zResponseFormat[Any]rY   ztuple[bool, str])r   zSequence[ToolCallWrapper]rY   zToolCallWrapper | None)r   zSequence[Callable[[ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]], Awaitable[ToolMessage | Command[Any]]]]rY   zCallable[[ToolCallRequest, Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]]], Awaitable[ToolMessage | Command[Any]]] | None)r   r  r   z?Sequence[BaseTool | Callable[..., Any] | dict[str, Any]] | Noner   zstr | SystemMessage | Noner   z.Sequence[AgentMiddleware[StateT_co, ContextT]]r   zCResponseFormat[ResponseT] | type[ResponseT] | dict[str, Any] | 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[Any] | NonerY   zcCompiledStateGraph[AgentState[ResponseT], ContextT, _InputAgentState, _OutputAgentState[ResponseT]])r  zJumpTo | Noner=  r   r>  r   rY   r  )r   zlist[AnyMessage]rY   z#tuple[AIMessage, list[ToolMessage]])r=  r   r   !dict[str, OutputToolBinding[Any]]r>  r   rY   3Callable[[dict[str, Any]], str | list[Send] | None])r=  r   r>  r   rY   r  )
r  r   r=  r   r   r  r>  r   rY   z&Callable[[dict[str, Any]], str | None])rr  z[StateGraph[AgentState[ResponseT], ContextT, _InputAgentState, _OutputAgentState[ResponseT]]r   r   rA  r   r=  r   r>  r   rB  zlist[JumpTo] | NonerY   None)f__doc__
__future__r   rX  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.typesr   r   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-   r.   langchain.chat_modelsr/   collections.abcr0   r1   r2   langchain_core.runnablesr3   r4   langgraph.cache.baser5   r6   langgraph.runtimer7   langgraph.store.baser8   r9   langgraph.typingr:   r;   r<   r   stripr	  r   rD   rm   rw   r   r{   r   r   r   r   r   r  r  r  rU  rV  rT  rW  __all__r_   rE   rC   <module>r     sa   @ "    E U U ) : * , F ) > >  
 
 
 2==A.8).,)R#O  0 
EG1 4
* &ooodTTTn3D H QU%%'M%	%P**(* *<-'--`===D NR@ 15AC[_7;,0(,")-(,#'@@J@ .	@
 ?@ Y@ 5@ *@ &@ @ '@ &@ @ @ !@ !@F  	
 **(* 55 ?5 	5
 95p  9	6  ?	
  ,@-2-2
 -2 -2 -2 -2 %-2 
-2b rE   