o
    .if2                     @  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 ddlZddlmZ ddl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'm(Z( ddl)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZAmBZBmCZCmDZDmEZE ddlFmGZG ddlHmIZI ddlJmKZK eLeMZNG dd de,ZOG dd  d e,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/d0 d0eOZVG d1d2 d2e5ZWeeeeef  ZXG d3d4 d4eGZYd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)
deprecated)AgentActionAgentFinish	AgentStep)OutputParserException)BaseLanguageModel)BaseMessage)BaseOutputParser)BasePromptTemplate)FewShotPromptTemplate)PromptTemplate)	BaseModelroot_validator)RunnableRunnableConfigensure_config)AddableDict)BaseTool)get_color_mapping)AgentExecutorIterator)	AgentType)InvalidTool)BaseCallbackManager)AsyncCallbackManagerForChainRunAsyncCallbackManagerForToolRunCallbackManagerForChainRunCallbackManagerForToolRun	Callbacks)Chain)LLMChain)asyncio_timeoutc                      s   e Zd ZdZed0ddZd1ddZe		d2d3ddZe		d2d3ddZ	eed0ddZ
d4ddZe		d2d5d"d#Zed6d$d%Zd7 fd'd(Zd8d,d-Zd9d.d/Z  ZS ):BaseSingleActionAgentzBase Single Action Agent class.return	List[str]c                 C     dgS Return values of the agent.output selfr5   r5   O/var/www/html/corbot_env/lib/python3.10/site-packages/langchain/agents/agent.pyreturn_values<      z#BaseSingleActionAgent.return_valuesOptional[List[str]]c                 C     d S Nr5   r6   r5   r5   r8   get_allowed_toolsA      z'BaseSingleActionAgent.get_allowed_toolsNintermediate_stepsList[Tuple[AgentAction, str]]	callbacksr*   kwargsr   Union[AgentAction, AgentFinish]c                 K     dS /  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.
        Nr5   r7   r@   rB   rC   r5   r5   r8   planD       zBaseSingleActionAgent.planc                      dS rF   r5   rH   r5   r5   r8   aplanW       zBaseSingleActionAgent.aplanc                 C  rE   7Return the input keys.

        :meta private:
        Nr5   r6   r5   r5   r8   
input_keysj   rJ   z BaseSingleActionAgent.input_keysearly_stopping_methodstrr   c                 K  &   |dkrt ddidS td| d)BReturn response when agent has been stopped due to max iterations.forcer4   3Agent stopped due to iteration limit or time limit. 'Got unsupported early_stopping_method ``r   
ValueErrorr7   rQ   r@   rC   r5   r5   r8   return_stopped_responser   s   
z-BaseSingleActionAgent.return_stopped_responsellmr   toolsSequence[BaseTool]callback_managerOptional[BaseCallbackManager]c                 K     t r=   NotImplementedError)clsr^   r_   ra   rC   r5   r5   r8   from_llm_and_tools   s   z(BaseSingleActionAgent.from_llm_and_toolsc                 C  rc   z Return Identifier of agent type.rd   r6   r5   r5   r8   _agent_type      z!BaseSingleActionAgent._agent_typer   c                   s\   t   }z| j}W n ty   d}Y nw t|tr$t|j|d< |S |dur,||d< |S )*Return dictionary representation of agent.N_type)superdictri   re   
isinstancer#   rR   value)r7   rC   _dictrl   	__class__r5   r8   rn      s   


zBaseSingleActionAgent.dict	file_pathUnion[Path, str]Nonec                 C  s   t |tr
t|}n|}|j}|jddd |  }d|vr&td|  d|jdkrKt|d}t	j
||dd	 W d
   d
S 1 sDw   Y  d
S |jdkrpt|d}tj
||dd W d
   d
S 1 siw   Y  d
S t| d)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_okrl   Agent z does not support saving.jsonw   indentN.yamlFdefault_flow_style must be json or yaml)ro   rR   r   parentmkdirrn   re   suffixopenjsondumpyamlr[   )r7   rt   	save_pathdirectory_path
agent_dictfr5   r5   r8   save   s"   


