HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/.local/lib/python3.10/site-packages/langchain/agents/__pycache__/agent.cpython-310.pyc
o

���g��@s�dZddlmZddlZddlZddlZddlZddlmZddl	m
Z
ddlmZm
Z
mZmZmZmZmZmZmZmZmZddlZddlmZddlmZmZmZdd	lmZm Z m!Z!m"Z"m#Z#m$Z$dd
l%m&Z&ddl'm(Z(ddl)m*Z*dd
l+m,Z,ddl-m.Z.ddl/m0Z0ddl1m2Z2ddl3m4Z4m5Z5m6Z6ddl7m8Z8ddl9m:Z:ddl;m<Z<ddl=m>Z>m?Z?m@Z@ddlAmBZBddlCmDZDddlEmFZFddlGmHZHddlImJZJddlKmLZLddlMmNZNddlOmPZPe�QeR�ZSGdd�de>�ZTGd d!�d!e>�ZUGd"d#�d#e,eeef�ZVGd$d%�d%e,eeeef�ZWGd&d'�d'eT�ZXGd(d)�d)eU�ZYed*eDd+d,�Gd-d.�d.eT��ZZed*eDd+d,�Gd/d0�d0eT��Z[Gd1d2�d2e:�Z\eeeeefZ]eeXeYfZ^Gd3d4�d4eL�Z_dS)5zEChain 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)�Runnable�RunnableConfig�
ensure_config)�AddableDict)�BaseTool)�get_color_mapping)�	BaseModel�
ConfigDict�model_validator)�Self)�AGENT_DEPRECATION_WARNING)�AgentExecutorIterator)�	AgentType)�InvalidTool)�Chain)�LLMChain)�asyncio_timeoutcs�eZdZdZed0dd��Zd1dd�Ze		d2d3dd��Ze		d2d3dd��Z	eed0dd���Z
d4dd�Ze		d2d5d"d#��Z
ed6d$d%��Zd7�fd'd(�Zd8d,d-�Zd9d.d/�Z�ZS):�BaseSingleActionAgentzBase Single Action Agent class.�return�	List[str]cC�dgS��Return values of the agent.�output���selfr9r9�I/home/arjun/.local/lib/python3.10/site-packages/langchain/agents/agent.py�
return_values@�z#BaseSingleActionAgent.return_values�Optional[List[str]]cCsdS�Nr9r:r9r9r<�get_allowed_toolsEsz'BaseSingleActionAgent.get_allowed_toolsN�intermediate_steps�List[Tuple[AgentAction, str]]�	callbacksr�kwargsr�Union[AgentAction, AgentFinish]cK�dS)�0Given 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.
        Nr9�r;rBrDrEr9r9r<�planH�zBaseSingleActionAgent.planc���dS)�6Async 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.
        Nr9rIr9r9r<�aplan[�zBaseSingleActionAgent.aplancCrG��7Return the input keys.

        :meta private:
        Nr9r:r9r9r<�
input_keysnrKz BaseSingleActionAgent.input_keys�early_stopping_method�strrcK�&|dkrtddid�Std|�d���)��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.
        �forcer8�3Agent stopped due to iteration limit or time limit.��'Got unsupported early_stopping_method `�`�r�
ValueError�r;rSrBrEr9r9r<�return_stopped_responsevs�
�z-BaseSingleActionAgent.return_stopped_response�llmr�tools�Sequence[BaseTool]�callback_manager�Optional[BaseCallbackManager]cK�t�)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.
        ��NotImplementedError)�clsr`rarcrEr9r9r<�from_llm_and_tools�sz(BaseSingleActionAgent.from_llm_and_toolscCre�z#Return Identifier of an agent type.rfr:r9r9r<�_agent_type��z!BaseSingleActionAgent._agent_typercs\t���}z|j}Wntyd}Ynwt|t�r$t|j�|d<|S|dur,||d<|S)z{Return dictionary representation of agent.

        Returns:
            Dict: Dictionary representation of agent.
        N�_type)�super�
model_dumprkrg�
isinstancer-rT�value)r;rE�_dictrm��	__class__r9r<�dict�s

�
�zBaseSingleActionAgent.dict�	file_path�Union[Path, str]�NonecCs�t|t�r
t|�}n|}|j}|jddd�|��}d|vr&td|�d���|jdkrKt|d��}t	j
||dd	�Wd
�d
S1sDwYd
S|j�d�rqt|d��}tj
||dd
�Wd
�d
S1sjwYd
St
|�d���)z�Save 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_okrm�Agent z does not support saving�.json�w���indentN�z.yamlz.ymlF��default_flow_style� must be json or yaml)rprTr�parent�mkdirrurg�suffix�open�json�dump�endswith�yamlr])r;rv�	save_path�directory_path�
agent_dict�fr9r9r<�save�s"


"�"�zBaseSingleActionAgent.savecC�iS��#Return logging kwargs for tool run.r9r:r9r9r<�tool_run_logging_kwargs�sz-BaseSingleActionAgent.tool_run_logging_kwargs�r3r4�r3r?r@�rBrCrDrrErr3rF�rSrTrBrCrErr3r)
r`rrarbrcrdrErr3r2�r3rT�rErr3r�rvrwr3rx�r3r)�__name__�
__module__�__qualname__�__doc__�propertyr=rArrJrNrRr_�classmethodrirkrur�r��
__classcell__r9r9rsr<r2=s.
��
�
#r2cs�eZdZdZed(dd��Zd)dd�Ze		d*d+dd��Ze		d*d+dd��Z	eed(dd���Z
d,dd�Zed-dd��Zd.�fdd �Z
d/d$d%�Zd0d&d'�Z�ZS)1�BaseMultiActionAgentzBase Multi Action Agent class.r3r4cCr5r6r9r:r9r9r<r=�r>z"BaseMultiActionAgent.return_valuesr?cCrG)z]Get allowed tools.

        Returns:
            Optional[List[str]]: Allowed tools.
        Nr9r:r9r9r<rA�sz&BaseMultiActionAgent.get_allowed_toolsNrBrCrDrrEr�%Union[List[AgentAction], AgentFinish]cKrG)a5Given 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.
        Nr9rIr9r9r<rJ�rKzBaseMultiActionAgent.planc�rL)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.
        Nr9rIr9r9r<rN
rOzBaseMultiActionAgent.aplancCrGrPr9r:r9r9r<rRrKzBaseMultiActionAgent.input_keysrSrTrcKrU)rVrWr8z$Agent stopped due to max iterations.rYrZr[r\r^r9r9r<r_%s

�z,BaseMultiActionAgent.return_stopped_responsecCrerjrfr:r9r9r<rkArlz BaseMultiActionAgent._agent_typercs4t���}z
t|j�|d<W|StyY|Sw)�*Return dictionary representation of agent.rm)rnrorTrkrg�r;rErrrsr9r<ruFs
��zBaseMultiActionAgent.dictrvrwrxcCs�t|t�r
t|�}n|}|��}d|vrtd|�d���|j}|jddd�|jdkrKt|d��}t	j
||dd	�Wd
�d
S1sDwYd
S|j�d�rqt|d��}tj
||dd
�Wd
�d
S1sjwYd
St
|�d���)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")
        rmr|z does not support saving.Tryr}r~rr�Nr�Fr�r�)rprTrrurgr�r�r�r�r�r�r�r�r])r;rvr�r�r�r�r9r9r<r�Os"


"�"�zBaseMultiActionAgent.savecCr�r�r9r:r9r9r<r�vrlz,BaseMultiActionAgent.tool_run_logging_kwargsr�r�r@�rBrCrDrrErr3r�r�r�r�r�r�)r�r�r�r�r�r=rArrJrNrRr_rkrur�r�r�r9r9rsr<r��s(
��

	'r�c@�eZdZdZed	dd��ZdS)
�AgentOutputParserz=Base class for parsing agent output into agent action/finish.�textrTr3rFcCrG)z$Parse text into agent action/finish.Nr9�r;r�r9r9r<�parserKzAgentOutputParser.parseN)r�rTr3rF�r�r�r�r�rr�r9r9r9r<r�|sr�c@r�)
�MultiActionAgentOutputParserz�Base class for parsing agent output into agent actions/finish.

    This is used for agents that can return multiple actions.
    r�rTr3r�cCrG)z�Parse text into agent actions/finish.

        Args:
            text: Text to parse.

        Returns:
            Union[List[AgentAction], AgentFinish]:
                List of agent actions or agent finish.
        Nr9r�r9r9r<r��rKz"MultiActionAgentOutputParser.parseN)r�rTr3r�r�r9r9r9r<r��sr�c@�eZdZUdZded<	gZded<gZded<dZded	<	edd
