U
    hv                     @  s  d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlmZmZmZmZmZmZmZmZmZmZmZ ddlZddlmZ ddlmZmZm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/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZG ddlHmIZI ddlJmKZK eLeMZNG dd de4ZOG dd de4ZPG d d! d!e,eeef  ZQG d"d# d#e,eee ef  ZRG d$d% d%eOZSG d&d' d'ePZTed(d)d*d+G d,d- d-eOZUed(d)d*d+G d.d/ d/eOZVG d0d1 d1e=ZWeeeeef  ZXeeSeTf ZYG d2d3 d3eGZZdS )4zEChain that takes in an input and produces an action and action input.    )annotationsN)abstractmethod)Path)AnyAsyncIteratorCallableDictIteratorListOptionalSequenceTupleUnioncast)
deprecated)AgentActionAgentFinish	AgentStep)AsyncCallbackManagerForChainRunAsyncCallbackManagerForToolRunBaseCallbackManagerCallbackManagerForChainRunCallbackManagerForToolRun	Callbacks)OutputParserException)BaseLanguageModel)BaseMessage)BaseOutputParser)BasePromptTemplate)FewShotPromptTemplate)PromptTemplate)	BaseModelroot_validator)RunnableRunnableConfigensure_config)AddableDict)BaseTool)get_color_mapping)AgentExecutorIterator)	AgentType)InvalidTool)Chain)LLMChain)asyncio_timeoutc                      s   e Zd ZdZeddddZddddZed-d
ddddddZed.d
ddddddZ	eeddddZ
dd
dddddZed/ddddd dddZeddd d!Zdd"d# fd$d%Zd&d'd(d)d*Zd"dd+d,Z  ZS )0BaseSingleActionAgentzBase Single Action Agent class.	List[str]returnc                 C  s   dgS Return values of the agent.output selfr6   r6   :/tmp/pip-unpacked-wheel-bo69hh5q/langchain/agents/agent.pyreturn_values>   s    z#BaseSingleActionAgent.return_valuesOptional[List[str]]c                 C  s   d S Nr6   r7   r6   r6   r9   get_allowed_toolsC   s    z'BaseSingleActionAgent.get_allowed_toolsNList[Tuple[AgentAction, str]]r   r   Union[AgentAction, AgentFinish]intermediate_steps	callbackskwargsr2   c                 K  s   dS )0  Given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        Nr6   r8   rA   rB   rC   r6   r6   r9   planF   s    zBaseSingleActionAgent.planc                   s   dS )6  Async given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        Nr6   rE   r6   r6   r9   aplanY   s    zBaseSingleActionAgent.aplanc                 C  s   dS 7Return the input keys.

        :meta private:
        Nr6   r7   r6   r6   r9   
input_keysl   s    z BaseSingleActionAgent.input_keysstrr   early_stopping_methodrA   rC   r2   c                 K  s*   |dkrt ddidS td| ddS )  Return response when agent has been stopped due to max iterations.

        Args:
            early_stopping_method: Method to use for early stopping.
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            **kwargs: User inputs.

        Returns:
            AgentFinish: Agent finish object.

        Raises:
            ValueError: If `early_stopping_method` is not supported.
        forcer5   3Agent stopped due to iteration limit or time limit. 'Got unsupported early_stopping_method ``Nr   
ValueErrorr8   rN   rA   rC   r6   r6   r9   return_stopped_responset   s     
z-BaseSingleActionAgent.return_stopped_responser   Sequence[BaseTool]Optional[BaseCallbackManager])llmtoolscallback_managerrC   r2   c                 K  s   t dS )a.  Construct an agent from an LLM and tools.

        Args:
            llm: Language model to use.
            tools: Tools to use.
            callback_manager: Callback manager to use.
            kwargs: Additional arguments.

        Returns:
            BaseSingleActionAgent: Agent object.
        NNotImplementedError)clsr[   r\   r]   rC   r6   r6   r9   from_llm_and_tools   s    z(BaseSingleActionAgent.from_llm_and_toolsc                 C  s   t dS z#Return Identifier of an agent type.Nr^   r7   r6   r6   r9   _agent_type   s    z!BaseSingleActionAgent._agent_typer   rC   r2   c                   s\   t   }z
| j}W n tk
r,   d}Y nX t|trHt|j|d< n|dk	rX||d< |S )z{Return dictionary representation of agent.

        Returns:
            Dict: Dictionary representation of agent.
        N_type)superdictrc   r_   
isinstancer*   rL   value)r8   rC   _dictre   	__class__r6   r9   rg      s    



zBaseSingleActionAgent.dictUnion[Path, str]None	file_pathr2   c              	   C  s   t |trt|}n|}|j}|jddd |  }d|krLtd|  d|jdkr~t|d}t	j
||dd	 W 5 Q R X nB|jd
rt|d}tj
||dd W 5 Q R X nt| ddS )zSave the agent.

        Args:
            file_path: Path to file to save the agent to.

        Example:
        .. code-block:: python

            # If working with agent executor
            agent.agent.save(file_path="path/agent.yaml")
        Tparentsexist_okre   Agent z does not support saving.jsonw   indentz.yamlz.ymlFZdefault_flow_style must be json or yamlN)rh   rL   r   parentmkdirrg   r_   suffixopenjsondumpendswithyamlrV   )r8   rp   	save_pathdirectory_path
