
    g3fi              $       "   d dl Z d dl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 d dlmZmZmZ d dlmZmZmZmZmZ d dlmZmZmZ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* d dl+m,Z, d dl-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4m5Z5 d dl6m7Z7 d dl8m9Z9 d dl:m;Z; d dl<m=Z=m>Z>m?Z? d dl@mAZAmBZB eCe;z  ZDeCeEe;   z  ZF e?de9       G d de>             ZG e?de9       G d de;             ZH ej                         5   ej                  de9d         e?d!e9       G d" d#eG             ZKddd        ej                         5   ej                  de9d         e?d$e9       G d% d&eH             ZLddd        ej                         5   ej                  de9        e
d'eGeHz  (      ZMeEeM   ZNddd       d)ZOeePz  eeMgef   z  eeMef   z  ZQdLd*eMd+ePd,ed-efd.ZRd/eQdz  d-efd0ZS	 dMd1ed2ee   d3eTd-eUfd4ZVd1ed-efd5ZWd6ee   d-dfd7ZX e?d8e9      ddddddddddd9d:dd;d1ePez  eeMe0e7   gef   z  eeMe0e7   gee   f   z  eeMe0e7   geeef   f   z  eeMe0e7   geeeef      f   z  d2eeez  eCePef   z     eBz  d/eQdz  d<eFeYePeFf   z  dz  d=e dz  d>e dz  d?eNdz  d@eEe   dz  dAe4dz  dBe2dz  dCeZeP   dz  dDeZeP   dz  dEeUdFe	dG   dHePdz  dIed-e,f"dJ       Z[e[Z\g dKZ]y# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   NxY w)N    N)	AwaitableCallableSequence)	AnnotatedAnyLiteralTypeVarcastget_type_hints)BaseChatModelLanguageModelInputLanguageModelLike)	AIMessage
AnyMessageBaseMessageSystemMessageToolMessage)RunnableRunnableBindingRunnableConfigRunnableSequence)BaseTool)RunnableCallableRunnableLike)MISSING)	ErrorCodecreate_error_message)END
StateGraph)add_messages)CompiledStateGraph)RemainingSteps)Runtime)	BaseStore)CheckpointerSend)ContextT)LangGraphDeprecatedSinceV10)	BaseModel)NotRequired	TypedDict
deprecated)ToolCallWithContextToolNodezxAgentState has been moved to `langchain.agents`. Please update your import to `from langchain.agents import AgentState`.categoryc                   <    e Zd ZU dZeee   ef   ed<   e	e
   ed<   y)
AgentStateThe state of the agent.messagesremaining_stepsN)__name__
__module____qualname____doc__r   r   r   r    __annotations__r*   r"        d/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langgraph/prebuilt/chat_agent_executor.pyr2   r2   5   s'    
 "-|;<< 00r<   r2   zTAgentStatePydantic has been deprecated in favor of AgentState in `langchain.agents`.c                   :    e Zd ZU dZeee   ef   ed<   dZ	e
ed<   y)AgentStatePydanticr3   r4      r5   N)r6   r7   r8   r9   r   r   r   r    r:   r5   r"   r;   r<   r=   r?   r?   A   s&    
 "-|;<<&(O^(r<   r?   ignorez1AgentState has been moved to `langchain.agents`.*)r0   messagezbAgentStateWithStructuredResponse has been deprecated in favor of AgentState in `langchain.agents`.c                       e Zd ZU dZeed<   y) AgentStateWithStructuredResponse2The state of the agent with a structured response.structured_responseNr6   r7   r8   r9   StructuredResponser:   r;   r<   r=   rD   rD   T       
 	A//r<   rD   zjAgentStateWithStructuredResponsePydantic has been deprecated in favor of AgentState in `langchain.agents`.c                       e Zd ZU dZeed<   y)(AgentStateWithStructuredResponsePydanticrE   rF   NrG   r;   r<   r=   rK   rK   e   rI   r<   rK   StateSchema)boundPromptstatekeydefaultreturnc                 `    t        | t              r| j                  ||      S t        | ||      S N)
