
    @h*                        S SK r S SKJr  S SKJrJrJr  S SKJr  S SK	J
r
  S SKJr  S SKJr  S SKJr  S S	KJrJrJr  S S
KJrJr  S SK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$  S SK%J&r&  S SK'J(r(J)r)J*r*  S SK+J,r,  S SK-J.r.  Sr/\" SSSS9 " S S\5      5       r0\.4SS.S\S\\   S \S!\S"\\1\2\3   4   S#\4S$ jjjr4g)%    N)Sequence)AnyOptionalUnion)
deprecated)AgentAction)BaseCallbackManager)BaseLanguageModel)BasePromptTemplate)ChatPromptTemplateHumanMessagePromptTemplateSystemMessagePromptTemplate)RunnableRunnablePassthrough)BaseTool)ToolsRenderer)Field)AgentAgentOutputParserformat_log_to_str)JSONAgentOutputParser)%StructuredChatOutputParserWithRetries)FORMAT_INSTRUCTIONSPREFIXSUFFIX)LLMChain) render_text_description_and_argsz{input}

{agent_scratchpad}z0.1.0create_structured_chat_agentz1.0)alternativeremovalc                     ^  \ rS rSr% Sr\" \S9r\\	S'    \
S\4S j5       r\
S\4S j5       rS\\\\4      S\4U 4S	 jjr\S
\\   SS4S j5       r\ SS\\   S\S\4S jj5       r\
S\\   4S j5       r\\\\\SS4S
\\   S\S\S\S\S\\\      S\\\      S\4S jj5       r \SS\\\\SS4S\S
\\   S\\!   S\\   S\S\S\S\S\\\      S\\\      S\S\"4S jj5       r#\
S\4S j5       r$Sr%U =r&$ )StructuredChatAgent!   zStructured Chat Agent.)default_factoryoutput_parserreturnc                     g)z&Prefix to append the observation with.zObservation:  selfs    ]/var/www/html/shao/venv/lib/python3.13/site-packages/langchain/agents/structured_chat/base.pyobservation_prefix&StructuredChatAgent.observation_prefix*   s         c                     g)z#Prefix to append the llm call with.zThought:r)   r*   s    r,   
llm_prefixStructuredChatAgent.llm_prefix/   s     r/   intermediate_stepsc                    > [         TU ]  U5      n[        U[        5      (       d  Sn[	        U5      eU(       a  SU 3$ U$ )Nz*agent_scratchpad should be of type string.zhThis was your previous work (but I haven't seen any of it! I only see what you return as final answer):
)super_construct_scratchpad
isinstancestr
ValueError)r+   r3   agent_scratchpadmsg	__class__s       r,   r6   )StructuredChatAgent._construct_scratchpad4   sT     !789KL*C00>CS/!11A0BD
  r/   toolsNc                     g Nr)   )clsr>   s     r,   _validate_tools#StructuredChatAgent._validate_toolsD   s    r/   llmkwargsc                 *    [         R                  " US9$ )NrD   )r   from_llm)rA   rD   rE   s      r,   _get_default_output_parser.StructuredChatAgent._get_default_output_parserH   s     5==#FFr/   c                     S/$ )NzObservation:r)   r*   s    r,   _stopStructuredChatAgent._stopP   s    r/   prefixsuffixhuman_message_templateformat_instructionsinput_variablesmemory_promptsc                 @   / nU Hq  n	[         R                  " SS[         R                  " SS[        U	R                  5      5      5      n
UR	                  U	R
                   SU	R                   SU
 35        Ms     SR                  U5      nSR                  U V	s/ sH  oR
                  PM     sn	5      nUR                  US	9nU S