agent_dictfr6   r6   r9   save   s    


zBaseSingleActionAgent.savec                 C  s   i S #Return logging kwargs for tool run.r6   r7   r6   r6   r9   tool_run_logging_kwargs   s    z-BaseSingleActionAgent.tool_run_logging_kwargs)N)N)N)__name__
__module____qualname____doc__propertyr:   r=   r   rF   rH   rK   rX   classmethodra   rc   rg   r   r   __classcell__r6   r6   rk   r9   r/   ;   s,      #r/   c                      s   e Zd ZdZeddddZddddZed'd
ddddddZed(d
ddddddZ	eeddddZ
dd
dddddZeddddZddd fddZd d!d"d#d$Zddd%d&Z  ZS ))BaseMultiActionAgentzBase Multi Action Agent class.r0   r1   c                 C  s   dgS r3   r6   r7   r6   r6   r9   r:      s    z"BaseMultiActionAgent.return_valuesr;   c                 C  s   dS )z]Get allowed tools.

        Returns:
            Optional[List[str]]: Allowed tools.
        Nr6   r7   r6   r6   r9   r=      s    z&BaseMultiActionAgent.get_allowed_toolsNr>   r   r   %Union[List[AgentAction], AgentFinish]r@   c                 K  s   dS )a5  Given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with the observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Actions specifying what tool to use.
        Nr6   rE   r6   r6   r9   rF      s    zBaseMultiActionAgent.planc                   s   dS )a;  Async given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with the observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Actions specifying what tool to use.
        Nr6   rE   r6   r6   r9   rH     s    zBaseMultiActionAgent.aplanc                 C  s   dS rI   r6   r7   r6   r6   r9   rK     s    zBaseMultiActionAgent.input_keysrL   r   rM   c                 K  s*   |dkrt ddidS td| ddS )rO   rP   r5   z$Agent stopped due to max iterations.rR   rS   rT   NrU   rW   r6   r6   r9   rX   #  s
    
z,BaseMultiActionAgent.return_stopped_responsec                 C  s   t dS rb   r^   r7   r6   r6   r9   rc   ?  s    z BaseMultiActionAgent._agent_typer   rd   c                   s6   t   }zt| j|d< W n tk
r0   Y nX |S )*Return dictionary representation of agent.re   )rf   rg   rL   rc   r_   r8   rC   rj   rk   r6   r9   rg   D  s    
zBaseMultiActionAgent.dictrm   rn   ro   c              	   C  s   t |trt|}n|}|  }d|kr8td|  d|j}|jddd |jdkr~t|d}t	j
||dd	 W 5 Q R X nB|jd
rt|d}tj
||dd W 5 Q R X nt| ddS )a  Save the agent.

        Args:
            file_path: Path to file to save the agent to.

        Raises:
            NotImplementedError: If agent does not support saving.
            ValueError: If file_path is not json or yaml.

        Example:
        .. code-block:: python

            # If working with agent executor
            agent.agent.save(file_path="path/agent.yaml")
        re   rt   z does not support saving.Trq   ru   rv   rw   rx   rz   Fr{   r|   N)rh   rL   r   rg   r_   r}   r~   r   r   r   r   r   r   rV   )r8   rp   r   r   r   r   r6   r6   r9   r   M  s    


zBaseMultiActionAgent.savec                 C  s   i S r   r6   r7   r6   r6   r9   r   t  s    z,BaseMultiActionAgent.tool_run_logging_kwargs)N)N)r   r   r   r   r   r:   r=   r   rF   rH   rK   rX   rc   rg   r   r   r   r6   r6   rk   r9   r      s&     	'r   c                   @  s$   e Zd ZdZedddddZdS )AgentOutputParserz=Base class for parsing agent output into agent action/finish.rL   r?   textr2   c                 C  s   dS )z$Parse text into agent action/finish.Nr6   r8   r   r6   r6   r9   parse}  s    zAgentOutputParser.parseNr   r   r   r   r   r   r6   r6   r6   r9   r   z  s   r   c                   @  s$   e Zd ZdZedddddZdS )MultiActionAgentOutputParserzBase class for parsing agent output into agent actions/finish.

    This is used for agents that can return multiple actions.
    rL   r   r   c                 C  s   dS )zParse text into agent actions/finish.

        Args:
            text: Text to parse.

        Returns:
            Union[List[AgentAction], AgentFinish]:
                List of agent actions or agent finish.
        Nr6   r   r6   r6   r9   r     s    z"MultiActionAgentOutputParser.parseNr   r6   r6   r6   r9   r     s   r   c                   @  s   e Zd ZU dZded< g Zded< g Zded< dZded	< G d