isinstancedictgetgetattr)rO   rP   rQ   s      r=   _get_state_valuerY      s6     eT" 			#w UC)r<   promptc                      t        d t              }|S t         t              r"t	               t        fdt              }|S t         t              rt         fdt              }|S t        j                         rt        d  t              }|S t               rt         t              }|S t         t              r }|S t        dt                      )Nc                     t        | d      S Nr4   rY   )rO   s    r=   <lambda>z&_get_prompt_runnable.<locals>.<lambda>   s    *5*= r<   namecontentc                 $    gt        | d      z   S r]   r^   )rO   _system_messages    r=   r_   z&_get_prompt_runnable.<locals>.<lambda>   s    ?+.>uj.QQ r<   c                 $    gt        | d      z   S r]   r^   )rO   rZ   s    r=   r_   z&_get_prompt_runnable.<locals>.<lambda>   s    6(%5eZ%HH r<   z"Got unexpected type for `prompt`: )r   PROMPT_RUNNABLE_NAMErU   strr   inspectiscoroutinefunctioncallabler   
ValueErrortype)rZ   prompt_runnablere   s   ` @r=   _get_prompt_runnablero      s    ~*=DX
< 7 
FC	 '4V'D*Q%
2 + 
FM	**H%
( ! 
	$	$V	,*%
  
&	*%
  
FH	%   =d6l^LMMr<   modeltoolsnum_builtinc                 :   t        | t              rt        d | j                  D        |       } t        | t              syd| j
                  vry| j
                  d   }t        |      t        |      |z
  k7  r&t        dt        |       dt        |      |z
         t        d |D              }t               }|D ]H  }|j                  d      dk(  r	|d   d	   }n|j                  d	      r|d	   }n8|j                  |       J ||z
  x}rt        d
| d      y)Nc              3   L   K   | ]  }t        |t        t        f      r|  y wrT   rU   r   r   .0steps     r=   	<genexpr>z%_should_bind_tools.<locals>.<genexpr>   '      d_m$DE    "$Trq   z`Number of tools in the model.bind_tools() and tools passed to create_react_agent must match Got z tools, expected c              3   4   K   | ]  }|j                     y wrT   r`   )rw   tools     r=   ry   z%_should_bind_tools.<locals>.<genexpr>   s     14TYY1s   rm   functionra   zMissing tools 'z' in the model.bind_tools()F)rU   r   nextstepsr   kwargslenrl   setrW   add)	rp   rq   rr   bound_tools
tool_namesbound_tool_names
bound_toolbound_tool_namemissing_toolss	            r=   _should_bind_toolsr      sA    %)*!KK
 
 e_-ell",,w'K
5zS%33J<0[1AK1O0PR
 	

 1511Ju! .
>>&!Z/(4V<O^^F#(0O _-. #%555}5?=/9TUVVr<   c                     t        | t              rt        d | j                  D        |       } t        | t              r| j
                  } t        | t              st        dt        |              | S )zKGet the underlying model from a RunnableBinding or return the model itself.c              3   L   K   | ]  }t        |t        t        f      r|  y wrT   ru   rv   s     r=   ry   z_get_model.<locals>.<genexpr>   rz   r{   zXExpected `model` to be a ChatModel or RunnableBinding (e.g. model.bind_tools(...)), got )	rU   r   r   r   r   rM   r   	TypeErrorrm   )rp   s    r=   
_get_modelr      sr    %)*!KK
 
 %)e]+fgklqgrfst
 	
 Lr<   r4   c                 f   | D cg c]%  }t        |t              r|j                  D ]  }| ' }}}| D ch c]  }t        |t              s|j                  ! }}|D cg c]  }|d   |vr| }}|syt        d|dd  dt        j                        }t        |      c c}}w c c}w c c}w )zLValidate that all tool calls in AIMessages have a corresponding ToolMessage.idNz{Found AIMessages with tool_calls that do not have a corresponding ToolMessage. Here are the first few of those tool calls:    z.

Every tool call (LLM requesting to call a tool) in the message history MUST have a corresponding ToolMessage (result of a tool invocation to return to the LLM) - this is required by most LLM providers.)rB   
error_code)	rU   r   
tool_callsr   tool_call_idr   r   INVALID_CHAT_HISTORYrl   )r4   rB   	tool_callall_tool_callstool_call_ids_with_resultstool_calls_without_resultserror_messages          r=   _validate_chat_historyr      s      gy) ++	  	N  -5"!(
7K8X" "
 ("T?"<< 	" "
 &(77QRTST7U6V Wgg 11M ]
##1""s   *B#B)B)!B.zcreate_react_agent has been moved to `langchain.agents`. Please update your import to `from langchain.agents import create_agent`.Fv2)rZ   response_formatpre_model_hookpost_model_hookstate_schemacontext_schemacheckpointerstoreinterrupt_beforeinterrupt_afterdebugversionra   r   r   r   r   r   r   r   r   r   r   r   v1r   ra   deprecated_kwargsc          	         '()*+,-./ |j                  dt              x}t        urt        j                  dt               ||}t        |      dkD  rt        d|       dvrt        d d	      Jd
dh}|j                  d       t        t                    }|t        |      z
  x}rt        d| d      t        nt        g }t        |t              r&t        |j                   j#                               }|}nm|D cg c]  }t        |t$              s| }}t        |D cg c]  }t        |t$              r| c}      }t        |j                   j#                               }t         t&        t(        f       xr t+               --xr t-        j.                         ,t        |      dkD  }-st         t&              r	 ddlm} t7        t8         |              t;         |t        |            r3t        ||z         dkD  r"t7        t8               j=                  ||z          t?               z  /nd/|D ch c]  }|j@                  s|jB                   c}.dtD        dtF        tH           dtJ        f- /fd*dtD        dtF        tH           dtJ        f,- /fd(dtD        dtL        dtN        f.fd'dtD        dtD        ffd)dtD        dtF        tH           dtP        dtD        f')*,-/fd}dtD        dtF        tH           dtP        dtD        f'()-/fd}Mt        tR              r/tU        tV              rddl,m-}  |dt        t\           df       }n G d! d      }|}n}dtD        dtF        tH           dtP        dtD        f*,fd"}dtD        dtF        tH           dtP        dtD        f(fd#} |st_        |$      }!|!ja                  d%tc        ||      |&       '|!ja                  d'       |!je                  d'd%       d'+nd%+|!jg                  +       $|!ja                  d(       |!je                  d%d(       C|!ja                  d)tc        ||              |!je                  d(d)       n|!je                  d%d)       |!ji                  ||	|
||*      S dtD        dt&        t        tj           z  ffd+}"t_        xs t        |$      }!|!ja                  d%tc        ||      |&       |!ja                  d,|       '|!ja                  d'       |!je                  d'd%       d'+nd%+|!jg                  +       g }#+d,g}$6|!ja                  d(       |#jm                  d(       |!je                  d%d(       n|#jm                  d,       B|!ja                  d)tc        ||              |$jm                  d)       n?|#jm                  d)       n-|$jm                  tn               n|#jm                  tn               5dtD        dt&        t        tj           z  f+fd-}%|!jq                  d(|%|$.       |!jq                  d%|"|#.       dtD        dt&        f+.fd/}&.r|!jq                  d,|&+tn        g.       n|!je                  d,+       |!ji                  ||	|
||*      S c c}w c c}w # t4        $ r t5        d      w xY wc c}w )0a()  Creates an agent graph that calls tools in a loop until a stopping condition is met.

    For more details on using `create_react_agent`, visit [Agents](https://langchain-ai.github.io/langgraph/agents/overview/) documentation.

    Args:
        model: The language model for the agent. Supports static and dynamic
            model selection.

            - **Static model**: A chat model instance (e.g.,
                [`ChatOpenAI`][langchain_openai.ChatOpenAI]) or string identifier (e.g.,
                `"openai:gpt-4"`)
            - **Dynamic model**: A callable with signature
                `(state, runtime) -> BaseChatModel` that returns different models
                based on runtime context

                If the model has tools bound via `bind_tools` or other configurations,
                the return type should be a `Runnable[LanguageModelInput, BaseMessage]`
                Coroutines are also supported, allowing for asynchronous model selection.

            Dynamic functions receive graph state and runtime, enabling
            context-dependent model selection. Must return a `BaseChatModel`
            instance. For tool calling, bind tools using `.bind_tools()`.
            Bound tools must be a subset of the `tools` parameter.

            !!! example "Dynamic model"

                ```python
                from dataclasses import dataclass

                @dataclass
                class ModelContext:
                    model_name: str = "gpt-3.5-turbo"

                # Instantiate models globally
                gpt4_model = ChatOpenAI(model="gpt-4")
                gpt35_model = ChatOpenAI(model="gpt-3.5-turbo")

                def select_model(state: AgentState, runtime: Runtime[ModelContext]) -> ChatOpenAI:
                    model_name = runtime.context.model_name
                    model = gpt4_model if model_name == "gpt-4" else gpt35_model
                    return model.bind_tools(tools)
                ```

            !!! note "Dynamic Model Requirements"

                Ensure returned models have appropriate tools bound via
                `.bind_tools()` and support required functionality. Bound tools
                must be a subset of those specified in the `tools` parameter.

        tools: A list of tools or a `ToolNode` instance.
            If an empty list is provided, the agent will consist of a single LLM node without tool calling.
        prompt: An optional prompt for the LLM. Can take a few different forms:

            - `str`: This is converted to a `SystemMessage` and added to the beginning of the list of messages in `state["messages"]`.
            - `SystemMessage`: this is added to the beginning of the list of messages in `state["messages"]`.
            - `Callable`: This function should take in full graph state and the output is then passed to the language model.
            - `Runnable`: This runnable should take in full graph state and the output is then passed to the language model.

        response_format: An optional schema for the final agent output.

            If provided, output will be formatted to match the given schema and returned in the 'structured_response' state key.

            If not provided, `structured_response` will not be present in the output state.

            Can be passed in as:

            - An OpenAI function/tool schema,
            - A JSON Schema,
            - A TypedDict class,
            - A Pydantic class.
            - A tuple `(prompt, schema)`, where schema is one of the above.
                The prompt will be used together with the model that is being used to
                generate the structured response.

            !!! Important
                `response_format` requires the model to support `.with_structured_output`

            !!! Note
                The graph will make a separate call to the LLM to generate the structured response after the agent loop is finished.
                This is not the only strategy to get structured responses, see more options in [this guide](https://langchain-ai.github.io/langgraph/how-tos/react-agent-structured-output/).

        pre_model_hook: An optional node to add before the `agent` node (i.e., the node that calls the LLM).
            Useful for managing long message histories (e.g., message trimming, summarization, etc.).
            Pre-model hook must be a callable or a runnable that takes in current graph state and returns a state update in the form of
                ```python
                # At least one of `messages` or `llm_input_messages` MUST be provided
                {
                    # If provided, will UPDATE the `messages` in the state
                    "messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), ...],
                    # If provided, will be used as the input to the LLM,
                    # and will NOT UPDATE `messages` in the state
                    "llm_input_messages": [...],
                    # Any other state keys that need to be propagated
                    ...
                }
                ```

            !!! Important
                At least one of `messages` or `llm_input_messages` MUST be provided and will be used as an input to the `agent` node.
                The rest of the keys will be added to the graph state.

            !!! Warning
                If you are returning `messages` in the pre-model hook, you should OVERWRITE the `messages` key by doing the following:

                ```python
                {
                    "messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), *new_messages]
                    ...
                }
                ```
        post_model_hook: An optional node to add after the `agent` node (i.e., the node that calls the LLM).
            Useful for implementing human-in-the-loop, guardrails, validation, or other post-processing.
            Post-model hook must be a callable or a runnable that takes in current graph state and returns a state update.

            !!! Note
                Only available with `version="v2"`.
        state_schema: An optional state schema that defines graph state.
            Must have `messages` and `remaining_steps` keys.
            Defaults to `AgentState` that defines those two keys.
            !!! Note
                `remaining_steps` is used to limit the number of steps the react agent can take.
                Calculated roughly as `recursion_limit` - `total_steps_taken`.
                If `remaining_steps` is less than 2 and tool calls are present in the response,
                the react agent will return a final AI Message with
                the content "Sorry, need more steps to process this request.".
                No `GraphRecusionError` will be raised in this case.

        context_schema: An optional schema for runtime context.
        checkpointer: An optional checkpoint saver object. This is 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. This is used for persisting data
            across multiple threads (e.g., multiple conversations / users).
        interrupt_before: An optional list of node names to interrupt before.
            Should be one of the following: `"agent"`, `"tools"`.

            This is 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.
            Should be one of the following: `"agent"`, `"tools"`.

            This is useful if you want to return directly or run additional processing on an output.
        debug: A flag indicating whether to enable debug mode.
        version: Determines the version of the graph to create.

            Can be one of:

            - `"v1"`: The tool node processes a single message. All tool
                calls in the message are executed in parallel within the tool node.
            - `"v2"`: The tool node processes a tool call.
                Tool calls are distributed across multiple instances of the tool
                node using the [Send](https://langchain-ai.github.io/langgraph/concepts/low_level/#send)
                API.
        name: An optional name for the `CompiledStateGraph`.
            This name will be automatically used when adding ReAct agent graph to another graph as a subgraph node -
            particularly useful for building multi-agent systems.

    !!! warning "`config_schema` Deprecated"
        The `config_schema` parameter is deprecated in v0.6.0 and support will be removed in v2.0.0.
        Please use `context_schema` instead to specify the schema for run-scoped context.


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

    The "agent" node calls the language model with the messages list (after applying the prompt).
    If the resulting AIMessage contains `tool_calls`, the graph will then call the ["tools"][langgraph.prebuilt.tool_node.ToolNode].
    The "tools" node executes the tools (1 tool per `tool_call`) and adds the responses to the messages list
    as `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 as a dictionary containing the key `'messages'`.

    ``` mermaid
        sequenceDiagram
            participant U as User
            participant A as LLM
            participant T as Tools
            U->>A: Initial input
            Note over A: Prompt + LLM
            loop while tool_calls present
                A->>T: Execute tools
                T-->>A: ToolMessage for each tool_calls
            end
            A->>U: Return final state
    ```

    Example:
        ```python
        from langgraph.prebuilt import create_react_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_react_agent(
            "anthropic:claude-3-7-sonnet-latest",
            tools=[check_weather],
            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)
        ```
    config_schemazW`config_schema` is deprecated and will be removed. Please use `context_schema` instead.r/   Nr   z7create_react_agent() got unexpected keyword arguments: r   zInvalid version z'. Supported versions are 'v1' and 'v2'.r4   r5   rF   zMissing required key(s) z in state_schema)init_chat_modelzsPlease install langchain (`pip install langchain`) to use '<provider>:<model>' string syntax for `model` parameter.)rr   rO   runtimerR   c                 6    rt               | |      z  S S )zBResolve the model to use, handling both static and dynamic models.ro   )rO   r   is_dynamic_modelrp   rZ   static_models     r=   _resolve_modelz*create_react_agent.<locals>._resolve_modelQ  s%     '/%w2GGGr<   c                    K   r | |       d{   }t              |z  S rt               | |      z  S S 7 +w)zHAsync resolve the model to use, handling both static and dynamic models.Nr   )rO   r   resolved_modelis_async_dynamic_modelr   rp   rZ   r   s      r=   _aresolve_modelz+create_react_agent.<locals>._aresolve_modelZ  sP      "#(#88N'/.@@'/%w2GGG 9s   A >,A responsec                     t        |t              xr |j                  }t        |t              rt        fd|j                  D              nd}t	        | dd       }||dk  r|ry|dk  r|ryy)Nc              3   ,   K   | ]  }|d    v   ywra   Nr;   rw   callshould_return_directs     r=   ry   zEcreate_react_agent.<locals>._are_more_steps_needed.<locals>.<genexpr>i  s     UV 44U   Fr5      T   )rU   r   r   allrY   )rO   r   has_tool_callsall_tools_return_directr5   r   s        r=   _are_more_steps_neededz2create_react_agent.<locals>._are_more_steps_neededf  sy    #Hi8PX=P=P (I. UATATUU 	 
 +52CTJ&"'> 1$r<   c                      t        | d      xs t        | d      }d|  }nt        | d      }d|  }|t        |      t        |       t        t              rt        t              r	|| _        | S || d<   | S )Nllm_input_messagesr4   zUExpected input to call_model to have 'llm_input_messages' or 'messages' key, but got z=Expected input to call_model to have 'messages' key, but got )rY   rl   r   rU   rm   