"
"zBaseSingleActionAgent.savec                 C     i S r=   r5   r6   r5   r5   r8   tool_run_logging_kwargs   r?   z-BaseSingleActionAgent.tool_run_logging_kwargsr/   r0   r/   r;   r=   r@   rA   rB   r*   rC   r   r/   rD   rQ   rR   r@   rA   rC   r   r/   r   )
r^   r   r_   r`   ra   rb   rC   r   r/   r.   r/   rR   rC   r   r/   r   rt   ru   r/   rv   r/   r   )__name__
__module____qualname____doc__propertyr9   r>   r   rI   rL   rP   r]   classmethodrg   ri   rn   r   r   __classcell__r5   r5   rr   r8   r.   9   s.    

	
#r.   c                      s   e Zd ZdZed(ddZd)ddZe		d*d+ddZe		d*d+ddZ	eed(ddZ
d,ddZed-ddZd. fdd Zd/d$d%Zd0d&d'Z  ZS )1BaseMultiActionAgentzBase Multi Action Agent class.r/   r0   c                 C  r1   r2   r5   r6   r5   r5   r8   r9      r:   z"BaseMultiActionAgent.return_valuesr;   c                 C  r<   r=   r5   r6   r5   r5   r8   r>      r?   z&BaseMultiActionAgent.get_allowed_toolsNr@   rA   rB   r*   rC   r   %Union[List[AgentAction], AgentFinish]c                 K  rE   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.
        Nr5   rH   r5   r5   r8   rI      rJ   zBaseMultiActionAgent.planc                   rK   r   r5   rH   r5   r5   r8   rL      rM   zBaseMultiActionAgent.aplanc                 C  rE   rN   r5   r6   r5   r5   r8   rP      rJ   zBaseMultiActionAgent.input_keysrQ   rR   r   c                 K  rS   )rT   rU   r4   z$Agent stopped due to max iterations.rW   rX   rY   rZ   r\   r5   r5   r8   r]      s
   
z,BaseMultiActionAgent.return_stopped_responsec                 C  rc   rh   rd   r6   r5   r5   r8   ri     rj   z BaseMultiActionAgent._agent_typer   c                   s4   t   }z
t| j|d< W |S  ty   Y |S w )rk   rl   )rm   rn   rR   ri   re   r7   rC   rq   rr   r5   r8   rn     s   
zBaseMultiActionAgent.dictrt   ru   rv   c                 C  s   t |tr
t|}n|}|  }d|vrtd|  d|j}|jddd |jdkrKt|d}t	j
||dd	 W d
   d
S 1 sDw   Y  d
S |jdkrpt|d}tj
||dd W d
   d
S 1 siw   Y  d
S t| d)rw   rl   r{   z does not support saving.Trx   r|   r}   r~   r   Nr   Fr   r   )ro   rR   r   rn   re   r   r   r   r   r   r   r   r[   )r7   rt   r   r   r   r   r5   r5   r8   r     s"   


"
"zBaseMultiActionAgent.savec                 C  r   r=   r5   r6   r5   r5   r8   r   ?  r?   z,BaseMultiActionAgent.tool_run_logging_kwargsr   r   r=   r@   rA   rB   r*   rC   r   r/   r   r   r   r   r   r   )r   r   r   r   r   r9   r>   r   rI   rL   rP   r]   ri   rn   r   r   r   r5   r5   rr   r8   r      s(    


	#r   c                   @     e Zd ZdZed	ddZdS )
AgentOutputParserz=Base class for parsing agent output into agent action/finish.textrR   r/   rD   c                 C  rE   )z$Parse text into agent action/finish.Nr5   r7   r   r5   r5   r8   parseF  rJ   zAgentOutputParser.parseN)r   rR   r/   rD   r   r   r   r   r   r   r5   r5   r5   r8   r   C  s    r   c                   @  r   )
MultiActionAgentOutputParserz>Base class for parsing agent output into agent actions/finish.r   rR   r/   r   c                 C  rE   )z%Parse text into agent actions/finish.Nr5   r   r5   r5   r8   r   P  rJ   z"MultiActionAgentOutputParser.parseN)r   rR   r/   r   r   r5   r5   r5   r8   r   K  s    r   c                   @  p   e Zd ZU dZded< 	 g Zded< 	 G dd dZedd	d
ZedddZ		ddddZ
	ddddZdS )RunnableAgentAgent powered by runnables.z/Runnable[dict, Union[AgentAction, AgentFinish]]runnabler0   _input_keysc                   @     e Zd ZdZdZdS )zRunnableAgent.Config'Configuration for this pydantic object.TNr   r   r   r   arbitrary_types_allowedr5   r5   r5   r8   Config]      r   r/   c                 C     g S r3   r5   r6   r5   r5   r8   r9   b  rj   zRunnableAgent.return_valuesc                 C     | j S QReturn the input keys.

        Returns:
            List of input keys.
        r   r6   r5   r5   r8   rP   g     zRunnableAgent.input_keysNr@   rA   rB   r*   rC   r   rD   c                 K  H   i |d|i}d}| j j|d|idD ]}|du r|}q||7 }q|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.
        r@   NrB   configr   streamr7   r@   rB   rC   inputsfinal_outputchunkr5   r5   r8   rI   p  s   
zRunnableAgent.planc                   T   i |d|i}d}| j j|d|id2 z3 dH W }|du r"|}q||7 }q6 |S )aJ  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.
        r@   NrB   r   r   astreamr   r5   r5   r8   rL     s   
zRunnableAgent.aplanr   r=   r   r   r   r   r   __annotations__r   r   r   r9   rP   rI   rL   r5   r5   r5   r8   r   U  s   
 #r   c                   @  r   )RunnableMultiActionAgentr   z5Runnable[dict, Union[List[AgentAction], AgentFinish]]r   r0   r   c                   @  r   )zRunnableMultiActionAgent.Configr   TNr   r5   r5   r5   r8   r     r   r   r/   c                 C  r   r   r5   r6   r5   r5   r8   r9     rj   z&RunnableMultiActionAgent.return_valuesc                 C  r   r   r   r6   r5   r5   r8   rP     r   z#RunnableMultiActionAgent.input_keysNr@   rA   rB   r*   rC   r   r   c                 K  r   r   r   r   r5   r5   r8   rI     s   
zRunnableMultiActionAgent.planc                   r   )aK  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.
        r@   NrB   r   r   r   r5   r5   r8   rL     s   
zRunnableMultiActionAgent.aplanr   r=   r   r   r5   r5   r5   r8   r     s   
 &r   z0.1.0zpUse new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc.z0.2.0)alternativeremovalc                      sv   e Zd ZU dZded< 	 ded< 	 ded< 	 edd	d
Zd fddZ	ddddZ	ddddZ	d ddZ
  ZS )!LLMSingleActionAgentz$Base class for single action agents.r,   	llm_chainr   output_parserr0   stopr/   c                 C     t t| jjdh S )r   r@   listsetr   rP   r6   r5   r5   r8   rP   +  s   zLLMSingleActionAgent.input_keysrC   r   r   c                      t   }|d= |S rk   r   rm   rn   r   rr   r5   r8   rn   4     
zLLMSingleActionAgent.dictNr@   rA   rB   r*   rD   c                 K  s(   | j jd|| 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.
        r@   r   rB   Nr5   )r   runr   r   r   r7   r@   rB   rC   r4   r5   r5   r8   rI   :  s   zLLMSingleActionAgent.planc                   s0   | j jd|| j|d|I dH }| j|S )rG   r   Nr5   )r   arunr   r   r   r   r5   r5   r8   rL   S  s   zLLMSingleActionAgent.aplanc                 C  s&   dt | jdkrddS | jd dS )NrW   r   
llm_prefixobservation_prefix)lenr   r6   r5   r5   r8   r   l  s
   z,LLMSingleActionAgent.tool_run_logging_kwargsr   r   r=   r   r   )r   r   r   r   r   r   rP   rn   rI   rL   r   r   r5   r5   rr   r8   r     s    
 		r   c                      s<  e Zd ZU dZded< ded< dZded< dI fddZdJddZedKddZ	dLddZ
edKddZdMddZ	dNdOd"d#Z	dNdOd$d%ZdPd'd(ZedKd)d*Ze dQd,d-ZeedRd.d/ZeedRd0d1ZeedSd5d6ZedTd8d9ZeedUd:d;Ze		dVdWdAdBZdXdEdFZdYdGdHZ  ZS )ZAgentzAgent that calls the language model and deciding the action.

    This is driven by an 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_toolsrC   r   r/   r   c                   r   r   r   r   rr   r5   r8   rn     r   z
Agent.dictc                 C  r   r=   )r   r6   r5   r5   r8   r>     s   zAgent.get_allowed_toolsr0   c                 C  r1   )Nr4   r5   r6   r5   r5   r8   r9     s   zAgent.return_valuesr   rR   c                 C     t d)zFix the text.z(fix_text not implemented for this agent.r[   r   r5   r5   r8   	_fix_text  s   zAgent._fix_textc                 C  s    d| j   d| j   gS )N
z
	)r   rstripr6   r5   r5   r8   _stop  s   zAgent._stopr@   rA   Union[str, List[BaseMessage]]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.rW   r   )logr   r   )r7   r@   thoughtsactionobservationr5   r5   r8   _construct_scratchpad  s
   
zAgent._construct_scratchpadrB   r*   rD   c                 K  s4   | j |fi |}| jjdd|i|}| j|S rG   rB   Nr5   )get_full_inputsr   predictr   r   )r7   r@   rB   rC   full_inputsfull_outputr5   r5   r8   rI     s   z
Agent.planc                   sF   | j |fi |}| jjdd|i|I dH }| j|I dH }|S r   )r   r   apredictr   aparse)r7   r@   rB   rC   r   r   agent_outputr5   r5   r8   rL     s
   zAgent.aplanDict[str, Any]c                 K  s&   |  |}|| jd}i ||}|S )z@Create the full inputs for the LLMChain from intermediate steps.agent_scratchpadr   )r   r   )r7   r@   rC   r   
new_inputsr   r5   r5   r8   r     s   
zAgent.get_full_inputsc                 C  r   )rO   r   r   r6   r5   r5   r8   rP     s   zAgent.input_keysvaluesc                 C  sx   |d j }d|jvr:td |jd t|tr#| jd7  _|S t|tr1| j	d7  _	|S t
dt| |S )z$Validate that prompt matches format.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 )promptinput_variablesloggerwarningappendro   r   templater   r   r[   type)rf   r   r  r5   r5   r8   validate_prompt  s   



zAgent.validate_promptc                 C  rE   )z&Prefix to append the observation with.Nr5   r6   r5   r5   r8   r     rJ   zAgent.observation_prefixc                 C  rE   )z#Prefix to append the LLM call with.Nr5   r6   r5   r5   r8   r     rJ   zAgent.llm_prefixr_   r`   r   c                 C  rE   )zCreate a prompt for this class.Nr5   rf   r_   r5   r5   r8   create_prompt  rJ   zAgent.create_promptrv   c                 C  rE   )z.Validate that appropriate tools are passed in.Nr5   r	  r5   r5   r8   _validate_tools  rj   zAgent._validate_toolsc                 K  rE   )z)Get default output parser for this class.Nr5   )rf   rC   r5   r5   r8   _get_default_output_parser  rJ   z Agent._get_default_output_parserr^   r   ra   rb   Optional[AgentOutputParser]c           	      K  sN   |  | t|| ||d}dd |D }|p|  }| d|||d|S )z)Construct an agent from an LLM and tools.)r^   r  ra   c                 S     g | ]}|j qS r5   name.0toolr5   r5   r8   
<listcomp>       z,Agent.from_llm_and_tools.<locals>.<listcomp>)r   r   r   Nr5   )r  r,   r
  r  )	rf   r^   r_   ra   r   rC   r   