d dZe	ddddZ
e	ddddZddddddddZddddddddZdS )RunnableAgentAgent powered by Runnables.z/Runnable[dict, Union[AgentAction, AgentFinish]]runnabler0   input_keys_argreturn_keys_argTboolstream_runnablec                   @  s   e Zd ZdZdS )zRunnableAgent.ConfigTNr   r   r   Zarbitrary_types_allowedr6   r6   r6   r9   Config  s   r   r1   c                 C  s   | j S r4   r   r7   r6   r6   r9   r:     s    zRunnableAgent.return_valuesc                 C  s   | j S )zReturn the input keys.r   r7   r6   r6   r9   rK     s    zRunnableAgent.input_keysNr>   r   r   r?   r@   c                 K  s`   |d|i}d}| j rH| jj|d|idD ]}|dkr<|}q*||7 }q*n| jj|d|id}|S aP  Based on past history and current inputs, decide what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with the observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        rA   NrB   configr   r   streamZinvoker8   rA   rB   rC   inputsfinal_outputchunkr6   r6   r9   rF     s    zRunnableAgent.planc                   sp   |d|i}d}| j rR| jj|d|id2 z"3 dH W }|dkrD|}q*||7 }q*6 n| jj|d|idI dH }|S aR  Async based on past history and current inputs, decide what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        rA   NrB   r   r   r   astreamZainvoker   r6   r6   r9   rH     s      zRunnableAgent.aplan)N)Nr   r   r   r   __annotations__r   r   r   r   r   r:   rK   rF   rH   r6   r6   r6   r9   r     s   
	 ' r   c                   @  s   e Zd ZU dZded< g Zded< g Zded< dZded	< G d
d dZe	ddddZ
e	ddddZddddddddZddddddddZdS )RunnableMultiActionAgentr   z5Runnable[dict, Union[List[AgentAction], AgentFinish]]r   r0   r   r   Tr   r   c                   @  s   e Zd ZdZdS )zRunnableMultiActionAgent.ConfigTNr   r6   r6   r6   r9   r     s   r   r1   c                 C  s   | j S r   r   r7   r6   r6   r9   r:     s    z&RunnableMultiActionAgent.return_valuesc                 C  s   | j S )QReturn the input keys.

        Returns:
            List of input keys.
        r   r7   r6   r6   r9   rK     s    z#RunnableMultiActionAgent.input_keysNr>   r   r   r   r@   c                 K  s`   |d|i}d}| j rH| jj|d|idD ]}|dkr<|}q*||7 }q*n| jj|d|id}|S r   r   r   r6   r6   r9   rF   $  s    zRunnableMultiActionAgent.planc                   sp   |d|i}d}| j rR| jj|d|id2 z"3 dH W }|dkrD|}q*||7 }q*6 n| jj|d|idI dH }|S r   r   r   r6   r6   r9   rH   K  s      zRunnableMultiActionAgent.aplan)N)Nr   r6   r6   r6   r9   r     s   
	 * r   z0.1.0zpUse new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc.z1.0)messageZremovalc                      s   e Zd ZU dZded< ded< ded< eddd	d
Zddd fddZddddddddZddddddddZ	ddddZ
  ZS )LLMSingleActionAgentz$Base class for single action agents.r-   	llm_chainr   output_parserr0   stopr1   c                 C  s   t t| jjdh S )r   rA   listsetr   rK   r7   r6   r6   r9   rK     s    zLLMSingleActionAgent.input_keysr   r   rd   c                   s   t   }|d= |S r   r   rf   rg   r   rk   r6   r9   rg     s    
zLLMSingleActionAgent.dictNr>   r   r?   r@   c                 K  s(   | j jf || j|d|}| j|S )a4  Given input, decided what to do.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with the observations.
            callbacks: Callbacks to run.
            **kwargs: User inputs.

        Returns:
            Action specifying what tool to use.
        rA   r   rB   )r   runr   r   r   r8   rA   rB   rC   r5   r6   r6   r9   rF     s    zLLMSingleActionAgent.planc                   s.   | j jf || j|d|I dH }| j|S )rG   r   N)r   arunr   r   r   r   r6   r6   r9   rH     s    zLLMSingleActionAgent.aplanc                 C  s"   dt | jdkrdn| jd dS )r   rR   r   
llm_prefixobservation_prefix)lenr   r7   r6   r6   r9   r     s    z,LLMSingleActionAgent.tool_run_logging_kwargs)N)N)r   r   r   r   r   r   rK   rg   rF   rH   r   r   r6   r6   rk   r9   r   w  s   
		  r   c                	      s  e Zd ZU dZded< ded< dZded< d	d