issubclassr)   r4   )rO   r4   	error_msgr   r   s      r=   _get_model_input_statez2create_react_agent.<locals>._get_model_input_statev  s    % (<=5!%4  ppuovwI'z:HOPUwW  Y''x(lD)jy.Q%EN  !)E*r<   configc                 (   
rd}t        |       |       }r* 	| |      }t        t        |j                  ||            }n t        t        j                  ||            }|_         | |      rdt        |j
                  d      giS d|giS )NAsync model callable provided but agent invoked synchronously. Use agent.ainvoke() or agent.astream(), or provide a sync model callable.r4   /Sorry, need more steps to process this request.r   rc   )RuntimeErrorr
   r   invokera   r   )rO   r   r   msgmodel_inputdynamic_modelr   r   r   r   r   r   ra   r   s          r=   
call_modelz&create_react_agent.<locals>.call_model  s     "1 
 s##,U3*5':MI}';';K'PQHI|':':;'OPH !%2#;; Q  XJ''r<   c                 N  K    |       }	r: | |       d {   }t        t        |j                  ||       d {         }n(t        t        j                  ||       d {         }
|_         | |      rdt        |j                  d      giS d|giS 7 7 b7 ;w)Nr4   r   r   )r
   r   ainvokera   r   )rO   r   r   r   r   r   r   r   r   r   ra   r   s         r=   acall_modelz'create_react_agent.<locals>.acall_model  s      -U3 #2%"AAMI]-B-B;PV-W'WXHI\-A-A+v-V'VWH !%2#;; Q  XJ''# B'W'Vs1   B%B#B%B!