tool_names_output_parserr5   r5   r8   rg     s   

zAgent.from_llm_and_toolsrQ   r   c                 K  s   |dkrt ddidS |dkrXd}|D ]\}}||j7 }|d| j | d| j 7 }q|d7 }|| jd}i ||}| jjdi |}	| j|	}
t	|
t rQ|
S t d|	i|	S t
d	| )rT   rU   r4   rV   rW   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 Nr5   )r   r   r   r   r   r   r   r   r   ro   r[   )r7   rQ   r@   rC   r   r   r   r   r   r   parsed_outputr5   r5   r8   r]   )  s4   

zAgent.return_stopped_responsec                 C  s   | j | jdS )Nr   r   r6   r5   r5   r8   r   S  s   zAgent.tool_run_logging_kwargsr   r   r   )r   rR   r/   rR   )r@   rA   r/   r   r=   r   )r@   rA   rC   r   r/   r   r   r   r/   r   r   )r_   r`   r/   r   )r_   r`   r/   rv   )rC   r   r/   r   )NN)r^   r   r_   r`   ra   rb   r   r  rC   r   r/   r   r   r   )r   r   r   r   r   r   rn   r>   r   r9   r   r   r   rI   rL   r   rP   r   r  r   r   r   r   r
  r  r  rg   r]   r   r   r5   r5   rr   r8   r   s  sT   
 	



	
*r   c                   @  sJ   e Zd ZU dZdZded< 	 dZded< 	 	ddddZ	ddddZdS )ExceptionToolz!Tool that just returns the query.
_ExceptionrR   r  zException tooldescriptionNqueryrun_manager#Optional[CallbackManagerForToolRun]r/   c                 C  s   |S r=   r5   r7   r  r  r5   r5   r8   _runb  s   zExceptionTool._run(Optional[AsyncCallbackManagerForToolRun]c                   s   |S r=   r5   r!  r5   r5   r8   _aruni  s   zExceptionTool._arunr=   )r  rR   r  r   r/   rR   )r  rR   r  r#  r/   rR   )	r   r   r   r   r  r   r  r"  r$  r5   r5   r5   r8   r  Z  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	dydzddZe d{d d!Ze d{d"d#Zed$d%d{d&d'Zd|d+d,Zd|d-d.Z	dyddd/d}d4d5Zed~d7d8Zed~d9d:Zdd=d>ZddCdDZ	dyddLdMZ	dyddOdPZddSdTZ	dyddZd[Z	dydd]d^Z	dydd_d`Z	dyddbdcZ	dyddddeZ 	dyddfdgZ!ddkdlZ"ddmdnZ#	dyddtduZ$	dyddwdxZ%dS )AgentExecutorzAgent that is using tools.2Union[BaseSingleActionAgent, BaseMultiActionAgent]agentr`   r_   Fboolreturn_intermediate_steps   zOptional[int]max_iterationsNzOptional[float]max_execution_timerU   rR   rQ   z8Union[bool, str, Callable[[OutputParserException], str]]handle_parsing_errorszTUnion[int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]]trim_intermediate_stepsrB   r*   rC   r   r/   c                 K  s   | d|||d|S )zCreate from agent and tools.)r'  r_   rB   Nr5   r5   )rf   r'  r_   rB   rC   r5   r5   r8   from_agent_and_tools  s   	z"AgentExecutor.from_agent_and_toolsr   r   c                 C  s^   |d }|d }|  }|dur-t|tdd |D kr-td| ddd |D  d	|S )
.Validate that tools are compatible with agent.r'  r_   Nc                 S  r  r5   r  r  r5   r5   r8   r    r  z0AgentExecutor.validate_tools.<locals>.<listcomp>zAllowed tools (z!) different than provided tools (c                 S  r  r5   r  r  r5   r5   r8   r    r  ))r>   r   r[   )rf   r   r'  r_   r   r5   r5   r8   validate_tools  s   zAgentExecutor.validate_toolsc                 C  s6   |d }|d }t |tr|D ]	}|jrtdq|S )r1  r'  r_   zKTools that have `return_direct=True` are not allowed in multi-action agents)ro   r   return_directr[   )rf   r   r'  r_   r  r5   r5   r8   validate_return_direct_tool  s   
z)AgentExecutor.validate_return_direct_toolT)prec              
   C  s   |d }t |tr?z|j}W n ty" } zd}W Y d}~nd}~ww |ttt tf k}|r8t|d|d< |S t	|d|d< |S )z'Convert runnable to agent if passed in.r'  FN)r   )