d fddZddddZeddddZ	dddddZ
eddddZdddddZdLddd	d d!d"d#ZdMddd	d d!d$d%Zdd	d&d'd(d)Zeddd*d+Zed,d-d.d
d
d/d0d1Zeeddd2d3Zeeddd4d5Zeed6d7d8d9d:Zed6d;d8d<d=Zeed	ddd>d?ZedNd@d6dAdBd	d dCdDdEZddd	dFdGdHdIZd
ddJdKZ  ZS )OAgentzAgent that calls the language model and deciding the action.

    This is driven by a LLMChain. The prompt in the LLMChain MUST include
    a variable called "agent_scratchpad" where the agent can put its
    intermediary work.
    r-   r   r   r   Nr;   allowed_toolsr   r   rd   c                   s   t   }|d= |S r   r   r   rk   r6   r9   rg     s    
z
Agent.dictr1   c                 C  s   | j S )zGet allowed tools.)r   r7   r6   r6   r9   r=     s    zAgent.get_allowed_toolsr0   c                 C  s   dgS r3   r6   r7   r6   r6   r9   r:     s    zAgent.return_valuesrL   r   c                 C  s   t ddS )zsFix the text.

        Args:
            text: Text to fix.

        Returns:
            str: Fixed text.
        z(fix_text not implemented for this agent.NrV   r   r6   r6   r9   	_fix_text  s    	zAgent._fix_textc                 C  s    d| j   d| j   gS )N
z
	)r   rstripr7   r6   r6   r9   _stop  s    zAgent._stopr>   zUnion[str, List[BaseMessage]]rA   r2   c                 C  s<   d}|D ].\}}||j 7 }|d| j | d| j 7 }q|S )zJConstruct the scratchpad that lets the agent continue its thought process.rR   r   )logr   r   )r8   rA   thoughtsactionobservationr6   r6   r9   _construct_scratchpad
  s
    
zAgent._construct_scratchpadr   r?   r@   c                 K  s0   | j |f|}| jjf d|i|}| j|S )rD   rB   )get_full_inputsr   predictr   r   )r8   rA   rB   rC   full_inputsfull_outputr6   r6   r9   rF     s    z
Agent.planc                   s@   | j |f|}| jjf d|i|I dH }| j|I dH }|S )rG   rB   N)r   r   Zapredictr   Zaparse)r8   rA   rB   rC   r   r   Zagent_outputr6   r6   r9   rH   )  s    zAgent.aplanDict[str, Any])rA   rC   r2   c                 K  s"   |  |}|| jd}||}|S )a1  Create the full inputs for the LLMChain from intermediate steps.

        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            **kwargs: User inputs.

        Returns:
            Dict[str, Any]: Full inputs for the LLMChain.
        agent_scratchpadr   )r   r   )r8   rA   rC   r   
new_inputsr   r6   r6   r9   r   ?  s    
zAgent.get_full_inputsc                 C  s   t t| jjdh S )rJ   r   r   r7   r6   r6   r9   rK   Q  s    zAgent.input_keysFTpreZskip_on_failurevaluesr2   c                 C  st   |d j }d|jkrptd |jd t|trD| jd7  _n,t|tr^| j	d7  _	nt
dt| |S )aF  Validate that prompt matches format.

        Args:
            values: Values to validate.

        Returns:
            Dict: Validated values.

        Raises:
            ValueError: If `agent_scratchpad` is not in prompt.input_variables
             and prompt is not a FewShotPromptTemplate or a PromptTemplate.
        r   r   zl`agent_scratchpad` should be a variable in prompt.input_variables. Did not find it, so adding it at the end.z
{agent_scratchpad}zGot unexpected prompt type )promptZinput_variablesloggerwarningappendrh   r    templater   r   rV   type)r`   r   r   r6   r6   r9   validate_promptY  s    



zAgent.validate_promptc                 C  s   dS )z&Prefix to append the observation with.Nr6   r7   r6   r6   r9   r   v  s    zAgent.observation_prefixc                 C  s   dS )z#Prefix to append the LLM call with.Nr6   r7   r6   r6   r9   r   {  s    zAgent.llm_prefixrY   r   )r\   r2   c                 C  s   dS )zCreate a prompt for this class.

        Args:
            tools: Tools to use.

        Returns:
            BasePromptTemplate: Prompt template.
        Nr6   r`   r\   r6   r6   r9   create_prompt  s    zAgent.create_promptrn   c                 C  s   dS )zgValidate that appropriate tools are passed in.

        Args:
            tools: Tools to use.
        Nr6   r   r6   r6   r9   _validate_tools  s    zAgent._validate_toolsc                 K  s   dS )z)Get default output parser for this class.Nr6   )r`   rC   r6   r6   r9   _get_default_output_parser  s    z Agent._get_default_output_parserr   rZ   zOptional[AgentOutputParser])r[   r\   r]   r   rC   r2   c           	      K  sN   |  | t|| ||d}dd |D }|p6|  }| f |||d|S )aO  Construct an agent from an LLM and tools.

        Args:
            llm: Language model to use.
            tools: Tools to use.
            callback_manager: Callback manager to use.
            output_parser: Output parser to use.
            kwargs: Additional arguments.

        Returns:
            Agent: Agent object.
        )r[   r   r]   c                 S  s   g | ]
}|j qS r6   name.0toolr6   r6   r9   
<listcomp>  s     z,Agent.from_llm_and_tools.<locals>.<listcomp>)r   r   r   )r   r-   r   r   )	r`   r[   r\   r]   r   rC   r   Z
tool_namesZ_output_parserr6   r6   r9   ra     s    
zAgent.from_llm_and_toolsr   rM   c                 K  s   |dkrt ddidS |dkrd}|D ].\}}||j7 }|d| j | d| j 7 }q&|d7 }|| jd}||}| jjf |}	| j|	}
t	|
t r|
S t d|	i|	S nt
d	| d
S )a  Return response when agent has been stopped due to max iterations.

        Args:
            early_stopping_method: Method to use for early stopping.
            intermediate_steps: Steps the LLM has taken to date,
                along with observations.
            **kwargs: User inputs.

        Returns:
            AgentFinish: Agent finish object.

        Raises:
            ValueError: If `early_stopping_method` is not in ['force', 'generate'].
        rP   r5   rQ   rR   generater   zB