U S
U S
U 3nUc  SS/nU=(       d    / n[        R                  " U5      /UQ[        R                  " U5      Pn[        XoS9$ s  sn	f )N}z}}{z{{z: z, args: 
, )
tool_namesz

inputr:   )rR   messages)resubr8   argsappendnamedescriptionjoinformatr   from_templater   r   )rA   r>   rN   rO   rP   rQ   rR   rS   tool_stringstoolargs_schemaformatted_toolsrY   template_memory_promptsr[   s                   r,   create_prompt!StructuredChatAgent.create_promptT   s'    D&&dBFF3c$))n,MNK499+R0@0@/A+ WX  ))L1YYe<ed		e<=
188J8OXT/!2$7J6K4PVxX"&(:;O(.B'55h?

 '445KL

 "/UU  =s   Dcallback_managerc           
          U R                  U5        U R                  UUUUUU	U
S9n[        UUUS9nU Vs/ sH  oR                  PM     nnU=(       d    U R	                  US9nU " SUUUS.UD6$ s  snf )z)Construct an agent from an LLM and tools.)rN   rO   rP   rQ   rR   rS   )rD   promptrm   rG   )	llm_chainallowed_toolsr&   r)   )rB   rk   r   r`   rI   )rA   rD   r>   rm   r&   rN   rO   rP   rQ   rR   rS   rE   ro   rp   rf   rY   _output_parsers                    r,   from_llm_and_tools&StructuredChatAgent.from_llm_and_toolsq   s      	E"""#9 3+) # 
 -
	
 -22EDiiE
2&Q#*H*HS*H*Q 
$(
 	
 	
 3s   A0c                     [         er@   )r9   r*   s    r,   _agent_typeStructuredChatAgent._agent_type   s    r/   r)   r@   )'__name__
__module____qualname____firstlineno____doc__r   r   r&   r   __annotations__propertyr8   r-   r1   listtupler   r6   classmethodr   r   rB   r   r
   r   rI   rL   r   r   HUMAN_MESSAGE_TEMPLATEr   r   rk   r	   r   rs   rv   __static_attributes____classcell__)r<   s   @r,   r#   r#   !   s~    ',=(M$  'C   C    {C'7!89  
   HX$6 4    ,0G'(G G 
	G G  tCy      &<#6/3=AV!V V 	V
 !$V !V "$s),V !&8!9:V 
V V8 
 ;?59&<#6/3=A%
%
 !%
 ##67	%

   12%
 %
 %
 !$%
 !%
 "$s),%
 !&8!9:%
 %
 
%
 %
N S  r/   r#   T)stop_sequencerD   r>   ro   tools_rendererr   r'   c          	         1 SkR                  UR                  [        UR                  5      -   5      nU(       a  SU 3n[	        U5      eUR                  U" [        U5      5      SR                  U Vs/ sH  owR                  PM     sn5      S9nU(       a  USL a  S/OUnU R                  US9n	OU n	[        R                  " S S	9U-  U	-  [        5       -  $ s  snf )
a  Create an agent aimed at supporting tools with multiple inputs.

Args:
    llm: LLM to use as the agent.
    tools: Tools this agent has access to.
    prompt: The prompt to use. See Prompt section below for more.
    stop_sequence: bool or list of str.
        If True, adds a stop token of "Observation:" to avoid hallucinates.
        If False, does not add a stop token.
        If a list of str, uses the provided list as the stop tokens.

        Default is True. You may to set this to False if the LLM you are using
        does not support stop sequences.
    tools_renderer: This controls how the tools are converted into a string and
        then passed into the LLM. Default is `render_text_description`.

Returns:
    A Runnable sequence representing an agent. It takes as input all the same input
    variables as the prompt passed in does. It returns as output either an
    AgentAction or AgentFinish.

Examples:

    .. code-block:: python

        from langchain import hub
        from langchain_community.chat_models import ChatOpenAI
        from langchain.agents import AgentExecutor, create_structured_chat_agent

        prompt = hub.pull("hwchase17/structured-chat-agent")
        model = ChatOpenAI()
        tools = ...

        agent = create_structured_chat_agent(model, tools, prompt)
        agent_executor = AgentExecutor(agent=agent, tools=tools)

        agent_executor.invoke({"input": "hi"})

        # Using with chat history
        from langchain_core.messages import AIMessage, HumanMessage
        agent_executor.invoke(
            {
                "input": "what's my name?",
                "chat_history": [
                    HumanMessage(content="hi! my name is bob"),
                    AIMessage(content="Hello Bob! How can I assist you today?"),
                ],
            }
        )

Prompt:

    The prompt must have input keys:
        * `tools`: contains descriptions and arguments for each tool.
        * `tool_names`: contains all tool names.
        * `agent_scratchpad`: contains previous agent actions and tool outputs as a string.

    Here's an example:

    .. code-block:: python

        from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

        system = '''Respond to the human as helpfully and accurately as possible. You have access to the following tools:

        {tools}

        Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).

        Valid "action" values: "Final Answer" or {tool_names}

        Provide only ONE action per $JSON_BLOB, as shown:

        ```
        {{
          "action": $TOOL_NAME,
          "action_input": $INPUT
        }}
        ```

        Follow this format:

        Question: input question to answer
        Thought: consider previous and subsequent steps
        Action:
        ```
        $JSON_BLOB
        ```
        Observation: action result
        ... (repeat Thought/Action/Observation N times)
        Thought: I know what to respond
        Action:
        ```
        {{
          "action": "Final Answer",
          "action_input": "Final response to human"
        }}

        Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation'''

        human = '''{input}

        {agent_scratchpad}

        (reminder to respond in a JSON blob no matter what)'''

        prompt = ChatPromptTemplate.from_messages(
            [
                ("system", system),
                MessagesPlaceholder("chat_history", optional=True),
                ("human", human),
            ]
        )
>   r>   rY   r:   z#Prompt missing required variables: rX   )r>   rY   Tz
Observation)stopc                     [        U S   5      $ )Nr3   r   )xs    r,   <lambda>.create_structured_chat_agent.<locals>.<lambda>+  s    '8;O9P'Qr/   )r:   )
differencerR   r   partial_variablesr9   partialrb   r`   bindr   assignr   )
rD   r>   ro   r   r   missing_varsr;   tr   llm_with_stops
             r,   r   r      s    t ?IIf&>&>!??L 3L>Bo^^T%[)99e4effe45  F $1T$9 }d+ 	""Q	
 	 		
  
!	" 5s   5C)5r\   collections.abcr   typingr   r   r   langchain_core._apir   langchain_core.agentsr   langchain_core.callbacksr	   langchain_core.language_modelsr
   langchain_core.promptsr   langchain_core.prompts.chatr   r   r   langchain_core.runnablesr   r   langchain_core.toolsr   langchain_core.tools.renderr   pydanticr   langchain.agents.agentr   r   "langchain.agents.format_scratchpadr   langchain.agents.output_parsersr   .langchain.agents.structured_chat.output_parserr   'langchain.agents.structured_chat.promptr   r   r   langchain.chains.llmr   langchain.tools.renderr   r   r#   boolr   r8   r   r)   r/   r,   <module>r      s    	 $ ' ' * - 8 < 5 
 C ) 5  ; @ A X W ) C8  G!?Oy% y Py@ %E	R -1R	RHR R "	R tCy)R Rr/   