
    Ng                     p   d dl mZ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 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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%  eddd           G d de                      Z&efdddedee         dededee'ee(         f         defdZ)dS )     )AnyListSequenceTupleUnion)
deprecated)AgentActionAgentFinish)	Callbacks)BaseLanguageModel)BasePromptTemplate)AIMessagePromptTemplateChatPromptTemplate)RunnableRunnablePassthrough)BaseTool)ToolsRendererrender_text_description)BaseSingleActionAgent
format_xmlXMLAgentOutputParser)agent_instructions)LLMChainz0.1.0create_xml_agentz1.0)alternativeremovalc                   (   e Zd ZU dZee         ed<   	 eed<   	 edee	         fd            Z
edefd            Zedefd            Z	 dd	eeee	f                  d
ededeeef         fdZ	 dd	eeee	f                  d
ededeeef         fdZdS )XMLAgentaO  Agent that uses XML tags.

    Args:
        tools: list of tools the agent can choose from
        llm_chain: The LLMChain to call to predict the next action

    Examples:

        .. code-block:: python

            from langchain.agents import XMLAgent
            from langchain

            tools = ...
            model =


    tools	llm_chainreturnc                     dgS )Ninput )selfs    U/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain/agents/xml/base.py
input_keyszXMLAgent.input_keys.   s
    y    c                  b    t          j        t                    } | t          j        d          z   S )Nz{intermediate_steps})r   from_templater   r   )base_prompts    r(   get_default_promptzXMLAgent.get_default_prompt2   s3    (67IJJ4B"
 
 
 	
r*   c                      t                      S Nr   r&   r*   r(   get_default_output_parserz"XMLAgent.get_default_output_parser9   s    #%%%r*   Nintermediate_steps	callbackskwargsc           	          d}|D ]\  }}|d|j          d|j         d| dz  }d}| j        D ]}||j         d|j         dz  }|||d         d	d
gd}	|                     |	|          }
|
| j        j                 S N z<tool>z</tool><tool_input>z</tool_input><observation>z</observation>z: 
r%   </tool_input>z</final_answer>)r2   r!   questionstop)r3   )tool
tool_inputr!   namedescriptionr"   
output_keyr'   r2   r3   r4   logactionobservationr!   r<   inputsresponses              r(   planzXMLAgent.plan=   s     #5 	 	FKI I I9J I I-8I I ICC J 	: 	:D	99T%59999EE"%w$&78	
 
 >>&I>>>122r*   c           	        K   d}|D ]\  }}|d|j          d|j         d| dz  }d}| j        D ]}||j         d|j         dz  }|||d         d	d
gd}	| j                            |	|           d {V }
|
| j        j                 S r6   )r<   r=   r!   r>   r?   r"   acallr@   rA   s              r(   aplanzXMLAgent.aplanU   s      #5 	 	FKI I I9J I I-8I I ICC J 	: 	:D	99T%59999EE"%w$&78	
 
 --f	-JJJJJJJJ122r*   r0   )__name__
__module____qualname____doc__r   r   __annotations__r   propertystrr)   staticmethodr   r.   r   r1   r   r	   r   r   r   r
   rG   rJ   r&   r*   r(   r    r       sw         & >1)DI    X 
 2 
 
 
 \
 &'; & & & \&  $3 3 {C'7!893 3 	3
 