(B%'B#
(8B%!B%#B%)create_modelCallModelInputSchema.)r   __base__c                       e Zd ZU ee   ed<   y)0create_react_agent.<locals>.CallModelInputSchemar   N)r6   r7   r8   listr   r:   r;   r<   r=   r   r     s    $($44r<   c                 (   rd}t        |      t        | d      }}t        t              r\  }}t	        |      gt        |      z   } 
| |      }t        |      j                  t        t        |            }|j                  ||      }	d|	iS )Nr   r4   rb   rF   )r   rY   rU   tupler   r   r   with_structured_outputr
   StructuredResponseSchemar   )rO   r   r   r   r4   structured_response_schemasystem_promptr   model_with_structured_outputr   r   r   r   s             r=   generate_structured_responsez8create_react_agent.<locals>.generate_structured_response  s     "\  s###E:6%4"ou-8G5M5%m<=XNH'w7'1(

 
 )+EF
 	%
 066xH%x00r<   c                 :  K   t        | d      }
}t        
t              r
\  }}t        |      gt	        |      z   } 	| |       d {   }t        |      j                  t        t        |            }|j                  ||       d {   }d|iS 7 J7 
w)Nr4   rb   rF   )
rY   rU   r   r   r   r   r   r
   r   r   )rO   r   r   r4   r   r   r   r   r   r   r   s            r=   agenerate_structured_responsez9create_react_agent.<locals>.agenerate_structured_response  s      $E:6%4"ou-8G5M5%m<=XNH.ug>>'1(

 
 )+EF
 	%
 6==hOO%x00 ? Ps%   A	BBABB	BB)r   r   agent)input_schemar   r   r   )r   r   r   r   r   ra   c                     t        | d      }|d   }t        |t              r|j                  syyt        S dk(  rydk(  r3y|j                  D cg c]  }t        dt        d|| 	             c}S y c c}w )