I now need to return a final answer based on the previous steps:r   zBearly_stopping_method should be one of `force` or `generate`, got N)r   r   r   r   r   r   r   r   r   rh   rV   )r8   rN   rA   rC   r   r   r   r   r   r   Zparsed_outputr6   r6   r9   rX     s2     

zAgent.return_stopped_responsec                 C  s   | j | jdS )r   r   r   r7   r6   r6   r9   r     s    zAgent.tool_run_logging_kwargs)N)N)NN)r   r   r   r   r   r   rg   r=   r   r:   r   r   r   rF   rH   r   rK   r"   r   r   r   r   r   r   r   r   ra   rX   r   r   r6   r6   rk   r9   r     sR   
	  

	  #7r   c                   @  sR   e Zd ZU dZdZded< dZded< ddddd	d
dZddddd	ddZdS )ExceptionToolz!Tool that just returns the query.
_ExceptionrL   r   zException tooldescriptionNz#Optional[CallbackManagerForToolRun])queryrun_managerr2   c                 C  s   |S r<   r6   r8   r   r   r6   r6   r9   _run  s    zExceptionTool._runz(Optional[AsyncCallbackManagerForToolRun]c                   s   |S r<   r6   r   r6   r6   r9   _arun  s    zExceptionTool._arun)N)N)	r   r   r   r   r   r   r   r   r   r6   r6   r6   r9   r     s   
 
 r   c                   @  s  e Zd ZU dZded< ded< dZded< d	Zd
ed< dZded< dZded< dZ	ded< dZ
ded< ed|ddddd dddZeddddddd d!Zedd"dddd#d$Zed%d&d'd(Zd)d*d+d,d-Zd)d*d+d.d/Zd}ddd0ddddd1d2d3d4Zed5d&d6d7Zed5d&d8d9Zdd:d;d<d=Zd>d?dd@dAdBZd~dCdDdEdFdGdHdIZddCdDdJdFdGdKdLZdMdNddOdPZddQdRdRdSdEdNdTdUdVZddQdRdRdSdEdWdTdXdYZddQdRdZdEd[d\d]d^ZddQdRdRdSdJdNdTd_d`ZddQdRdRdSdJdadTdbdcZ ddQdRdZdJd[d\dddeZ!ddRdEdFdfdgdhZ"ddRdJdRdfdidjZ#dkdldmdndoZ$dSdSdpdqdrZ%ddsdtddudvdwdxZ&ddsdtddydvdzd{Z'dS )AgentExecutorzAgent that is using tools.z<Union[BaseSingleActionAgent, BaseMultiActionAgent, Runnable]agentrY   r\   Fr   return_intermediate_steps   zOptional[int]max_iterationsNzOptional[float]max_execution_timerP   rL   rN   z8Union[bool, str, Callable[[OutputParserException], str]]handle_parsing_errorszTUnion[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]]trim_intermediate_stepsr   r   )r  r\   rB   rC   r2   c                 K  s   | f |||d|S )a  Create from agent and tools.

        Args:
            agent: Agent to use.
            tools: Tools to use.
            callbacks: Callbacks to use.
            kwargs: Additional arguments.

        Returns:
            AgentExecutor: Agent executor object.
        )r  r\   rB   r6   )r`   r  r\   rB   rC   r6   r6   r9   from_agent_and_toolsI  s    z"AgentExecutor.from_agent_and_toolsTr   r   r   c                 C  s^   |d }|d }|  }|dk	rZt|tdd |D krZtd| ddd |D  d	|S )
a  Validate that tools are compatible with agent.

        Args:
            values: Values to validate.

        Returns:
            Dict: Validated values.

        Raises:
            ValueError: If allowed tools are different than provided tools.
        r  r\   Nc                 S  s   g | ]
}|j qS r6   r   r   r6   r6   r9   r   t  s     z0AgentExecutor.validate_tools.<locals>.<listcomp>zAllowed tools (z!) different than provided tools (c                 S  s   g | ]
}|j qS r6   r   r   r6   r6   r9   r   v  s     ))r=   r   rV   )r`   r   r  r\   r   r6   r6   r9   validate_toolsc  s    zAgentExecutor.validate_tools)r   c              
   C  s   | d}|rt|trz
