
    3fi*                        d dl Z d dlmZ d dlmZ d dlmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d d	lmZ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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'm(Z(m)Z)m*Z* d dl+m,Z, d dl-m.Z. dZ/ eddd       G d de             Z0e.fddded ee   d!ed"ed#e1e2e3   z  d$efd%Z4y)&    N)Sequence)Any)
deprecated)AgentAction)BaseCallbackManager)BaseLanguageModel)BasePromptTemplate)ChatPromptTemplateHumanMessagePromptTemplateSystemMessagePromptTemplate)RunnableRunnablePassthrough)BaseTool)ToolsRenderer)Field)override)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                       e Zd ZU dZ ee      Zeed<   	 e	de
fd       Ze	de
fd       Zdeeee
f      de
f fdZed	ee   dd
fd       Zee	 dded
z  dedefd              Ze	edee
   fd              Zeeeeeed
d
fd	ee   de
de
de
de
dee
   d
z  dee   d
z  defd              Zed
d
eeeed
d
fded	ee   de d
z  ded
z  de
de
de
de
dee
   d
z  dee   d
z  dede!fd       Z"e	de
fd       Z# xZ$S )StructuredChatAgentzStructured Chat Agent.)default_factoryoutput_parserreturnc                      y)z&Prefix to append the observation with.zObservation:  selfs    k/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_classic/agents/structured_chat/base.pyobservation_prefixz&StructuredChatAgent.observation_prefix/   s         c                      y)z#Prefix to append the llm call with.zThought:r'   r(   s    r*   
llm_prefixzStructuredChatAgent.llm_prefix4   s     r,   intermediate_stepsc                 n    t         |   |      }t        |t              sd}t	        |      |rd| S |S )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)   r/   agent_scratchpadmsg	__class__s       r*   r2   z)StructuredChatAgent._construct_scratchpad9   sQ     !789KL*C0>CS/!11A0BD
  r,   toolsNc                      y Nr'   )clsr9   s     r*   _validate_toolsz#StructuredChatAgent._validate_toolsI   s    r,   llmkwargsc                 .    t        j                  |      S )Nr>   )r   from_llm)r<   r>   r?   s      r*   _get_default_output_parserz.StructuredChatAgent._get_default_output_parserM   s     5==#FFr,   c                     dgS )NzObservation:r'   r(   s    r*   _stopzStructuredChatAgent._stopV   s     r,   prefixsuffixhuman_message_templateformat_instructionsinput_variablesmemory_promptsc                 4   g }|D ]n  }	t        j                  ddt        j                  ddt        |	j                                    }
|j	                  |	j
                   d|	j                   d|
        p dj                  |      }dj                  |D 	cg c]  }	|	j
                   c}	      }|j                  |	      }| d
| d
| d
| }|ddg}|xs g }t        j                  |      g|t        j                  |      }t        ||      S c c}	w )N}z}}{z{{z: z, args: 
, )
tool_namesz

inputr6   )rJ   messages)resubr4   argsappendnamedescriptionjoinformatr   from_templater   r
   )r<   r9   rF   rG   rH   rI   rJ   rK   tool_stringstoolargs_schemaformatted_toolsrQ   template_memory_promptsrS   s                   r*   create_promptz!StructuredChatAgent.create_prompt[   s.     	YD&&dBFF3c$))n,MNK499+R0@0@/A+ WX	Y ))L1YYe<d		<=
188J8OXT/!2$7J6K4PVxX"&(:;O(.B'55h?

 '445KL

 "/HUU  =s   Dcallback_managerc           	          | j                  |       | j                  ||||||	|
      }t        |||      }|D cg c]  }|j                   }}|xs | j	                  |      } | d|||d|S c c}w )z)Construct an agent from an LLM and tools.)rF   rG   rH   rI   rJ   rK   )r>   promptrd   rA   )	llm_chainallowed_toolsr$   r'   )r=   rc   r   rX   rC   )r<   r>   r9   rd   r$   rF   rG   rH   rI   rJ   rK   r?   rf   rg   r^   rQ   _output_parsers                    r*   from_llm_and_toolsz&StructuredChatAgent.from_llm_and_toolsy   s      	E"""#9 3+) # 
 -
	
 -22Ddii2
2&Q#*H*HS*H*Q 
$(
 	
 	
 3s   A3c                     t         r;   )r5   r(   s    r*   _agent_typezStructuredChatAgent._agent_type   s    r,   r;   )%__name__
__module____qualname____doc__r   r   r$   r   __annotations__propertyr4   r+   r.   listtupler   r2   classmethodr   r   r=   r   r   r   rC   rE   r   r   HUMAN_MESSAGE_TEMPLATEr   r	   rc   r   r   rj   rl   __classcell__)r8   s   @r*   r"   r"   &   s    ',=(M$  'C   C    {C'7!89  
   HX$6 4    )-G%G G 
	G  G  tCy       &<#6,0:>V!V V 	V
 !$V !V cT)V /047V 
V  V8 
 8<26&<#6,0:>%
%
 !%
 .4	%

 )4/%
 %
 %
 !$%
 !%
 cT)%
 /047%
 %
 
%
 %
N S  r,   r"   T)stop_sequencer>   r9   rf   tools_rendererrx   r%   c          	         h dj                  |j                  t        |j                        z         }|rd| }t	        |      |j                   |t        |            dj                  |D cg c]  }|j                   c}            }|r|du rdgn|}| j                  |      }	n| }	t        j                  d 	      |z  |	z  t               z  S c c}w )
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.

            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.

    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:
        ```python
        from langchain_classic import hub
        from langchain_openai import ChatOpenAI
        from langchain_classic.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:

        ```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:

        ```txt
        {{
            "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:
        ```txt
        {{
            "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),
            ]
        )

        ```
    >   r9   rQ   r6   z#Prompt missing required variables: rP   )r9   rQ   Tz
Observation)stopc                     t        | d         S )Nr/   r   )xs    r*   <lambda>z.create_structured_chat_agent.<locals>.<lambda>8  s    '8;O9P'Q r,   )r6   )
differencerJ   rs   partial_variablesr5   partialrZ   rX   bindr   assignr   )
r>   r9   rf   ry   rx   missing_varsr7   tr{   llm_with_stops
             r*   r   r      s    ~ ?IIf&>&>!??L 3L>Bo^^T%[)99e4aff45  F $1T$9 }d+ 	""Q	
 	 		
  
!	" 5s   0C)5rT   collections.abcr   typingr   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   typing_extensionsr   langchain_classic.agents.agentr   r   *langchain_classic.agents.format_scratchpadr   'langchain_classic.agents.output_parsersr   6langchain_classic.agents.structured_chat.output_parserr   /langchain_classic.agents.structured_chat.promptr   r   r   langchain_classic.chains.llmr   langchain_classic.tools.renderr   rv   r"   boolrs   r4   r   r'   r,   r*   <module>r      s    	 $  * - 8 < 5 
 C ) 5  & C H I 
 2 K8  G!?O|% | P|F %E	W '+W	WHW W "	W $s)#W Wr,   