ro   r   
OutputType	Exceptionr   r
   r   r   r   r   )rf   r   r'  output_type_multi_actionr5   r5   r8   validate_runnable_agent  s   

z%AgentExecutor.validate_runnable_agentrt   ru   rv   c                 C  r   )z7Raise error - 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   r7   rt   r5   r5   r8   r     s   zAgentExecutor.savec                 C  s   | j |S )zSave the underlying agent.)r'  r   r=  r5   r5   r8   
save_agent  s   zAgentExecutor.save_agent)include_run_infoasync_r   r?  r@  r"   c                C  s   t | ||| j|dS )z9Enables iteration over steps taken to reach final output.)tagsr?  )r"   rA  )r7   r   rB   r?  r@  r5   r5   r8   iter  s   	zAgentExecutor.iterr0   c                 C  s   | j jS )rO   )r'  rP   r6   r5   r5   r8   rP     s   zAgentExecutor.input_keysc                 C  s   | j r
| jjdg S | jjS )z@Return the singular output key.

        :meta private:
        r@   )r)  r'  r9   r6   r5   r5   r8   output_keys  s   zAgentExecutor.output_keysr  r    c                 C  s   dd | j D | S )zLookup tool by name.c                 S     i | ]}|j |qS r5   r  r  r5   r5   r8   
