a
    ag                     @  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l3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z>m?Z?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddlGmHZH ddlImJZJ ddlKmLZL ddlMmNZN ddlOmPZP eQeRZSG dd de>ZTG d d! d!e>ZUG d"d# d#e,eeef  ZVG d$d% d%e,eee ef  ZWG d&d' d'eTZXG d(d) d)eUZYed*eDd+d,G d-d. d.eTZZed*eDd+d,G d/d0 d0eTZ[G d1d2 d2e:Z\eeeeef  Z]eeXeYf Z^G d3d4 d4eLZ_dS )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_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 selfr9   r9   d/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langchain/agents/agent.pyreturn_values@   s    z#BaseSingleActionAgent.return_valuesOptional[List[str]]c                 C  s   d S Nr9   r:   r9   r9   r<   get_allowed_toolsE   s    z'BaseSingleActionAgent.get_allowed_toolsNList[Tuple[AgentAction, str]]r   r   Union[AgentAction, AgentFinish]intermediate_steps	callbackskwargsr5   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.
        Nr9   r;   rD   rE   rF   r9   r9   r<   planH   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.
        Nr9   rH   r9   r9   r<   aplan[   s    zBaseSingleActionAgent.aplanc                 C  s   dS 7Return the input keys.

        :meta private:
        Nr9   r:   r9   r9   r<   
input_keysn   s    z BaseSingleActionAgent.input_keysstrr   early_stopping_methodrD   rF   r5   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.
        forcer8   3Agent stopped due to iteration limit or time limit. 'Got unsupported early_stopping_method ``Nr   
ValueErrorr;   rQ   rD   rF   r9   r9   r<   return_stopped_responsev   s    
z-BaseSingleActionAgent.return_stopped_responser   Sequence[BaseTool]Optional[BaseCallbackManager])llmtoolscallback_managerrF   r5   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`   rF   r9   r9   r<   from_llm_and_tools   s    z(BaseSingleActionAgent.from_llm_and_toolsc                 C  s   t dS z#Return Identifier of an agent type.Nra   r:   r9   r9   r<   _agent_type   s    z!BaseSingleActionAgent._agent_typer   rF   r5   c                   sZ   t   }z
| j}W n ty*   d}Y n0 t|trFt|j|d< n|durV||d< |S )z{Return dictionary representation of agent.

        Returns:
            Dict: Dictionary representation of agent.
        N_type)super
model_dumprf   rb   
isinstancer-   rO   value)r;   rF   _dictrh   	__class__r9   r<   dict   s    



zBaseSingleActionAgent.dictUnion[Path, str]None	file_pathr5   c                 C  s   t |trt|}n|}|j}|jddd |  }d|vrLtd|  d|jdkrt|d }t	j
||dd	 W d
   q1 s0    Y  nV|jdrt|d }tj
||dd W d
   q1 s0    Y  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_okrh   Agent z does not support saving.jsonw   indentNz.yamlz.ymlFZdefault_flow_style must be json or yaml)rk   rO   r   parentmkdirrp   rb   suffixopenjsondumpendswithyamlrY   )r;   rt   	save_pathdirectory_path
agent_dictfr9   r9   r<   save   s    


00zBaseSingleActionAgent.savec                 C  s   i S #Return logging kwargs for tool run.r9   r:   r9   r9   r<   tool_run_logging_kwargs   s    z-BaseSingleActionAgent.tool_run_logging_kwargs)N)N)N)__name__
__module____qualname____doc__propertyr=   r@   r   rI   rK   rN   r[   classmethodrd   rf   rp   r   r   __classcell__r9   r9   rn   r<   r2   =   s,      #r2   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.r3   r4   c                 C  s   dgS r6   r9   r:   r9   r9   r<   r=      s    z"BaseMultiActionAgent.return_valuesr>   c                 C  s   dS )z]Get allowed tools.

        Returns:
            Optional[List[str]]: Allowed tools.
        Nr9   r:   r9   r9   r<   r@      s    z&BaseMultiActionAgent.get_allowed_toolsNrA   r   r   %Union[List[AgentAction], AgentFinish]rC   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.
        Nr9   rH   r9   r9   r<   rI      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.
        Nr9   rH   r9   r9   r<   rK   
  s    zBaseMultiActionAgent.aplanc                 C  s   dS rL   r9   r:   r9   r9   r<   rN     s    zBaseMultiActionAgent.input_keysrO   r   rP   c                 K  s*   |dkrt ddidS td| ddS )rR   rS   r8   z$Agent stopped due to max iterations.rU   rV   rW   NrX   rZ   r9   r9   r<   r[   %  s
    
z,BaseMultiActionAgent.return_stopped_responsec                 C  s   t dS re   ra   r:   r9   r9   r<   rf   A  s    z BaseMultiActionAgent._agent_typer   rg   c                   s4   t   }zt| j|d< W n ty.   Y n0 |S )*Return dictionary representation of agent.rh   )ri   rj   rO   rf   rb   r;   rF   rm   rn   r9   r<   rp   F  s    
zBaseMultiActionAgent.dictrq   rr   rs   c                 C  s   t |trt|}n|}|  }d|vr8td|  d|j}|jddd |jdkrt|d }t	j
||dd	 W d
   q1 s0    Y  nV|jdrt|d }tj
||dd W d
   q1 s0    Y  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")
        rh   rx   z does not support saving.Tru   ry   rz   r{   r|   Nr~   Fr   r   )rk   rO   r   rp   rb   r   r   r   r   r   r   r   r   rY   )r;   rt   r   r   r   r   r9   r9   r<   r   O  s    


00zBaseMultiActionAgent.savec                 C  s   i S r   r9   r:   r9   r9   r<   r   v  s    z,BaseMultiActionAgent.tool_run_logging_kwargs)N)N)r   r   r   r   r   r=   r@   r   rI   rK   rN   r[   rf   rp   r   r   r   r9   r9   rn   r<   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.rO   rB   textr5   c                 C  s   dS )z$Parse text into agent action/finish.Nr9   r;   r   r9   r9   r<   parse  s    zAgentOutputParser.parseNr   r   r   r   r   r   r9   r9   r9   r<   r   |  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.
    rO   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.
        Nr9   r   r9   r9   r<   r     s    z"MultiActionAgentOutputParser.parseNr   r9   r9   r9   r<   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	< e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]]runnabler3   input_keys_argreturn_keys_argTboolstream_runnableZarbitrary_types_allowedr4   c                 C  s   | j S r7   r   r:   r9   r9   r<   r=     s    zRunnableAgent.return_valuesc                 C  s   | j S )zReturn the input keys.r   r:   r9   r9   r<   rN     s    zRunnableAgent.input_keysNrA   r   r   rB   rC   c                 K  sd   i |d|i}d}| j rL| jj|d|idD ]}|du 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.
        rD   NrE   configr   r   streamZinvoker;   rD   rE   rF   inputsfinal_outputchunkr9   r9   r<   rI     s    zRunnableAgent.planc                   st   i |d|i}d}| j rV| jj|d|id2 z"3 dH W }|du rH|}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.
        rD   NrE   r   r   r   astreamZainvoker   r9   r9   r<   rK     s    zRunnableAgent.aplan)N)Nr   r   r   r   __annotations__r   r   r   r(   Zmodel_configr   r=   rN   rI   rK   r9   r9   r9   r<   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	< e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   r3   r   r   Tr   r   r   r4   c                 C  s   | j S r   r   r:   r9   r9   r<   r=     s    z&RunnableMultiActionAgent.return_valuesc                 C  s   | j S )QReturn the input keys.

        Returns:
            List of input keys.
        r   r:   r9   r9   r<   rN     s    z#RunnableMultiActionAgent.input_keysNrA   r   r   r   rC   c                 K  sd   i |d|i}d}| j rL| jj|d|idD ]}|du r@|}q.||7 }q.n| jj|d|id}|S r   r   r   r9   r9   r<   rI   (  s    zRunnableMultiActionAgent.planc                   st   i |d|i}d}| j rV| jj|d|id2 z"3 dH W }|du rH|}q.||7 }q.6 n| jj|d|idI dH }|S r   r   r   r9   r9   r<   rK   O  s    zRunnableMultiActionAgent.aplan)N)Nr   r9   r9   r9   r<   r     s    
	 * r   z0.1.0z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.r0   	llm_chainr   output_parserr3   stopr4   c                 C  s   t t| jjdh S )r   rD   listsetr   rN   r:   r9   r9   r<   rN     s    zLLMSingleActionAgent.input_keysr   r   rg   c                   s   t   }|d= |S r   r   ri   rp   r   rn   r9   r<   rp     s    
zLLMSingleActionAgent.dictNrA   r   rB   rC   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.
        rD   r   rE   )r   runr   r   r   r;   rD   rE   rF   r8   r9   r9   r<   rI     s    zLLMSingleActionAgent.planc                   s.   | j jf || j|d|I dH }| j|S )rJ   r   N)r   arunr   r   r   r   r9   r9   r<   rK     s    zLLMSingleActionAgent.aplanc                 C  s"   dt | jdkrdn| jd dS )r   rU   r   
llm_prefixobservation_prefix)lenr   r:   r9   r9   r<   r     s    z,LLMSingleActionAgent.tool_run_logging_kwargs)N)N)r   r   r   r   r   r   rN   rp   rI   rK   r   r   r9   r9   rn   r<   r   {  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dKddd	d d!d"d#ZdLd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/d0Zeeddd1d2Zeeddd3d4Zeed5d6d7d8d9Zed5d:d7d;d<Zeed	ddd=d>ZedMd?d5d@dAd	d dBdCdDZddd	dEdFdGdHZd
ddIdJZ  ZS )N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.
    r0   r   r   r   Nr>   allowed_toolsr   r   rg   c                   s   t   }|d= |S r   r   r   rn   r9   r<   rp     s    
z
Agent.dictr4   c                 C  s   | j S )zGet allowed tools.)r   r:   r9   r9   r<   r@     s    zAgent.get_allowed_toolsr3   c                 C  s   dgS r6   r9   r:   r9   r9   r<   r=     s    zAgent.return_valuesrO   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rY   r   r9   r9   r<   	_fix_text  s    	zAgent._fix_textc                 C  s    d| j   d| j   gS )N
z
	)r   rstripr:   r9   r9   r<   _stop  s    zAgent._stoprA   zUnion[str, List[BaseMessage]]rD   r5   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.rU   r   )logr   r   )r;   rD   thoughtsactionobservationr9   r9   r<   _construct_scratchpad  s
    
zAgent._construct_scratchpadr   rB   rC   c                 K  s4   | j |fi |}| jjf d|i|}| j|S )rG   rE   )get_full_inputsr   predictr   r   )r;   rD   rE   rF   full_inputsfull_outputr9   r9   r<   rI     s    z
Agent.planc                   sD   | j |fi |}| jjf d|i|I dH }| j|I dH }|S )rJ   rE   N)r   r   Zapredictr   Zaparse)r;   rD   rE   rF   r   r   Zagent_outputr9   r9   r<   rK   '  s    zAgent.aplanDict[str, Any])rD   rF   r5   c                 K  s&   |  |}|| jd}i ||}|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   )r;   rD   rF   r   
new_inputsr   r9   r9   r<   r   =  s    
zAgent.get_full_inputsc                 C  s   t t| jjdh S )rM   r   r   r:   r9   r9   r<   rN   O  s    zAgent.input_keysaftermoder*   c                 C  sr   | j j}d|jvrntd |jd t|trB| 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   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 )r   promptZinput_variablesloggerwarningappendrk   r    templater   r   rY   type)r;   r   r9   r9   r<   validate_promptW  s    


zAgent.validate_promptc                 C  s   dS )z&Prefix to append the observation with.Nr9   r:   r9   r9   r<   r   t  s    zAgent.observation_prefixc                 C  s   dS )z#Prefix to append the LLM call with.Nr9   r:   r9   r9   r<   r   y  s    zAgent.llm_prefixr\   r   )r_   r5   c                 C  s   dS )zCreate a prompt for this class.

        Args:
            tools: Tools to use.

        Returns:
            BasePromptTemplate: Prompt template.
        Nr9   rc   r_   r9   r9   r<   create_prompt~  s    zAgent.create_promptrr   c                 C  s   dS )zgValidate that appropriate tools are passed in.

        Args:
            tools: Tools to use.
        Nr9   r   r9   r9   r<   _validate_tools  s    zAgent._validate_toolsc                 K  s   dS )z)Get default output parser for this class.Nr9   )rc   rF   r9   r9   r<   _get_default_output_parser  s    z Agent._get_default_output_parserr   r]   zOptional[AgentOutputParser])r^   r_   r`   r   rF   r5   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 r9   name.0toolr9   r9   r<   