Nr4   r   r   r   rq   r   tool_call_with_context__typer   rO   )rY   rU   r   r   r   r&   r-   )rO   r4   last_messager   r   r   r   s       r=   should_continuez+create_react_agent.<locals>.should_continue9  s    #E:6|,	2,:Q:Q*( ,5
 $D"., !- 7 7
  +#;&*"'
 
 !
s   A:rq   c                    t        | d      }|D cg c]  }t        |t              s|j                  ! }}t	        d t        |      D              }|j                  D cg c]  }|d   |vs| }}|r&|D cg c]  }t        dt        d||              c}S t        |d   t              rS 	yt        S c c}w c c}w c c}w )	aw  Route to the next node after post_model_hook.

            Routes to one of:
            * "tools": if there are pending tool calls without a corresponding message.
            * "generate_structured_response": if no pending tool calls exist and response_format is specified.
            * END: if no pending tool calls exist and no response_format is specified.
            r4   c              3   B   K   | ]  }t        |t              s|  y wrT   )rU   r   )rw   ms     r=   ry   zEcreate_react_agent.<locals>.post_model_hook_router.<locals>.<genexpr>  s      #Ay1I#s   r   rq   r   r   r   r   )
rY   rU   r   r   r   reversedr   r&   r-   r   )
rO   r4   r   tool_messageslast_ai_messagecpending_tool_callsr   
entrypointr   s
           r=   post_model_hook_routerz2create_react_agent.<locals>.post_model_hook_router  s     (z:H(0#$Jq+4NM  # ##H-# O +55"49U" " " !3
  +#;&*"'
 
 HRL+6!! ,5
7"

s   B:B:!B?.B?:C)path_mapc                    t        t        | d            D ]*  }t        |t              s n|j                  v s$t
        c S  t        t              r0|j                  r$t        fd|j                  D              rt
        S S )Nr4   c              3   ,   K   | ]  }|d    v   ywr   r;   r   s     r=   ry   zCcreate_react_agent.<locals>.route_tool_responses.<locals>.<genexpr>  s     QD4<#77Qr   )	r   rY   rU   r   ra   r   r   r   any)rO   r   r   r   s     r=   route_tool_responsesz0create_react_agent.<locals>.route_tool_responses  sm    *5*=> 	Aa-vv--
		 a#QALLQQ
