o
    Jjg                     @  s   d dl mZ d dlmZmZmZ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mZ d dlmZ d d	lmZ d d
lmZ defdddddZdS )    )annotations)ListOptionalSequenceUnion)BaseLanguageModel)BasePromptTemplate)RunnableRunnablePassthrough)BaseTool)ToolsRendererrender_text_description)AgentOutputParserformat_log_to_str)ReActSingleInputOutputParserNT)stop_sequencellmr   toolsSequence[BaseTool]promptr   output_parserOptional[AgentOutputParser]tools_rendererr   r   Union[bool, List[str]]returnr	   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| }|pAt }t	j
d
d d|B |B |B }	|	S )a  Create an agent that uses ReAct prompting.

    Based on paper "ReAct: Synergizing Reasoning and Acting in Language Models"
    (https://arxiv.org/abs/2210.03629)

    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.
        output_parser: AgentOutputParser for parse the LLM output.
        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 "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.

    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.llms import OpenAI
            from langchain.agents import AgentExecutor, create_react_agent

            prompt = hub.pull("hwchase17/react")
            model = OpenAI()
            tools = ...

            agent = create_react_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 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 PromptTemplate

            template = '''Answer the following questions as best you can. You have access to the following tools:

            {tools}

            Use the following format:

            Question: the input question you must answer
            Thought: you should always think about what to do
            Action: the action to take, should be one of [{tool_names}]
            Action Input: the input to the action
            Observation: the result of the action
            ... (this Thought/Action/Action Input/Observation can repeat N times)
            Thought: I now know the final answer
            Final Answer: the final answer to the original input question

            Begin!

            Question: {input}
            Thought:{agent_scratchpad}'''

            prompt = PromptTemplate.from_template(template)
    >   r   
tool_namesagent_scratchpadz#Prompt missing required variables: z, c                 S  s   g | ]}|j qS  )name).0tr   r   T/var/www/html/zoom/venv/lib/python3.10/site-packages/langchain/agents/react/agent.py
<listcomp>y   s    z&create_react_agent.<locals>.<listcomp>)r   r   Tz
Observation)stopc                 S  s   t | d S )Nintermediate_stepsr   )xr   r   r"   <lambda>   s    z$create_react_agent.<locals>.<lambda>)r   )
differenceinput_variableslistpartial_variables
ValueErrorpartialjoinbindr   r
   assign)
r   r   r   r   r   r   missing_varsr$   llm_with_stopagentr   r   r"   create_react_agent   s2   a

r4   )r   r   r   r   r   r   r   r   r   r   r   r   r   r	   )
__future__r   typingr   r   r   r   langchain_core.language_modelsr   langchain_core.promptsr   langchain_core.runnablesr	   r
   langchain_core.toolsr   langchain_core.tools.renderr   r   langchain.agentsr   "langchain.agents.format_scratchpadr   langchain.agents.output_parsersr   r4   r   r   r   r"   <module>   s    