|j}W n& tk
rH } zd}W 5 d}~X Y nX |ttt tf k}|	dd}|rt
||d|d< nt||d|d< |S )zConvert runnable to agent if passed in.

        Args:
            values: Values to validate.

        Returns:
            Dict: Validated values.
        r  FNr   T)r   r   )getrh   r#   Z
OutputType	Exceptionr   r
   r   r   popr   r   )r`   r   r  output_type_Zmulti_actionr   r6   r6   r9   validate_runnable_agent{  s$    


  
z%AgentExecutor.validate_runnable_agentz2Union[BaseSingleActionAgent, BaseMultiActionAgent]r1   c                 C  s"   t | jtrtt| jS | jS dS )aG  Type cast self.agent.

        The .agent attribute type includes Runnable, but is converted to one of
        RunnableAgentType in the validate_runnable_agent root_validator.

        To support instantiating with a Runnable, here we explicitly cast the type
        to reflect the changes made in the root_validator.
        N)rh   r  r#   r   RunnableAgentTyper7   r6   r6   r9   _action_agent  s    
zAgentExecutor._action_agentrm   rn   ro   c                 C  s   t ddS )zRaise error - saving not supported for Agent Executors.

        Args:
            file_path: Path to save to.

        Raises:
            ValueError: Saving not supported for agent executors.
        zpSaving not supported for agent executors. If you are trying to save the agent, please use the `.save_agent(...)`Nr   r8   rp   r6   r6   r9   r     s    	zAgentExecutor.savec                 C  s   | j |S )zZSave the underlying agent.

        Args:
            file_path: Path to save to.
        )r  r   r  r6   r6   r9   
save_agent  s    zAgentExecutor.save_agent)include_run_infoasync_r)   )r   rB   r  r  r2   c                C  s   t | ||| j|dS )ag  Enables iteration over steps taken to reach final output.

        Args:
            inputs: Inputs to the agent.
            callbacks: Callbacks to run.
            include_run_info: Whether to include run info.
            async_: Whether to run async. (Ignored)

        Returns:
            AgentExecutorIterator: Agent executor iterator object.
        )tagsr  )r)   r  )r8   r   rB   r  r  r6   r6   r9   iter  s    zAgentExecutor.iterr0   c                 C  s   | j jS )rJ   )r  rK   r7   r6   r6   r9   rK     s    zAgentExecutor.input_keysc                 C  s    | j r| jjdg S | jjS dS )z@Return the singular output key.

        :meta private:
        rA   N)r  r  r:   r7   r6   r6   r9   output_keys  s    zAgentExecutor.output_keysr'   )r   r2   c                 C  s   dd | j D | S )zLookup tool by name.

        Args:
            name: Name of tool.

        Returns:
            BaseTool: Tool object.
        c                 S  s   i | ]}|j |qS r6   r   r   r6   r6   r9   
<dictcomp>  s      z-AgentExecutor.lookup_tool.<locals>.<dictcomp>)r\   )r8   r   r6   r6   r9   lookup_tool  s    	zAgentExecutor.lookup_toolintfloat)
iterationstime_elapsedr2   c                 C  s4   | j d k	r|| j krdS | jd k	r0|| jkr0dS dS )NFT)r  r  )r8   r  r   r6   r6   r9   _should_continue  s    zAgentExecutor._should_continuer   r   z$Optional[CallbackManagerForChainRun]r   )r5   rA   r   r2   c                 C  s.   |r|j |d| jd |j}| jr*||d< |S Ngreen)colorverboserA   Zon_agent_finishr%  r:   r  r8   r5   rA   r   r   r6   r6   r9   _return  s    zAgentExecutor._returnz)Optional[AsyncCallbackManagerForChainRun]c                   s4   |r|j |d| jdI d H  |j}| jr0||d< |S r"  r&  r'  r6   r6   r9   _areturn  s      zAgentExecutor._areturnNextStepOutputz1Union[AgentFinish, List[Tuple[AgentAction, str]]]c                 C  s8   t |d tr&t|dkst|d S dd |D S d S )Nr     c                 S  s"   g | ]}t |tr|j|jfqS r6   )rh   r   r   r   r   ar6   r6   r9   r   &  s    
 z4AgentExecutor._consume_next_step.<locals>.<listcomp>)rh   r   r   AssertionError)r8   r   r6   r6   r9   _consume_next_step  s    z AgentExecutor._consume_next_stepzDict[str, BaseTool]zDict[str, str]r>   )name_to_tool_mapcolor_mappingr   rA   r   r2   c              
   C  s"   |  dd | |||||D S )Nc                 S  s   g | ]}|qS r6   r6   r,  r6   r6   r9   r   3  s   z1AgentExecutor._take_next_step.<locals>.<listcomp>)r/  _iter_next_stepr8   r0  r1  r   rA   r   r6   r6   r9   _take_next_step*  s    zAgentExecutor._take_next_stepz4Iterator[Union[AgentFinish, AgentAction, AgentStep]]c              
   c  s  z4|  |}| jj|fd|r$| ndi|}W n* tk
r^ } zt| jtr`| j }nd}|rztdt	| t	|}	t| jtr|j
rt	|j}
t	|j}	qd}
n2t| jt	r| j}
nt| jr| |}
ntdtd|
|	}|r|j|dd	 | j }t j|jf| jd|r,| ndd
|}
t||
dV  W Y dS d}~X Y nX t|trv|V  dS t|tr|g}n|}|D ]}|V  q|D ]}| ||||V  qdS )Take a single step in the thought-action-observation loop.

        Override this to take control of how the agent makes and acts on choices.
        rB   NFAn output parsing error occurred. In order to pass this error back to the agent and have it try again, pass `handle_parsing_errors=True` to the AgentExecutor. This is the error: Invalid or incomplete response.Got unexpected type of `handle_parsing_errors`r   r#  r$  r%  r$  rB   r   r   )_prepare_intermediate_stepsr  rF   	get_childr   rh   r  r   rV   rL   send_to_llmr   