�Z	e
ddd
��Ze
ddd��Z	dddd�Z
	dddd�ZdS)�
RunnableAgent�Agent powered by Runnables.z/Runnable[dict, Union[AgentAction, AgentFinish]]�runnabler4�input_keys_arg�return_keys_argT�bool�stream_runnable��arbitrary_types_allowedr3cC�|jS�r7�r�r:r9r9r<r=�r>zRunnableAgent.return_valuescCr�)zReturn the input keys.�r�r:r9r9r<rR�r>zRunnableAgent.input_keysNrBrCrDrrErrFcK�fi|�d|i�}d}|jr'|jj|d|id�D]
}|dur |}q||7}q|S|jj|d|id�}|S�aPBased 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.
        rBNrD��config�r�r��stream�invoke�r;rBrDrE�inputs�final_output�chunkr9r9r<rJ�s
�zRunnableAgent.planc��x�i|�d|i�}d}|jr-|jj|d|id�2z3dHW}|dur%|}q||7}q6|S|jj|d|id�IdH}|S�aRAsync 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.
        rBNrDr��r�r��astream�ainvoker�r9r9r<rN�s ��
���zRunnableAgent.aplanr�r@r��r�r�r�r��__annotations__r�r�r�r(�model_configr�r=rRrJrNr9r9r9r<r��s&
��'�r�c@r�)�RunnableMultiActionAgentr�z5Runnable[dict, Union[List[AgentAction], AgentFinish]]r�r4r�r�Tr�r�r�r3cCr�r�r�r:r9r9r<r=r>z&RunnableMultiActionAgent.return_valuescCr�)�QReturn the input keys.

        Returns:
            List of input keys.
        r�r:r9r9r<rRsz#RunnableMultiActionAgent.input_keysNrBrCrDrrErr�cKr�r�r�r�r9r9r<rJ(s
�zRunnableMultiActionAgent.planc�r�r�r�r�r9r9r<rNOs ��
���zRunnableMultiActionAgent.aplanr�r@r�r�r9r9r9r<r�s&
��*�r�z0.1.0z1.0)�message�removalcsveZdZUdZded<	ded<	ded<	edd	d
��Zd�fdd�Z	dddd�Z	dddd�Z	d dd�Z
�ZS)!�LLMSingleActionAgentz$Base class for single action agents.r0�	llm_chainr��
output_parserr4�stopr3cC�tt|jj�dh�S)r�rB��list�setr�rRr:r9r9r<rR�szLLMSingleActionAgent.input_keysrErrc�t���}|d=|S�r�r��rnrur�rsr9r<ru��
zLLMSingleActionAgent.dictNrBrCrDrrFcKs(|jjd||j|d�|��}|j�|�S)a4Given 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.
        �rBr�rDNr9)r��runr�r�r��r;rBrDrEr8r9r9r<rJ�s��zLLMSingleActionAgent.planc�s0�|jjd||j|d�|��IdH}|j�|�S)rMr�Nr9)r��arunr�r�r�r�r9r9r<rN�s���zLLMSingleActionAgent.aplancCs&dt|j�dkrdd�S|jdd�S)r�rYr��
llm_prefix�observation_prefix)�lenr�r:r9r9r<r��s
��z,LLMSingleActionAgent.tool_run_logging_kwargsr�r�r@r�r�)r�r�r�r�r�r�rRrurJrNr�r�r9r9rsr<r�{s 
	��r�csFeZdZUdZded<	ded<	dZded<	dK�fd
d�ZdLdd�ZedMdd��Z	dNdd�Z
edMdd��ZdOdd�Z	dPdQd"d#�Z
	dPdQd$d%�ZdRd'd(�ZedMd)d*��Zed+d,�dSd.d/��ZeedTd0d1���ZeedTd2d3���ZeedUd7d8���ZedVd:d;��ZeedWd<d=���Ze		dXdYdCdD��ZdZdGdH�Zd[dIdJ�Z�ZS)\�Agentz�Agent 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.
    r0r�r�r�Nr?�
allowed_toolsrErr3rcr�r�r�r�rsr9r<ru�r�z
Agent.dictcCr�)zGet allowed tools.)r�r:r9r9r<rA�szAgent.get_allowed_toolsr4cCr5r6r9r:r9r9r<r=�r>zAgent.return_valuesr�rTcC�td��)zsFix the text.

        Args:
            text: Text to fix.

        Returns:
            str: Fixed text.
        z(fix_text not implemented for this agent.�r]r�r9r9r<�	_fix_text�s	zAgent._fix_textcCs d|j����d|j����gS)N�
z
	)r��rstripr:r9r9r<�_stops�zAgent._stoprBrC�Union[str, List[BaseMessage]]cCs<d}|D]\}}||j7}|d|j�|�d|j��7}q|S)zJConstruct the scratchpad that lets the agent continue its thought process.rYr�)�logr�r�)r;rB�thoughts�action�observationr9r9r<�_construct_scratchpads

zAgent._construct_scratchpadrDrrFcKs4|j|fi|��}|jjdd|i|��}|j�|�S)rHrDNr9)�get_full_inputsr��predictr�r�)r;rBrDrE�full_inputs�full_outputr9r9r<rJsz
Agent.planc�sF�|j|fi|��}|jjdd|i|��IdH}|j�|�IdH}|S)rMrDNr9)r�r��apredictr��aparse)r;rBrDrEr�r��agent_outputr9r9r<rN's
�zAgent.aplan�Dict[str, Any]cKs&|�|�}||jd�}i|�|�}|S)a1Create 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�)r;rBrEr��
new_inputsr�r9r9r<r�=s

zAgent.get_full_inputscCr�)rQrr�r:r9r9r<rROszAgent.input_keys�after��moder*cCsv|jj}d|jvr9t�d�|j�d�t|t�r"|jd7_|St|t	�r0|j
d7_
|Stdt|�����|S)aFValidate 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.
        rzl`agent_scratchpad` should be a variable in prompt.input_variables. Did not find it, so adding it at the end.z
{agent_scratchpad}zGot unexpected prompt type )
r��prompt�input_variables�logger�warning�appendrpr �templaterr�r]�type)r;rr9r9r<�validate_promptWs
�

��zAgent.validate_promptcCrG)z&Prefix to append the observation with.Nr9r:r9r9r<r�trKzAgent.observation_prefixcCrG)z#Prefix to append the LLM call with.Nr9r:r9r9r<r�yrKzAgent.llm_prefixrarbrcCrG)z�Create a prompt for this class.

        Args:
            tools: Tools to use.

        Returns:
            BasePromptTemplate: Prompt template.
        Nr9�rhrar9r9r<�
create_prompt~rKzAgent.create_promptrxcCrG)zgValidate that appropriate tools are passed in.

        Args:
            tools: Tools to use.
        Nr9rr9r9r<�_validate_tools�szAgent._validate_toolscKrG)z)Get default output parser for this class.Nr9)rhrEr9r9r<�_get_default_output_parser�rKz Agent._get_default_output_parserr`rrcrd�Optional[AgentOutputParser]c	KsN|�|�t||�|�|d�}dd�|D�}|p|��}|d|||d�|��S)aOConstruct 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`rrccS�g|]}|j�qSr9��name��.0�toolr9r9r<�
<listcomp>��z,Agent.from_llm_and_tools.<locals>.<listcomp>)r�r�r�Nr9)rr0rr)	rhr`rarcr�rEr��
tool_names�_output_parserr9r9r<ri�s
���zAgent.from_llm_and_toolsrSrcKs�|dkrtddid�S|dkrXd}|D]\}}||j7}|d|j�|�d|j��7}q|d7}||jd�}i|�|�}|jjdi|��}	|j�|	�}
t	|
t�rQ|
Std|	i|	�St
d	|����)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'].
        rWr8rXrY�generater�zB

I now need to return a final answer based on the previous steps:rzBearly_stopping_method should be one of `force` or `generate`, got Nr9)rr�r�r�r�r�r�r�r�rpr])r;rSrBrEr�r�r�rr�r��
parsed_outputr9r9r<r_�s4�
��
��zAgent.return_stopped_responsecCs|j|jd�S)r�r�r�r:r9r9r<r��s�zAgent.tool_run_logging_kwargsr�r�r�)r�rTr3rT)rBrCr3r�r@r�)rBrCrErr3r�r3r*r�)rarbr3r)rarbr3rx)rErr3r�)NN)r`rrarbrcrdr�rrErr3r�r�r�)r�r�r�r�r�r�rurAr�r=r�r�r�rJrNr�rRr)rrr�r�r�rrrrir_r�r�r9r9rsr<r��sZ




��

	�
#7r�c@sJeZdZUdZdZded<	dZded<		dddd
�Z	dddd�ZdS)�
ExceptionToolz!Tool that just returns the query.�
_ExceptionrTrzException tool�descriptionN�query�run_manager�#Optional[CallbackManagerForToolRun]r3cCs|Sr@r9�r;r$r%r9r9r<�_runszExceptionTool._run�(Optional[AsyncCallbackManagerForToolRun]c�s�|Sr@r9r'r9r9r<�_aruns�zExceptionTool._arunr@)r$rTr%r&r3rT)r$rTr%r)r3rT)	r�r�r�r�rr�r#r(r*r9r9r9r<r!�s
�
�r!c@s�eZdZUdZded<	ded<	dZded<	d	Zd
ed<	dZd
ed<	dZded<	dZ	ded<	dZ
ded<	e	d�d�dd��Ze
dd�d�d!d"��Ze
d#d�ed�d&d'���Zed�d)d*��Zd�d.d/�Zd�d0d1�Z	d�ddd2�d�d7d8�Zed�d:d;��Zed�d<d=��Zd�d@dA�Zd�dFdG�Z	d�d�dOdP�Z	d�d�dRdS�Zd�dVdW�Z	d�d�d]d^�Z	d�d�d`da�Z	d�d�dedf�Z	d�d�dgdh�Z	d�d�djdk�Z 	d�d�dldm�Z!	d�d�dndo�Z"	d�d�dpdq�Z#d�dudv�Z$d�dwdx�Z%	d�d�d~d�Z&	d�d�d�d��Z'dS)��
AgentExecutorzAgent that is using tools.�<Union[BaseSingleActionAgent, BaseMultiActionAgent, Runnable]�agentrbraFr��return_intermediate_steps�z
Optional[int]�max_iterationsNzOptional[float]�max_execution_timerWrTrSz8Union[bool, str, Callable[[OutputParserException], str]]�handle_parsing_errors���zTUnion[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]]�trim_intermediate_stepsrDrrErr3cKs|d|||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-rarDNr9r9)rhr-rarDrEr9r9r<�from_agent_and_toolsGs��z"AgentExecutor.from_agent_and_toolsrrr*cCsZ|j}|j}|��}|dur+t|�tdd�|D��kr+td|�ddd�|D��d���|S)aValidate 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.
        NcSrr9rrr9r9r<rrrz0AgentExecutor.validate_tools.<locals>.<listcomp>zAllowed tools (z!) different than provided tools (cSrr9rrr9r9r<rur�))r-rarAr�r])r;r-rar�r9r9r<�validate_toolsas
��zAgentExecutor.validate_tools�before�valuesrc
Cs�|�d�}|rJt|t�rJz|j}Wnty%}zd}WYd}~nd}~ww|ttttfk}|�	dd�}|rBt
||d�|d<|St||d�|d<|S)z�Convert runnable to agent if passed in.

        Args:
            values: Values to validate.

        Returns:
            Dict: Validated values.
        r-FNr�T)r�r�)�getrpr!�
OutputType�	Exceptionrr
rr�popr�r�)rhr9r-�output_type�_�multi_actionr�r9r9r<�validate_runnable_agentys&

��
��
�z%AgentExecutor.validate_runnable_agent�2Union[BaseSingleActionAgent, BaseMultiActionAgent]cCst|jt�rtt|j�S|jS)aCType cast self.agent.

        If the `agent` attribute is a Runnable, it will be converted 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.
        )rpr-r!r�RunnableAgentTyper:r9r9r<�
_action_agent�s
zAgentExecutor._action_agentrvrwrxcCr�)z�Raise 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(...)`r��r;rvr9r9r<r��s	�zAgentExecutor.savecCs|j�|�S)zZSave the underlying agent.

        Args:
            file_path: Path to save to.
        )rDr�rEr9r9r<�
save_agent�szAgentExecutor.save_agent)�include_run_info�async_r�rGrHr,cCst||||j|d�S)agEnables 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.
        )�tagsrG)r,rI)r;r�rDrGrHr9r9r<�iter�s�zAgentExecutor.iterr4cCs|jjS)rQ)rDrRr:r9r9r<rR�szAgentExecutor.input_keyscCs|jr
|jjdgS|jjS)z@Return the singular output key.

        :meta private:
        rB)r.rDr=r:r9r9r<�output_keys�szAgentExecutor.output_keysrr%cCsdd�|jD�|S)z�Lookup tool by name.

        Args:
            name: Name of tool.

        Returns:
            BaseTool: Tool object.
        cS�i|]}|j|�qSr9rrr9r9r<�
<dictcomp>��z-AgentExecutor.lookup_tool.<locals>.<dictcomp>)ra)r;rr9r9r<�lookup_tool�s	zAgentExecutor.lookup_tool�
iterations�int�time_elapsed�floatcCs4|jdur||jkrdS|jdur||jkrdSdS)NFT)r0r1)r;rPrRr9r9r<�_should_continue�s

zAgentExecutor._should_continuer8rrBr�r%�$Optional[CallbackManagerForChainRun]rcCs.|r|j|d|jd�|j}|jr||d<|S�N�green)�color�verboserB��on_agent_finishrYr=r.�r;r8rBr%r�r9r9r<�_returnszAgentExecutor._return�)Optional[AsyncCallbackManagerForChainRun]c�s6�|r|j|d|jd�IdH|j}|jr||d<|SrVrZr\r9r9r<�_areturns��zAgentExecutor._areturn�NextStepOutput�1Union[AgentFinish, List[Tuple[AgentAction, str]]]cCs4t|dt�rt|�dksJ�|dSdd�|D�S)Nr3�cSs"g|]
}t|t�r|j|jf�qSr9)rprr�r��r�ar9r9r<r%s

�
�z4AgentExecutor._consume_next_step.<locals>.<listcomp>)rprr�)r;r9r9r9r<�_consume_next_steps�z AgentExecutor._consume_next_step�name_to_tool_map�Dict[str, BaseTool]�
color_mapping�Dict[str, str]rCc
Cs"|�dd�|�|||||�D��S)NcSsg|]}|�qSr9r9rcr9r9r<r2s��z1AgentExecutor._take_next_step.<locals>.<listcomp>)re�_iter_next_step�r;rfrhr�rBr%r9r9r<�_take_next_step)s���zAgentExecutor._take_next_step�4Iterator[Union[AgentFinish, AgentAction, AgentStep]]c
cs��z|�|�}|jj|fd|r|��ndi|��}Wn�ty�}z�t|jt�r-|j}nd}|r:tdt	|�����t	|�}	t|jt�rU|j
rRt	|j�}
t	|j�}	nd}
nt|jt	�r_|j}
nt
|j�rj|�|�}
ntd��td|
|	�}|r}|j|dd	�|j��}t�j|jf|jd|r�|��ndd
�|��}
t||
d�VWYd}~dSd}~wwt|t�r�|VdSt|t�r�|g}n|}|D]}
|
Vq�|D]}
|�|||
|�Vq�dS)��Take a single step in the thought-action-observation loop.

        Override this to take control of how the agent makes and acts on choices.
        rDNF��An 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"rW�rX�rYrXrD�r�r�)�_prepare_intermediate_stepsrDrJ�	get_childrrpr2r�r]rT�send_to_llmr��
llm_output�callabler�on_agent_actionr�r!r��
tool_inputrYrr�_perform_agent_action)r;rfrhr�rBr%r8�e�raise_errorr�r��tool_run_kwargs�actions�agent_actionr9r9r<rj>sz�
��
�
��


�����
(
��zAgentExecutor._iter_next_stepr�rrc
Cs�|r	|j|dd�|j|vr<||j}|j}||j}|j��}|r&d|d<|j|jf|j||r4|��ndd�|��}	n"|j��}t	�j|jt
|���d�f|jd|rW|��ndd�|��}	t||	d�S)NrWrrrYr�rs��requested_tool_name�available_tool_namesrt)
rzr�
return_directrDr�r�r{rYrvr.r��keysr�
r;rfrhr�r%rr�rXrr�r9r9r<r|�s>



���

����
z#AgentExecutor._perform_agent_actionc
�s*�|�dd�|�|||||�2�IdH�S)Nc�s�g|z3dHW}|�q6Sr@r9rcr9r9r<r�s
���z2AgentExecutor._atake_next_step.<locals>.<listcomp>)re�_aiter_next_steprkr9r9r<�_atake_next_step�s��
��zAgentExecutor._atake_next_step�9AsyncIterator[Union[AgentFinish, AgentAction, AgentStep]]c
s��z��|�}�jj|fd�r���ndi|��IdH}Wn�ty�}z~t�jt�r0�j}nd}|r=tdt	|�����t	|�}	t�jt�rX|j
rUt	|j�}
t	|j�}	nd}
nt�jt	�rb�j}
nt
�j�rm��|�}
ntd��td|
|	�}�j��}t�j|jf�jd�r����ndd�|��IdH}
t||
d	�VWYd}~dSd}~wwt|t�r�|VdSt|t�r�|g}n|}|D]}
|
Vq�tj����fd
d�|D��IdH}|D]}|Vq�dS)rnrDNFrorprqr"rsrtcsg|]
}����|���qSr9)�_aperform_agent_action)rr��rhrfr%r;r9r<rs���z2AgentExecutor._aiter_next_step.<locals>.<listcomp>)rurDrNrvrrpr2r�r]rTrwr�rxryrr�r!r�r{rYrr�asyncio�gather)r;rfrhr�rBr%r8r}r~r�r�rr�r��resultr�r9r�r<r��s|�
���
��


�����
&
�
�
�zAgentExecutor._aiter_next_stepc
�s��|r|j||jdd�IdH|j|vrE||j}|j}||j}|j��}|r,d|d<|j|jf|j||r:|��ndd�|��IdH}	n%|j��}t	�j|jt
|���d�f|jd|r`|��ndd�|��IdH}	t||	d�S)NrW)rYrXrYr�rsr�rt)
rzrYrr�rDr�r�r{rvr.r�r�rr�r9r9r<r�sD��



���

����
z$AgentExecutor._aperform_agent_actionc
Csdd�|jD�}tdd�|jD�ddgd�}g}d}d	}t��}|�||�rm|j|||||d
�}	t|	t�r=|j|	||d
�S|�|	�t	|	�dkr]|	d}
|�
|
�}|dur]|j|||d
�S|d7}t��|}|�||�s&|jj|j
|fi|��}|j|||d
�S)
z(Run text through and get agent response.cSrLr9rrr9r9r<rMLrNz'AgentExecutor._call.<locals>.<dictcomp>cSrr9rrr9r9r<rOrz'AgentExecutor._call.<locals>.<listcomp>rW�red��excluded_colorsr��r%rbN)rar&�timerTrlrprr]�extendr��_get_tool_returnrDr_rS�
r;r�r%rfrhrBrPrR�
start_time�next_step_output�next_step_action�tool_returnr8r9r9r<�_callEsJ��
�

����zAgentExecutor._callc
	�s��dd�|jD�}tdd�|jD�dgd�}g}d}d}t��}z�t|j�4Id	H��|�||�r�|j|||||d
�Id	H}	t|	t�rY|j	|	||d
�Id	HWd	�Id	HWS|�
|	�t|	�dkr�|	d}
|�|
�}|d	ur�|j	|||d
�Id	HWd	�Id	HWS|d7}t��|}|�||�s1|j
j|j|fi|��}|j	|||d
�Id	HWd	�Id	HWS1Id	Hs�wYWd	Sttjfy�|j
j|j|fi|��}|j	|||d
�Id	HYSw)z.Async run text through and get agent response.cSrLr9rrr9r9r<rM{rNz(AgentExecutor._acall.<locals>.<dictcomp>cSrr9rrr9r9r<r~rz(AgentExecutor._acall.<locals>.<listcomp>rWr�rr�Nr�rb)rar&r�r1r1rTr�rprr_r�r�r�rDr_rS�TimeoutErrorr�r�r9r9r<�_acalltsr���

��


�����
�4�"����zAgentExecutor._acallr��Tuple[AgentAction, str]�Optional[AgentFinish]cCs`|\}}dd�|jD�}d}t|jj�dkr|jjd}|j|vr.||jjr.t||id�SdS)z&Check if the tool is a returning tool.cSrLr9rrr9r9r<rM�rNz2AgentExecutor._get_tool_return.<locals>.<dictcomp>r8rrYN)rar�rDr=rr�r)r;r�r�r�rf�return_value_keyr9r9r<r��s
�zAgentExecutor._get_tool_returncCs>t|jt�r|jdkr||jd�St|j�r|�|�S|S)Nr)rpr4rQry)r;rBr9r9r<ru�s
�


z)AgentExecutor._prepare_intermediate_steps�input�Union[Dict[str, Any], Any]r��Optional[RunnableConfig]�Iterator[AddableDict]cks\�t|�}t|||�d�f|�d�|�d�|�d�|�d�dd�|��}|D]}|Vq&dS)	aEnables 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.
        rDrI�metadata�run_name�run_idT�rIr�r�r��
yield_actionsN�r#r,r:�r;r�r�rE�iterator�stepr9r9r<r��s$���	��zAgentExecutor.stream�AsyncIterator[AddableDict]cKsf�t|�}t|||�d�f|�d�|�d�|�d�|�d�dd�|��}|2z	3dHW}|Vq&6dS)	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.
        rDrIr�r�r�Tr�Nr�r�r9r9r<r��s$���	��zAgentExecutor.astreamr@)
r-r,rarbrDrrErr3r+r )r9rr3r)r3rBr�)
r�rrDrrGr�rHr�r3r,r�)rrTr3r%)rPrQrRrSr3r�)r8rrBr�r%rUr3r)r8rrBr�r%r^r3r)r9r`r3ra)rfrgrhrir�rirBrCr%rUr3ra)rfrgrhrir�rirBrCr%rUr3rm)
rfrgrhrir�rr%rUr3r)rfrgrhrir�rirBrCr%r^r3ra)rfrgrhrir�rirBrCr%r^r3r�)
rfrgrhrir�rr%r^r3r)r�rir%rUr3r)r�rir%r^r3ri)r�r�r3r�)rBrCr3rC)r�r�r�r�rErr3r�)r�r�r�r�rErr3r�)(r�r�r�r�r�r.r0r1rSr2r4r�r5r)r7rAr�rDr�rFrJrRrKrOrTr]r_rerlrjr|r�r�r�r�r�r�rur�r�r9r9r9r<r+s�


�

��

��


��
��R�-��Z�,�2�
>
�"�r+)`r��
__future__rr�r��loggingr��abcr�pathlibr�typingrrrrr	r
rrr
rrr��langchain_core._apir�langchain_core.agentsrrr�langchain_core.callbacksrrrrrr�langchain_core.exceptionsr�langchain_core.language_modelsr�langchain_core.messagesr�langchain_core.output_parsersr�langchain_core.promptsr�langchain_core.prompts.few_shotr�langchain_core.prompts.promptr �langchain_core.runnablesr!r"r#�langchain_core.runnables.utilsr$�langchain_core.toolsr%�langchain_core.utils.inputr&�pydanticr'r(r)�typing_extensionsr*�langchain._api.deprecationr+�langchain.agents.agent_iteratorr,�langchain.agents.agent_typesr-�langchain.agents.toolsr.�langchain.chains.baser/�langchain.chains.llmr0�langchain.utilities.asyncior1�	getLoggerr�r	r2r�r�r�r�r�r�r�r!r`rCr+r9r9r9r<�<module>s|4 
+
�mu�S�&