<dictcomp>      z-AgentExecutor.lookup_tool.<locals>.<dictcomp>)r_   )r7   r  r5   r5   r8   lookup_tool  s   zAgentExecutor.lookup_tool
iterationsinttime_elapsedfloatc                 C  s4   | j d ur|| j krdS | jd ur|| jkrdS dS )NFT)r+  r,  )r7   rH  rJ  r5   r5   r8   _should_continue  s   

zAgentExecutor._should_continuer4   r   r@   r   r  $Optional[CallbackManagerForChainRun]r   c                 C  s.   |r|j |d| jd |j}| jr||d< |S Ngreen)colorverboser@   on_agent_finishrQ  r9   r)  r7   r4   r@   r  r   r5   r5   r8   _return  s   zAgentExecutor._return)Optional[AsyncCallbackManagerForChainRun]c                   s6   |r|j |d| jdI d H  |j}| jr||d< |S rN  rR  rT  r5   r5   r8   _areturn+  s   zAgentExecutor._areturnNextStepOutput1Union[AgentFinish, List[Tuple[AgentAction, str]]]c                 C  s4   t |d trt|dksJ |d S dd |D S )Nr.     c                 S  s"   g | ]}t |tr|j|jfqS r5   )ro   r   r   r   r  ar5   r5   r8   r  A  s
    