<listcomp>      z,Agent.from_llm_and_tools.<locals>.<listcomp>)r   r   r   )r   r0   r   r   )	rc   r^   r_   r`   r   rF   r   Z
tool_namesZ_output_parserr9   r9   r<   rd     s    
zAgent.from_llm_and_toolsr   rP   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}i ||}| jjf i |}	| 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'].
        rS   r8   rT   rU   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   rk   rY   )r;   rQ   rD   rF   r   r   r   r   r   r   Zparsed_outputr9   r9   r<   r[     s4    

zAgent.return_stopped_responsec                 C  s   | j | jdS )r   r   r   r:   r9   r9   r<   r     s    zAgent.tool_run_logging_kwargs)N)N)NN)r   r   r   r   r   r   rp   r@   r   r=   r   r   r   rI   rK   r   rN   r)   r   r   r   r   r   r   r   r   rd   r[   r   r   r9   r9   rn   r<   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.
_ExceptionrO   r   zException tooldescriptionNz#Optional[CallbackManagerForToolRun])queryrun_managerr5   c                 C  s   |S r?   r9   r;   r   r   r9   r9   r<   _run  s    zExceptionTool._runz(Optional[AsyncCallbackManagerForToolRun]c                   s   |S r?   r9   r   r9   r9   r<   _arun  s    zExceptionTool._arun)N)N)	r   r   r   r   r   r   r   r  r  r9   r9   r9   r<   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!Zed"ded#dd$d%d&Zed'dd(d)Zd*d+d,d-d.Zd*d+d,d/d0Zd~ddd1ddddd2d3d4d5Zed6dd7d8Zed6dd9d:Zdd;d<d=d>Zd?d@ddAdBdCZddDdEdFdGdHdIdJZddDdEdKdGdHdLdMZdNdOd$dPdQZddRdSdSdTdFdOdUdVdWZddRdSdSdTdFdXdUdYdZZddRdSd[dFd\d]d^d_ZddRdSdSdTdKdOdUd`daZddRdSdSdTdKdbdUdcddZ ddRdSd[dKd\d]dedfZ!ddSdFdGdgdhdiZ"ddSdKdSdgdjdkZ#dldmdndodpZ$dTdTdqdrdsZ%ddtduddvdwdxdyZ&ddtduddzdwd{d|Z'dS )AgentExecutorzAgent that is using tools.z<Union[BaseSingleActionAgent, BaseMultiActionAgent, Runnable]agentr\   r_   Fr   return_intermediate_steps   zOptional[int]max_iterationsNzOptional[float]max_execution_timerS   rO   rQ   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_   rE   rF   r5   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_   rE   r9   )rc   r  r_   rE   rF   r9   r9   r<   from_agent_and_toolsG  s    z"AgentExecutor.from_agent_and_toolsr   r   r*   r4   c                 C  sZ   | j }| j}| }|durVt|tdd |D krVt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.
        Nc                 S  s   g | ]
}|j qS r9   r   r   r9   r9   r<   r   r  r   z0AgentExecutor.validate_tools.<locals>.<listcomp>zAllowed tools (z!) different than provided tools (c                 S  s   g | ]
}|j qS r9   r   r   r9   r9   r<   r   u  r   ))r  r_   r@   r   rY   )r;   r  r_   r   r9   r9   r<   validate_toolsa  s    zAgentExecutor.validate_toolsbeforer   )valuesr5   c              
   C  s   | d}|rt|trz
