o
    JjgO*                     @   sn  d dl Z d dlmZmZmZmZ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 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 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Z0e	ddddG dd de Z1e/fdddedee ded ed!ee2ee3 f d"efd#dZ4dS )$    N)AnyListOptionalSequenceTuple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                       s  e Zd ZU dZeedZeed< 	 e	de
fddZe	de
fddZd	eeee
f  de
f fd
dZedee ddfddZe	d#dee dedefddZe	dee
 fddZeeeeeddfdee de
de
de
de
deee
  deee  defddZeddeeeeddfdedee dee  dee de
de
de
de
deee
  deee  dede!fdd Z"e	de
fd!d"Z#  Z$S )$StructuredChatAgentzStructured Chat Agent.)default_factoryoutput_parserreturnc                 C      dS )z&Prefix to append the observation with.zObservation:  selfr(   r(   ]/var/www/html/zoom/venv/lib/python3.10/site-packages/langchain/agents/structured_chat/base.pyobservation_prefix)      z&StructuredChatAgent.observation_prefixc                 C   r'   )z#Prefix to append the llm call with.zThought:r(   r)   r(   r(   r+   
llm_prefix.   r-   zStructuredChatAgent.llm_prefixintermediate_stepsc                    s0   t  |}t|tstd|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	__class__r(   r+   r1   3   s   
z)StructuredChatAgent._construct_scratchpadtoolsNc                 C   s   d S Nr(   )clsr8   r(   r(   r+   _validate_toolsB      z#StructuredChatAgent._validate_toolsllmkwargsc                 K   s   t j|dS )Nr=   )r   from_llm)r:   r=   r>   r(   r(   r+   _get_default_output_parserF   s   z.StructuredChatAgent._get_default_output_parserc                 C   s   dgS )NzObservation:r(   r)   r(   r(   r+   _stopL   s   zStructuredChatAgent._stopprefixsuffixhuman_message_templateformat_instructionsinput_variablesmemory_promptsc                 C   s   g }|D ] }	t ddt ddt|	j}
||	j d|	j d|
  qd|}dd	d
 |D }|j|d}d||||g}|d u rKddg}|pNg }t	
|g|t
|}t||dS )N}z}}{z{{z: z, args: 
, c                 S      g | ]}|j qS r(   name.0toolr(   r(   r+   
<listcomp>`       z5StructuredChatAgent.create_prompt.<locals>.<listcomp>)
tool_namesz

inputr5   )rG   messages)resubr3   argsappendrO   descriptionjoinformatr   from_templater   r   )r:   r8   rC   rD   rE   rF   rG   rH   tool_stringsrR   args_schemaformatted_toolsrU   template_memory_promptsrW   r(   r(   r+   create_promptP   s$    
z!StructuredChatAgent.create_promptcallback_managerc              	   K   sd   |  | | j||||||	|
d}t|||d}dd |D }|p&| j|d}| d|||d|S )	z)Construct an agent from an LLM and tools.)rC   rD   rE   rF   rG   rH   )r=   promptrf   c                 S   rM   r(   rN   rP   r(   r(   r+   rS      rT   z:StructuredChatAgent.from_llm_and_tools.<locals>.<listcomp>r?   )	llm_chainallowed_toolsr%   Nr(   )r;   re   r   rA   )r:   r=   r8   rf   r%   rC   rD   rE   rF   rG   rH   r>   rg   rh   rU   _output_parserr(   r(   r+   from_llm_and_toolsm   s0   
	z&StructuredChatAgent.from_llm_and_toolsc                 C   s   t r9   )r4   r)   r(   r(   r+   _agent_type   r<   zStructuredChatAgent._agent_typer9   )%__name__
__module____qualname____doc__r   r   r%   r   __annotations__propertyr3   r,   r.   r   r   r	   r1   classmethodr   r   r;   r   r   r   rA   rB   r   r   HUMAN_MESSAGE_TEMPLATEr   r   re   r
   r   rk   rl   __classcell__r(   r(   r6   r+   r#       s   
 

		


'r#   T)stop_sequencer=   r8   rg   tools_rendererrv   r&   c          	      C   s   h d |jt|j }|rtd| |j|t|ddd |D d}|r;|du r2dgn|}| j|d	}n| }tj	d
d d|B |B t
 B }|S )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),
                ]
            )
    >   r8   rU   r5   z#Prompt missing required variables: rL   c                 S   rM   r(   rN   )rQ   tr(   r(   r+   rS     rT   z0create_structured_chat_agent.<locals>.<listcomp>)r8   rU   Tz
Observation)stopc                 S   s   t | d S )Nr/   r   )xr(   r(   r+   <lambda>&  s    z.create_structured_chat_agent.<locals>.<lambda>)r5   )
differencerG   listpartial_variablesr4   partialr]   bindr   assignr   )	r=   r8   rg   rw   rv   missing_varsry   llm_with_stopagentr(   r(   r+   r       s0   z
)5rX   typingr   r   r   r   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   rt   r#   boolr3   r    r(   r(   r(   r+   <module>   sL     }