z4AgentExecutor._consume_next_step.<locals>.<listcomp>)ro   r   r   )r7   r   r5   r5   r8   _consume_next_step:  s   z AgentExecutor._consume_next_stepname_to_tool_mapDict[str, BaseTool]color_mappingDict[str, str]rA   c              
   C  s"   |  dd | |||||D S )Nc                 S  s   g | ]}|qS r5   r5   r[  r5   r5   r8   r  N  s    z1AgentExecutor._take_next_step.<locals>.<listcomp>)r]  _iter_next_stepr7   r^  r`  r   r@   r  r5   r5   r8   _take_next_stepE  s   zAgentExecutor._take_next_step4Iterator[Union[AgentFinish, AgentAction, AgentStep]]c              
   c  sn   z|  |}| jj|fd|r| ndi|}W n ty } zt| jtr-| j }nd}|r:tdt	| t	|}	t| jtrU|j
rRt	|j}
t	|j}	nd}
nt| jt	r_| j}
nt| jrj| |}
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}~ww t|tr|V  dS t|tr|g}n|}|D ]}|V  q|D ]j}|r|j|dd	 |j|v r
||j }|j}||j }| j }|rd|d< |j|jf| j||r| ndd
|}
n#| j }t j|jt| df| jd|r&| ndd
|}
t||
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  rO  )rP  rQ  rP  rB   r   r   rW   r   requested_tool_nameavailable_tool_names)_prepare_intermediate_stepsr'  rI   	get_childr   ro   r-  r(  r[   rR   send_to_llmr   
llm_outputcallabler   on_agent_actionr   r  r   
tool_inputrQ  r   r   r  r4  r$   r   keys)r7   r^  r`  r   r@   r  r4   eraise_errorr   r   tool_run_kwargsactionsagent_actionr  r4  rP  r5   r5   r8   rb  Z  s   






(






zAgentExecutor._iter_next_stepc              
     s*   |  dd | |||||2 I d H S )Nc                   s   g | z3 d H W }|q6 S r=   r5   r[  r5   r5   r8   r    s
    z2AgentExecutor._atake_next_step.<locals>.<listcomp>)r]  _aiter_next_steprc  r5   r5   r8   _atake_next_step  s   
zAgentExecutor._atake_next_step9AsyncIterator[Union[AgentFinish, AgentAction, AgentStep]]c              
    s  z |}jj|fdr ndi|I dH }W n ty } z~tjtr0j }nd}|r=tdt	| t	|}	tjtrX|j
rUt	|j}
t	|j}	nd}
ntjt	rbj}
ntjrm|}
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}~ww t|tr|V  dS t|tr|g}n|}|D ]}|V  qdfdd tj fdd|D  I dH }|D ]}|V  qdS )rf  rB   NFrg  rh  ri  r  rj  rk  r{  r   r/   r   c                   s   rj | jddI d H  | jv rE| j }|j} | j }j }|r,d|d< |j| jfj|r: nd d|I d H }n%j }t	 j| jt
 dfjd r` nd d|I d H }t| |dS )NrO  )rQ  rP  rW   r   rj  rl  rk  )rt  rQ  r  r4  r'  r   r   ru  rp  r$   r   rv  r   )r{  r  r4  rP  ry  r   )r`  r^  r  r7   r5   r8   _aperform_agent_action  sD   