|j}W n( tyJ } zd}W Y d}~nd}~0 0 |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   )getrk   r!   Z
OutputType	Exceptionr   r
   r   r   popr   r   )rc   r  r  output_type_Zmulti_actionr   r9   r9   r<   validate_runnable_agenty  s     


z%AgentExecutor.validate_runnable_agentz2Union[BaseSingleActionAgent, BaseMultiActionAgent]c                 C  s"   t | jtrtt| jS | jS dS )aC  Type 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.
        N)rk   r  r!   r   RunnableAgentTyper:   r9   r9   r<   _action_agent  s    
zAgentExecutor._action_agentrq   rr   rs   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   r;   rt   r9   r9   r<   r     s    	zAgentExecutor.savec                 C  s   | j |S )zZSave the underlying agent.

        Args:
            file_path: Path to save to.
        )r  r   r  r9   r9   r<   
save_agent  s    zAgentExecutor.save_agent)include_run_infoasync_r,   )r   rE   r  r  r5   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  )r;   r   rE   r  r  r9   r9   r<   iter  s    zAgentExecutor.iterr3   c                 C  s   | j jS )rM   )r  rN   r:   r9   r9   r<   rN     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:
        rD   N)r  r  r=   r:   r9   r9   r<   output_keys  s    zAgentExecutor.output_keysr%   )r   r5   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 r9   r   r   r9   r9   r<   