{K'	(3 3 3 36  $3 3 {C'7!893 3 	3
 
{K'	(3 3 3 3 3 3r*   r    T)stop_sequencellmr!   prompttools_rendererrS   r#   c                   ddh                     |j        t          |j                  z             }|rt	          d|           |                     |t          |                              }|r |du rdgn|}|                     |          }n| }t          j        d 	          |z  |z  t                      z  }|S )
a  Create an agent that uses XML to format its logic.

    Args:
        llm: LLM to use as the agent.
        tools: Tools this agent has access to.
        prompt: The prompt to use, must have input keys
            `tools`: contains descriptions for each tool.
            `agent_scratchpad`: contains previous agent actions and tool outputs.
        tools_renderer: This controls how the tools are converted into a string and
            then passed into the LLM. Default is `render_text_description`.
        stop_sequence: bool or list of str.
            If True, adds a stop token of "</tool_input>" 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.

    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.

    Example:

        .. code-block:: python

            from langchain import hub
            from langchain_community.chat_models import ChatAnthropic
            from langchain.agents import AgentExecutor, create_xml_agent

            prompt = hub.pull("hwchase17/xml-agent-convo")
            model = ChatAnthropic(model="claude-3-haiku-20240307")
            tools = ...

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

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

            # Use with chat history
            from langchain_core.messages import AIMessage, HumanMessage
            agent_executor.invoke(
                {
                    "input": "what's my name?",
                    # Notice that chat_history is a string
                    # since this prompt is aimed at LLMs, not chat models
                    "chat_history": "Human: My name is Bob\nAI: Hello Bob!",
                }
            )

    Prompt:

        The prompt must have input keys:
            * `tools`: contains descriptions for each tool.
            * `agent_scratchpad`: contains previous agent actions and tool outputs as an XML string.

        Here's an example:

        .. code-block:: python

            from langchain_core.prompts import PromptTemplate

            template = '''You are a helpful assistant. Help the user answer any questions.

            You have access to the following tools:

            {tools}

            In order to use a tool, you can use <tool></tool> and <tool_input></tool_input> tags. You will then get back a response in the form <observation></observation>
            For example, if you have a tool called 'search' that could run a google search, in order to search for the weather in SF you would respond:

            <tool>search</tool><tool_input>weather in SF</tool_input>
            <observation>64 degrees</observation>

            When you are done, respond with a final answer between <final_answer></final_answer>. For example:

            <final_answer>The weather in SF is 64 degrees</final_answer>

            Begin!

            Previous Conversation:
            {chat_history}

            Question: {input}
            {agent_scratchpad}'''
            prompt = PromptTemplate.from_template(template)
    r!   agent_scratchpadz#Prompt missing required variables: )r!   Tr9   )r;   c                 ,    t          | d                   S )Nr2   r   )xs    r(   <lambda>z"create_xml_agent.<locals>.<lambda>   s    z!4H2I'J'J r*   )rX   )

differenceinput_variableslistpartial_variables
ValueErrorpartialbindr   assignr   )	rT   r!   rU   rV   rS   missing_varsr;   llm_with_stopagents	            r(   r   r   n   s   @ /0;;f&>!?!?? L  OM|MMNNN^^nT%[[))   F  $1T$9$9  }d++ 	"JJ	
 	
 	
 	 		
 
 
 	! 
 Lr*   N)*typingr   r   r   r   r   langchain_core._apir   langchain_core.agentsr	   r
   langchain_core.callbacksr   langchain_core.language_modelsr   langchain_core.prompts.baser   langchain_core.prompts.chatr   r   langchain_core.runnablesr   r   langchain_core.toolsr   langchain_core.tools.renderr   r   langchain.agents.agentr   "langchain.agents.format_scratchpadr   langchain.agents.output_parsersr   langchain.agents.xml.promptr   langchain.chains.llmr   r    boolrQ   r   r&   r*   r(   <module>rw      s'   4 4 4 4 4 4 4 4 4 4 4 4 4 4 * * * * * * : : : : : : : : . . . . . . < < < < < < : : : : : : S S S S S S S S B B B B B B B B ) ) ) ) ) ) N N N N N N N N 8 8 8 8 8 8 9 9 9 9 9 9 @ @ @ @ @ @ : : : : : : ) ) ) ) ) ) G!3UCCCV3 V3 V3 V3 V3$ V3 V3 DCV3z %<	x -1x x x	xHx x "	x tCy)x x x x x x xr*   