z>AgentExecutor._aiter_next_step.<locals>._aperform_agent_actionc                   s   g | ]} |qS r5   r5   )r  r{  )r  r5   r8   r  F  rF  z2AgentExecutor._aiter_next_step.<locals>.<listcomp>)r{  r   r/   r   )ro  r'  rL   rp  r   ro   r-  r(  r[   rR   rq  r   rr  rs  r   r   r  r   ru  rQ  r   r   asynciogather)r7   r^  r`  r   r@   r  r4   rw  rx  r   r   ry  rz  r{  resultr   r5   )r  r`  r^  r  r7   r8   r|    sz   





&
&
zAgentExecutor._aiter_next_stepc                 C  s  dd | j D }tdd | j D ddgd}g }d}d	}t }| ||rm| j|||||d
}	t|	tr=| j|	||d
S ||	 t	|	dkr]|	d }
| 
|
}|dur]| j|||d
S |d7 }t | }| ||s&| jj| j|fi |}| j|||d
S )(Run text through and get agent response.c                 S  rD  r5   r  r  r5   r5   r8   rE  T  rF  z'AgentExecutor._call.<locals>.<dictcomp>c                 S  r  r5   r  r  r5   r5   r8   r  W  r  z'AgentExecutor._call.<locals>.<listcomp>rO  redexcluded_colorsr           r  rZ  N)r_   r!   timerL  rd  ro   r   rU  extendr   _get_tool_returnr'  r]   rQ   r7   r   r  r^  r`  r@   rH  rJ  
start_timenext_step_outputnext_step_actiontool_returnr4   r5   r5   r8   _callM  sJ   