llm_outputcallabler   on_agent_actionr   r   r   
tool_inputr%  r   r   _perform_agent_action)r8   r0  r1  r   rA   r   r5   eraise_errorr   r   tool_run_kwargsactionsagent_actionr6   r6   r9   r2  ?  st    





   zAgentExecutor._iter_next_stepr   r   )r0  r1  rH  r   r2   c           
      C  s   |r|j |dd |j|krx||j }|j}||j }| j }|rLd|d< |j|jf| j||rh| nd d|}	nD| j }t	 j|jt
| df| jd |r| nd d|}	t||	dS )Nr#  r9  rR   r   r:  Zrequested_tool_nameZavailable_tool_namesr;  )rA  r   return_directr  r   r   rB  r%  r=  r+   r   keysr   
r8   r0  r1  rH  r   r   rJ  r$  rF  r   r6   r6   r9   rC    s>    






z#AgentExecutor._perform_agent_actionc              
     s(   |  dd | |||||2 I d H S )Nc                   s   g | z3 d H W }|q6 S r<   r6   r,  r6   r6   r9   r     s   z2AgentExecutor._atake_next_step.<locals>.<listcomp>)r/  _aiter_next_stepr3  r6   r6   r9   _atake_next_step  s    
zAgentExecutor._atake_next_stepz9AsyncIterator[Union[AgentFinish, AgentAction, AgentStep]]c              
    s  z: |}jj|fdr$ ndi|I dH }W n tk
rT } ztjtrdj }nd}|r~tdt	| t	|}	tjtr|j
rt	|j}
t	|j}	qd}
n2tjt	rȈj}
ntjrވ|}
ntdtd|
|	}j }t j|jfjdr ndd|I dH }
t||
d	V  W Y dS d}~X Y nX t|trl|V  dS t|tr|g}n|}|D ]}|V  qtj fd
d|D  I dH }|D ]}|V  qdS )r5  rB   NFr6  r7  r8  r   r:  r;  c                   s   g | ]}  |qS r6   )_aperform_agent_action)r   rH  r1  r0  r   r8   r6   r9   r     s      z2AgentExecutor._aiter_next_step.<locals>.<listcomp>)r<  r  rH   r=  r   rh   r  r   rV   rL   r>  r   r?  r@  r   r   r   r   rB  r%  r   r   asyncioZgather)r8   r0  r1  r   rA   r   r5   rD  rE  r   r   rF  rG  rH  resultr   r6   rP  r9   rM    sp    







zAgentExecutor._aiter_next_stepc           
        s   |r|j || jddI d H  |j|kr||j }|j}||j }| j }|rVd|d< |j|jf| j||rr| nd d|I d H }	nJ| j }t	 j|jt
| df| jd |r| nd d|I d H }	t||	dS )Nr#  )r%  r$  rR   r   r:  rI  r;  )rA  r%  r   rJ  r  r   r   rB  r=  r+   r   rK  r   rL  r6   r6   r9   rO    sF      