<dictcomp>  r   z-AgentExecutor.lookup_tool.<locals>.<dictcomp>)r_   )r;   r   r9   r9   r<   lookup_tool  s    	zAgentExecutor.lookup_toolintfloat)
iterationstime_elapsedr5   c                 C  s4   | j d ur|| j krdS | jd ur0|| jkr0dS dS )NFT)r  r  )r;   r$  r%  r9   r9   r<   _should_continue  s    zAgentExecutor._should_continuer   r   z$Optional[CallbackManagerForChainRun]r   )r8   rD   r   r5   c                 C  s.   |r|j |d| jd |j}| jr*||d< |S Ngreen)colorverboserD   Zon_agent_finishr*  r=   r  r;   r8   rD   r   r   r9   r9   r<   _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,  r9   r9   r<   _areturn  s    zAgentExecutor._areturnNextStepOutputz1Union[AgentFinish, List[Tuple[AgentAction, str]]]c                 C  s8   t |d tr&t|dksJ |d S dd |D S d S )Nr
     c                 S  s"   g | ]}t |tr|j|jfqS r9   )rk   r   r   r   r   ar9   r9   r<   r   %  s   z4AgentExecutor._consume_next_step.<locals>.<listcomp>)rk   r   r   )r;   r  r9   r9   r<   _consume_next_step  s    z AgentExecutor._consume_next_stepzDict[str, BaseTool]zDict[str, str]rA   )name_to_tool_mapcolor_mappingr   rD   r   r5   c              
   C  s"   |  dd | |||||D S )Nc                 S  s   g | ]}|qS r9   r9   r1  r9   r9   r<   r   2  s   z1AgentExecutor._take_next_step.<locals>.<listcomp>)r3  _iter_next_stepr;   r4  r5  r   rD   r   r9   r9   r<   _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yZ } z