zAgentExecutor._callc              	     s  dd | j D }tdd | j D dgd}g }d}d}t }zt| j4 I d	H  | ||r| j|||||d
I d	H }	t|	trY| 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 | }| ||s1| jj| j|fi |}| j	|||d
I d	H W  d	  I d	H  W S 1 I d	H sw   Y  W d	S  ttjfy   | jj| j|fi |}| j	|||d
I d	H  Y S w )r  c                 S  rD  r5   r  r  r5   r5   r8   rE    rF  z(AgentExecutor._acall.<locals>.<dictcomp>c                 S  r  r5   r  r  r5   r5   r8   r    r  z(AgentExecutor._acall.<locals>.<listcomp>rO  r  r   r  Nr  rZ  )r_   r!   r  r-   r,  rL  r}  ro   r   rW  r  r   r  r'  r]   rQ   TimeoutErrorr  r  r5   r5   r8   _acall|  sr   





4"zAgentExecutor._acallr  Tuple[AgentAction, str]Optional[AgentFinish]c                 C  s`   |\}}dd | j D }d}t| jjdkr| 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  rD  r5   r  r  r5   r5   r8   rE    rF  z2AgentExecutor._get_tool_return.<locals>.<dictcomp>r4   r   rW   N)r_   r   r'  r9   r  r4  r   )r7   r  r{  r   r^  return_value_keyr5   r5   r8   r    s   
zAgentExecutor._get_tool_returnc                 C  s>   t | jtr| jdkr|| j d  S t| jr| |S |S )Nr   )ro   r/  rI  rs  )r7   r@   r5   r5   r8   ro    s   



z)AgentExecutor._prepare_intermediate_stepsinputUnion[Dict[str, Any], Any]r   Optional[RunnableConfig]Iterator[AddableDict]c                 k  sT    t |}t| ||df|d|d|ddd|}|D ]}|V  q"dS z9Enables streaming over steps taken to reach final output.rB   rA  metadatarun_nameT)rA  r  r  yield_actionsNr   r"   getr7   r  r   rC   iteratorstepr5   r5   r8   r     s"   
zAgentExecutor.streamAsyncIterator[AddableDict]c                 K s^   t |}t| ||df|d|d|ddd|}|2 z	3 dH W }|V  q"6 dS r  r  r  r5   r5   r8   r     s"   
zAgentExecutor.astreamr=   )
r'  r&  r_   r`   rB   r*   rC   r   r/   r%  r  r   )
r   r   rB   r*   r?  r(  r@  r(  r/   r"   r   )r  rR   r/   r    )rH  rI  rJ  rK  r/   r(  )r4   r   r@   r   r  rM  r/   r   )r4   r   r@   r   r  rV  r/   r   )r   rX  r/   rY  )r^  r_  r`  ra  r   ra  r@   rA   r  rM  r/   rY  )r^  r_  r`  ra  r   ra  r@   rA   r  rM  r/   re  )r^  r_  r`  ra  r   ra  r@   rA   r  rV  r/   rY  )r^  r_  r`  ra  r   ra  r@   rA   r  rV  r/   r~  )r   ra  r  rM  r/   r   )r   ra  r  rV  r/   ra  )r  r  r/   r  )r@   rA   r/   rA   )r  r  r   r  rC   r   r/   r  )r  r  r   r  rC   r   r/   r  )&r   r   r   r   r   r)  r+  r,  rQ   r-  r/  r   r0  r   r3  r5  r<  r   r>  rB  r   rP   rC  rG  rL  rU  rW  r]  rd  rb  r}  r|  r  r  r  ro  r   r   r5   r5   r5   r8   r%  t  s   
 








ox2
>
r%  )Zr   
__future__r   r  r   loggingr  abcr   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   r   langchain_core._apir   langchain_core.agentsr   r   r   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.pydantic_v1r   r   langchain_core.runnablesr   r   r   langchain_core.runnables.utilsr   langchain_core.toolsr    langchain_core.utils.inputr!   langchain.agents.agent_iteratorr"   langchain.agents.agent_typesr#   langchain.agents.toolsr$   langchain.callbacks.baser%   langchain.callbacks.managerr&   r'   r(   r)   r*   langchain.chains.baser+   langchain.chains.llmr,   langchain.utilities.asyncior-   	getLoggerr   r  r.   r   r   r   r   r   r   r   r  rX  r%  r5   r5   r5   r8   <module>   st    0
 }

`dR `