r<   )9popr   warningswarnr(   r   r   rl   r   r   r   rD   r2   rU   r.   r   tools_by_namevaluesrV   rh   r   rk   ri   rj   langchain.chat_modelsr   ImportErrorr
   r   r   
bind_toolsro   return_directra   rL   r#   r'   r   r   boolr   rm   r   r)   pydanticr   r   r   add_noder   add_edgeset_entry_pointcompiler&   appendr   add_conditional_edges)0rp   rq   rZ   r   r   r   r   r   r   r   r   r   r   r   ra   r   r   required_keysschema_keysmissing_keysllm_builtin_toolstool_classes	tool_nodettool_calling_enabledr   r   r   r   r   r   r   r   workflowr   agent_pathspost_model_hook_pathsr   r  r   r   r   r   r   r   r   r   r   s0   ` `````      ``                        @@@@@@@@@r=   create_react_agentr    s   \ +..HH 	e0	

 !*N
!EFWEXY
 	
 l"wi'NO
 	
 #%67&34.67(3{+;;;<;7~EUVWW * - 	 %'%"E//6689	(-E1At1DQEEJAjD6IaJK	I33::<=%ec8_==Q(5/-T'2M2Me2T|,q0eS! (>?E ulDU@VWL#4459.9900E )=V(Du(L  -9LqAOOAFFL  %,X%6 	   
 
 %,X%6
 	
  
 k [ T  k k 2!(!(%,X%6!(@N!(	!( !(F((%,X%6(@N(	( (8 !lD)jy.Q-'&$($4c#:%L5| 5 0L#11%,X%61@N1	1211%,X%61@N1	1$  <WZ5% 	 	

 %.?.8)J J  ,&/Ag'89&. 01 *!!"35ST!!'+IJ%-+   
 	
{ sT$Z/? > !/ZH
 [1!  
 gy) !*N;*G4%

 Z(K'1 "+_=,-'#457# "*,-	
 &!(()GH=>&!((-s#"%	+ %	#T
:J %	N 	&&"* 	' 	
 "" # K C  &&)Z4E 	' 	
 	':.
 !)'   i FJ  !T . Ms0   [,[;[[[ [2*[2[/)r  create_tool_calling_executorr2   r?   rD   rK   rT   )r   )^ri   r  collections.abcr   r   r   typingr   r   r   r	   r
   r   langchain_core.language_modelsr   r   r   langchain_core.messagesr   r   r   r   r   langchain_core.runnablesr   r   r   r   langchain_core.toolsr   langgraph._internal._runnabler   r   langgraph._internal._typingr   langgraph.errorsr   r   langgraph.graphr   r   langgraph.graph.messager    langgraph.graph.stater!   langgraph.managedr"   langgraph.runtimer#   langgraph.store.baser$   langgraph.typesr%   r&   langgraph.typingr'   langgraph.warningsr(   r  r)   typing_extensionsr*   r+   r,   langgraph.prebuilt.tool_noder-   r.   rV   rH   rm   r   r2   r?   catch_warningsfilterwarningsrD   rK   rL   StateSchemaTyperg   rh   rN   rY   ro   intr  r   r   r   r   r   r  r  __all__r;   r<   r=   <module>r9     s     9 9  
   * H / < + 0 4 , % * . % :  @ @ FI% $y/1  ~(1 1	1 Z() )	) X 0H,C l,0: 0	00" X 0H,f t,03E 0	00" X (H, -z<N/NOK;'O(    	
}0012 {../0 K c C 3 !$ !8 !J MN,,%-h%7,FI,	,^' M .${#$	$>  I($ ! *.+/+/'+(,")-(,#'9NWX./>?@ WX./=1IIJK 	gh'((3E{3R*SS	 	gh'((-{:;<	>
N Hx'$sCx.89HDN TMN .C))*+
N$ !4'%N& "D('N( "D()N* I$+N, %-N. t/N0 3i$&1N2 #Y%3N4 5N6 Z 7N8 *9N: ;N< =N	Nd  2 {0 0"0 0"( (s$   .K*
.K7'L*K47LL