t| jtr^| j }nd}|rxt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}~dS d}~0 0 t|trr|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.
        rE   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)  rE   r   r   )_prepare_intermediate_stepsr  rI   	get_childr   rk   r	  r   rY   rO   send_to_llmr   
llm_outputcallabler   on_agent_actionr   r   r   
tool_inputr*  r   r   _perform_agent_action)r;   r4  r5  r   rD   r   r8   eraise_errorr   r   tool_run_kwargsactionsagent_actionr9   r9   r<   r6  >  sr    





zAgentExecutor._iter_next_stepr   r   )r4  r5  rL  r   r5   c           
      C  s   |r|j |dd |j|v 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(  r=  rU   r   r>  Zrequested_tool_nameZavailable_tool_namesr?  )rE  r   return_directr  r   r   rF  r*  rA  r.   r   keysr   
r;   r4  r5  rL  r   r   rN  r)  rJ  r   r9   r9   r<   rG    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?   r9   r1  r9   r9   r<   r     s   z2AgentExecutor._atake_next_step.<locals>.<listcomp>)r3  _aiter_next_stepr7  r9   r9   r<   _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yT }  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}~dS d}~0 0 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 )r9  rE   NFr:  r;  r<  r   r>  r?  c                   s   g | ]}  |qS r9   )_aperform_agent_action)r   rL  r5  r4  r   r;   r9   r<   r     s   z2AgentExecutor._aiter_next_step.<locals>.<listcomp>)r@  r  rK   rA  r   rk   r	  r   rY   rO   rB  r   rC  rD  r   r   r   r   rF  r*  r   r   asynciogather)r;   r4  r5  r   rD   r   r8   rH  rI  r   r   rJ  rK  rL  resultr   r9   rT  r<   rQ    st    