z$AgentExecutor._aperform_agent_action)r   r   r2   c                 C  s   dd | j D }tdd | j D ddgd}g }d}d	}t }| ||r| j|||||d
}	t|	trz| j|	||d
S ||	 t	|	dkr|	d }
| 
|
}|dk	r| j|||d
S |d7 }t | }q@| jj| j|f|}| j|||d
S )z(Run text through and get agent response.c                 S  s   i | ]}|j |qS r6   r   r   r6   r6   r9   r  M  s      z'AgentExecutor._call.<locals>.<dictcomp>c                 S  s   g | ]
}|j qS r6   r   r   r6   r6   r9   r   P  s     z'AgentExecutor._call.<locals>.<listcomp>r#  ZredZexcluded_colorsr           r   r+  N)r\   r(   timer!  r4  rh   r   r(  extendr   _get_tool_returnr  rX   rN   r8   r   r   r0  r1  rA   r  r   
start_timenext_step_outputZnext_step_actionZtool_returnr5   r6   r6   r9   _callF  sT     
  

   zAgentExecutor._callc                   s  dd | j D }tdd | j D dgd}g }d}d}t }z4t| j4 I d	H  | ||r(| j|||||d
I d	H }	t|	tr| j	|	||d
I d	H W  5 Q I d	H R  W S |
|	 t|	dkr|	d }
| |
}|d	k	r| j	|||d
I d	H W  5 Q I d	H R  W S |d7 }t | }qX| jj| j|f|}| j	|||d
I d	H W  5 Q I d	H R  W S Q I d	H R X W nF ttjfk
r   | jj| j|f|}| j	|||d
I d	H  Y S X d	S )z.Async run text through and get agent response.c                 S  s   i | ]}|j |qS r6   r   r   r6   r6   r9   r  |  s      z(AgentExecutor._acall.<locals>.<dictcomp>c                 S  s   g | ]
}|j qS r6   r   r   r6   r6   r9   r     s     z(AgentExecutor._acall.<locals>.<listcomp>r#  rS  r   rT  NrU  r+  )r\   r(   rV  r.   r  r!  rN  rh   r   r)  rW  r   rX  r  rX   rN   TimeoutErrorrQ  rY  r6   r6   r9   _acallu  sx     
 


      0   zAgentExecutor._acallzTuple[AgentAction, str]zOptional[AgentFinish])r[  r2   c                 C  s`   |\}}dd | j D }d}t| jjdkr8| jjd }|j|kr\||j jr\t||idS dS )z&Check if the tool is a returning tool.c                 S  s   i | ]}|j |qS r6   r   r   r6   r6   r9   r    s      z2AgentExecutor._get_tool_return.<locals>.<dictcomp>r5   r   rR   N)r\   r   r  r:   r   rJ  r   )r8   r[  rH  r   r0  Zreturn_value_keyr6   r6   r9   rX    s    
zAgentExecutor._get_tool_returnr   c                 C  sB   t | jtr&| jdkr&|| j d  S t| jr:| |S |S d S )Nr   )rh   r  r  r@  )r8   rA   r6   r6   r9   r<    s    


z)AgentExecutor._prepare_intermediate_stepszUnion[Dict[str, Any], Any]zOptional[RunnableConfig]zIterator[AddableDict])inputr   rC   r2   c                 k  sZ   t |}t| ||df|d|d|d|ddd|}|D ]
}|V  qJdS )	a  Enables streaming over steps taken to reach final output.

        Args:
            input: Input to the agent.
            config: Config to use.
            kwargs: Additional arguments.

        Yields:
            AddableDict: Addable dictionary.
        rB   r  metadatarun_namerun_idTr  r`  ra  rb  Zyield_actionsNr%   r)   r  r8   r_  r   rC   iteratorstepr6   r6   r9   r     s     	zAgentExecutor.streamzAsyncIterator[AddableDict]c                 K sd   t |}t| ||df|d|d|d|ddd|}|2 z3 dH W }|V  qJ6 dS )	a	  Async enables streaming over steps taken to reach final output.

        Args:
            input: Input to the agent.
            config: Config to use.
            kwargs: Additional arguments.

        Yields:
            AddableDict: Addable dictionary.
        rB   r  r`  ra  rb  Trc  Nrd  re  r6   r6   r9   r     s     	zAgentExecutor.astream)N)N)N)N)N)N)N)N)N)N)N)N)N)N)(r   r   r   r   r   r  r  r  rN   r  r  r   r	  r"   r  r  r   r  r   r  r  rK   r  r  r!  r(  r)  r/  r4  r2  rC  rN  rM  rO  r\  r^  rX  r<  r   r   r6   r6   r6   r9   r     sx   


 
 
    R -  Z , 2 > " r   )[r   
__future__r   rQ  r   loggingrV  abcr   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   r   r   Zlangchain_core._apir   Zlangchain_core.agentsr   r   r   Zlangchain_core.callbacksr   r   r   r   r   r   Zlangchain_core.exceptionsr   Zlangchain_core.language_modelsr   Zlangchain_core.messagesr   Zlangchain_core.output_parsersr   Zlangchain_core.promptsr   Zlangchain_core.prompts.few_shotr   Zlangchain_core.prompts.promptr    Zlangchain_core.pydantic_v1r!   r"   Zlangchain_core.runnablesr#   r$   r%   Zlangchain_core.runnables.utilsr&   Zlangchain_core.toolsr'   Zlangchain_core.utils.inputr(   Zlangchain.agents.agent_iteratorr)   Zlangchain.agents.agent_typesr*   Zlangchain.agents.toolsr+   Zlangchain.chains.baser,   Zlangchain.chains.llmr-   Zlangchain.utilities.asyncior.   	getLoggerr   r   r/   r   r   r   r   r   r   r   r   r*  r  r   r6   r6   r6   r9   <module>   sv   4 
 + 
ltS  &