zAgentExecutor._aiter_next_stepc           
        s   |r|j || jddI d H  |j|v 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)  rU   r   r>  rM  r?  )rE  r*  r   rN  r  r   r   rF  rA  r.   r   rO  r   rP  r9   r9   r<   rS    sB    






z$AgentExecutor._aperform_agent_action)r   r   r5   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ur| j|||d
S |d7 }t | }q@| jj| j|fi |}| j|||d
S )z(Run text through and get agent response.c                 S  s   i | ]}|j |qS r9   r   r   r9   r9   r<   r   L  r   z'AgentExecutor._call.<locals>.<dictcomp>c                 S  s   g | ]
}|j qS r9   r   r   r9   r9   r<   r   O  r   z'AgentExecutor._call.<locals>.<listcomp>r(  redZexcluded_colorsr           r   r0  N)r_   r&   timer&  r8  rk   r   r-  extendr   _get_tool_returnr  r[   rQ   r;   r   r   r4  r5  rD   r$  r%  
start_timenext_step_outputZnext_step_actionZtool_returnr8   r9   r9   r<   _callE  sH    


zAgentExecutor._callc              	     s  dd | j D }tdd | j D dgd}g }d}d}t }zJt| j4 I d	H  | ||r,| j|||||d
I d	H }	t|	tr| j	|	||d
I d	H W  d	  I d	H  W S |
|	 t|	dkr|	d }
| |
}|d	ur| j	|||d
I d	H W  d	  I d	H  W S |d7 }t | }qX| jj| j|fi |}| j	|||d
I d	H W  d	  I d	H  W S 1 I d	H s~0    Y  W nH ttjfy   | jj| j|fi |}| j	|||d
I d	H  Y S 0 d	S )z.Async run text through and get agent response.c                 S  s   i | ]}|j |qS r9   r   r   r9   r9   r<   r   {  r   z(AgentExecutor._acall.<locals>.<dictcomp>c                 S  s   g | ]
}|j qS r9   r   r   r9   r9   r<   r   ~  r   z(AgentExecutor._acall.<locals>.<listcomp>r(  rY  r   rZ  Nr[  r0  )r_   r&   r\  r1   r  r&  rR  rk   r   r.  r]  r   r^  r  r[   rQ   TimeoutErrorrU  r_  r9   r9   r<   _acallt  sf    
"


">zAgentExecutor._acallzTuple[AgentAction, str]zOptional[AgentFinish])ra  r5   c                 C  s`   |\}}dd | j D }d}t| jjdkr8| jjd }|j|v 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 r9   r   r   r9   r9   r<   r     r   z2AgentExecutor._get_tool_return.<locals>.<dictcomp>r8   r   rU   N)r_   r   r  r=   r   rN  r   )r;   ra  rL  r   r4  Zreturn_value_keyr9   r9   r<   r^    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   )rk   r  r"  rD  )r;   rD   r9   r9   r<   r@    s    


z)AgentExecutor._prepare_intermediate_stepszUnion[Dict[str, Any], Any]zOptional[RunnableConfig]zIterator[AddableDict])inputr   rF   r5   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.
        rE   r  metadatarun_namerun_idTr  rf  rg  rh  Zyield_actionsNr#   r,   r  r;   re  r   rF   iteratorstepr9   r9   r<   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.
        rE   r  rf  rg  rh  Tri  Nrj  rk  r9   r9   r<   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  rQ   r	  r  r   r  r)   r  r  r   r  r   r  r  rN   r  r!  r&  r-  r.  r3  r8  r6  rG  rR  rQ  rS  rb  rd  r^  r@  r   r   r9   r9   r9   r<   r    sz   


  
    R -  Z , 2 > " r  )`r   
__future__r   rU  r   loggingr\  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.runnablesr!   r"   r#   Zlangchain_core.runnables.utilsr$   Zlangchain_core.toolsr%   Zlangchain_core.utils.inputr&   Zpydanticr'   r(   r)   Ztyping_extensionsr*   Zlangchain._api.deprecationr+   Zlangchain.agents.agent_iteratorr,   Zlangchain.agents.agent_typesr-   Zlangchain.agents.toolsr.   Zlangchain.chains.baser/   Zlangchain.chains.llmr0   Zlangchain.utilities.asyncior1   	getLoggerr   r   r2   r   r   r   r   r   r   r   r   r/  r  r  r9   r9   r9   r<   <module>   sz   4 
 + 
muS  &