
    @'h2                    N   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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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.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z=m>Z>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZG ddlHmIZI ddlJmKZK ddlLmMZM ddlNmOZO  ej                  eQ      ZR G d d e=      ZS G d! d"e=      ZT G d# d$e+eeef            ZU G d% d&e+eeVe   ef            ZW G d' d(eS      ZX G d) d*eT      ZY ed+eCd,-       G d. d/eS             ZZ ed+eCd,-       G d0 d1eS             Z[ G d2 d3e9      Z\eVeeeef      Z]eeXeYf   Z^ G d4 d5eK      Z_y)6zEChain that takes in an input and produces an action and action input.    )annotationsN)abstractmethod)AsyncIteratorIteratorSequence)Path)AnyCallableOptional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                      e Zd ZdZedd       ZddZe	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Z	eedd              Z
	 	 	 	 	 	 	 	 ddZe	 d	 	 	 	 	 	 	 	 	 dd       Zedd	       Zd fd
ZddZddZ xZS )BaseSingleActionAgentzBase Single Action Agent class.c                    dgS Return values of the agent.output selfs    ]/home/kushmeetdev/Regenta/Chatbot/venv/lib/python3.12/site-packages/langchain/agents/agent.pyreturn_valuesz#BaseSingleActionAgent.return_values<        z    c                     y Nr6   r7   s    r9   get_allowed_toolsz'BaseSingleActionAgent.get_allowed_toolsA   s    r<   c                     y)0  Given input, decided what to do.

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

        Returns:
            Action specifying what tool to use.
        Nr6   r8   intermediate_steps	callbackskwargss       r9   planzBaseSingleActionAgent.planD       r<   c                   K   yw)6  Async given input, decided what to do.

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

        Returns:
            Action specifying what tool to use.
        Nr6   rB   s       r9   aplanzBaseSingleActionAgent.aplanW           c                     y7Return the input keys.

        :meta private:
        Nr6   r7   s    r9   
input_keysz BaseSingleActionAgent.input_keysj   rG   r<   c                F    |dk(  rt        ddid      S t        d| 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.
        forcer5   3Agent stopped due to iteration limit or time limit. 'Got unsupported early_stopping_method ``r   
ValueErrorr8   early_stopping_methodrC   rE   s       r9   return_stopped_responsez-BaseSingleActionAgent.return_stopped_responser   sC    ( !G+PQSU  9:O9PPQR r<   c                    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)clsllmtoolscallback_managerrE   s        r9   from_llm_and_toolsz(BaseSingleActionAgent.from_llm_and_tools   s
    & "!r<   c                    t         z#Return Identifier of an agent type.r^   r7   s    r9   _agent_typez!BaseSingleActionAgent._agent_type   
     "!r<   c                    t         |          }	 | j                  }t	        |t
              rt        |j                        |d<   |S |||d<   |S # t        $ r d}Y @w xY w)z{Return dictionary representation of agent.

        Returns:
            Dict: Dictionary representation of agent.
        N_type)super
model_dumprg   r_   
isinstancer+   strvalue)r8   rE   _dictrj   	__class__s       r9   dictzBaseSingleActionAgent.dict   ss     "$	$$E eY' -E'N  "E'N # 	E	s   A AAc                   t        |t              rt        |      }n|}|j                  }|j	                  dd       | j                         }d|vrt        d|  d      |j                  dk(  r.t        |d      5 }t        j                  ||d	       d
d
d
       y
|j                  j                  d      r.t        |d      5 }t        j                  ||d       d
d
d
       y
t        | d      # 1 sw Y   y
xY w# 1 sw Y   y
xY w)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_okrj   Agent z does not support saving.jsonw   indentNz.yamlz.ymlFdefault_flow_style must be json or yaml)rm   rn   r   parentmkdirrr   r_   suffixopenjsondumpendswithyamlrY   )r8   	file_path	save_pathdirectory_path
agent_dictfs         r9   savezBaseSingleActionAgent.save   s    i%YI!I"))TD9 YY[
*$%tf4L&MNNw&i% 3		*a23 3&&'89i% C		*aEBC C 	{*?@AA3 3C C   <C5D5C>D
c                    i S #Return logging kwargs for tool run.r6   r7   s    r9   tool_run_logging_kwargsz-BaseSingleActionAgent.tool_run_logging_kwargs   s    	r<   return	list[str]r   Optional[list[str]]r>   rC   list[tuple[AgentAction, str]]rD   r   rE   r	   r   Union[AgentAction, AgentFinish]r[   rn   rC   r   rE   r	   r   r   )
ra   r   rb   Sequence[BaseTool]rc   Optional[BaseCallbackManager]rE   r	   r   r1   r   rn   rE   r	   r   builtins.dictr   zUnion[Path, str]r   Noner   r   )__name__
__module____qualname____doc__propertyr:   r?   r   rF   rJ   rP   r\   classmethodrd   rg   rr   r   r   __classcell__rq   s   @r9   r1   r1   9   sP   )    $9  	
 
) $   $9  	
 
) $   " : 	
 
< 
 ;?	"" "" 8	"
 " 
" "( " ""!BFr<   r1   c                       e Zd ZdZedd       ZddZe	 d	 	 	 	 	 	 	 dd       Ze	 d	 	 	 	 	 	 	 dd       Z	eedd              Z
	 	 	 	 	 	 	 	 ddZedd       Zd fd	Zdd
ZddZ xZS )BaseMultiActionAgentzBase Multi Action Agent class.c                    dgS r3   r6   r7   s    r9   r:   z"BaseMultiActionAgent.return_values   r;   r<   c                     y)z]Get allowed tools.

        Returns:
            Optional[List[str]]: Allowed tools.
        Nr6   r7   s    r9   r?   z&BaseMultiActionAgent.get_allowed_tools   s     r<   c                     y)a5  Given input, decided what to do.

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

        Returns:
            Actions specifying what tool to use.
        Nr6   rB   s       r9   rF   zBaseMultiActionAgent.plan   rG   r<   c                   K   yw)a;  Async given input, decided what to do.

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

        Returns:
            Actions specifying what tool to use.
        Nr6   rB   s       r9   rJ   zBaseMultiActionAgent.aplan  rK   rL   c                     yrN   r6   r7   s    r9   rP   zBaseMultiActionAgent.input_keys  rG   r<   c                F    |dk(  rt        ddid      S t        d| d      )rR   rS   r5   z$Agent stopped due to max iterations.rU   rV   rW   rX   rZ   s       r9   r\   z,BaseMultiActionAgent.return_stopped_response!  s<    ( !G+*PQSUVV9:O9PPQR r<   c                    t         rf   r^   r7   s    r9   rg   z BaseMultiActionAgent._agent_type=  rh   r<   c                v    t         |          }	 t        | j                        |d<   |S # t        $ r Y |S w xY w)*Return dictionary representation of agent.rj   )rk   rl   rn   rg   r_   r8   rE   rp   rq   s      r9   rr   zBaseMultiActionAgent.dictB  sI    "$	 !1!12E'N  # 		s   + 	88c                   t        |t              rt        |      }n|}| j                         }d|vrt	        d|  d      |j
                  }|j                  dd       |j                  dk(  r.t        |d      5 }t        j                  ||d	       d
d
d
       y
|j                  j                  d      r.t        |d      5 }t        j                  ||d       d
d
d
       y
t        | d      # 1 sw Y   y
xY w# 1 sw Y   y
xY w)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")
        rj   rw   z does not support saving.Trt   rx   ry   rz   r{   Nr}   Fr~   r   )rm   rn   r   rr   r_   r   r   r   r   r   r   r   r   rY   )r8   r   r   r   r   r   s         r9   r   zBaseMultiActionAgent.saveK  s   " i%YI!I YY[
*$%tf4M&NOO"))TD9w&i% 3		*a23 3&&'89i% C		*aEBC C 	{*?@AA3 3C Cr   c                    i S r   r6   r7   s    r9   r   z,BaseMultiActionAgent.tool_run_logging_kwargsr  s	     	r<   r   r   r>   rC   r   rD   r   rE   r	   r   %Union[list[AgentAction], AgentFinish]r   r   r   r   r   )r   r   r   r   r   r:   r?   r   rF   rJ   rP   r\   rg   rr   r   r   r   r   s   @r9   r   r      s   (    $9  	
 
/ $   $9  	
 
/ $   " : 	
 
8 " "%BNr<   r   c                  "    e Zd ZdZedd       Zy)AgentOutputParserz=Base class for parsing agent output into agent action/finish.c                     y)z$Parse text into agent action/finish.Nr6   r8   texts     r9   parsezAgentOutputParser.parse{  rG   r<   N)r   rn   r   r   r   r   r   r   r   r   r6   r<   r9   r   r   x  s    G3 3r<   r   c                  "    e Zd ZdZedd       Zy)MultiActionAgentOutputParserzBase class for parsing agent output into agent actions/finish.

    This is used for agents that can return multiple actions.
    c                     y)zParse text into agent actions/finish.

        Args:
            text: Text to parse.

        Returns:
            Union[List[AgentAction], AgentFinish]:
                List of agent actions or agent finish.
        Nr6   r   s     r9   r   z"MultiActionAgentOutputParser.parse  rG   r<   N)r   rn   r   r   r   r6   r<   r9   r   r     s    
 	 	r<   r   c                      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
      Z	e
dd       Ze
dd       Z	 d	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 ddZy)RunnableAgentAgent powered by Runnables.z/Runnable[dict, Union[AgentAction, AgentFinish]]runnabler   input_keys_argreturn_keys_argTboolstream_runnablearbitrary_types_allowedc                    | j                   S r4   r   r7   s    r9   r:   zRunnableAgent.return_values       ###r<   c                    | j                   S )zReturn the input keys.r   r7   s    r9   rP   zRunnableAgent.input_keys  s     """r<   Nc                    i |d|i}d}| j                   r0| j                  j                  |d|i      D ]  }||}||z  } |S | j                  j                  |d|i      }|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.
        rC   NrD   configr   r   streaminvoker8   rC   rD   rE   inputsfinal_outputchunks          r9   rF   zRunnableAgent.plan  s    " JFI35GHI  --fk9=U-V *'#(L E)L	*   ==//Y?W/XLr<   c                   K   i |d|i}d}| j                   r3| j                  j                  |d|i      2 3 d{   }||}||z  }| j                  j                  |d|i       d{   }|S 7 86 |S 7 w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.
        rC   NrD   r   r   r   astreamainvoker   s          r9   rJ   zRunnableAgent.aplan  s     ( JFI35GHI   $}}44Y7  5   * *e  '#(L E)L!%!6!6Y7 "7 " L *   2   6A<A7A5A7 .A<.A:/A<5A77A<r   r>   r   r   r   r   r   __annotations__r   r   r   r&   model_configr   r:   rP   rF   rJ   r6   r<   r9   r   r     s    %==/ "NI"!#OY# OT   $L $ $ # #  $"9" " 	"
 
)"N  $(9( ( 	(

(r<   r   c                      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
      Z	e
dd       Ze
dd       Z	 d	 	 	 	 	 	 	 ddZ	 d	 	 	 	 	 	 	 ddZy)RunnableMultiActionAgentr   z5Runnable[dict, Union[list[AgentAction], AgentFinish]]r   r   r   r   Tr   r   r   c                    | j                   S r   r   r7   s    r9   r:   z&RunnableMultiActionAgent.return_values  r   r<   c                    | j                   S )QReturn the input keys.

        Returns:
            List of input keys.
        r   r7   s    r9   rP   z#RunnableMultiActionAgent.input_keys  s     """r<   Nc                    i |d|i}d}| j                   r0| j                  j                  |d|i      D ]  }||}||z  } |S | j                  j                  |d|i      }|S r   r   r   s          r9   rF   zRunnableMultiActionAgent.plan$  s    ( JFI35GHI  --fk9=U-V *'#(L E)L	*   ==//Y?W/XLr<   c                   K   i |d|i}d}| j                   r3| j                  j                  |d|i      2 3 d{   }||}||z  }| j                  j                  |d|i       d{   }|S 7 86 |S 7 wr   r   r   s          r9   rJ   zRunnableMultiActionAgent.aplanK  s     ( JFI35GHI   $}}44Y7  5   * *e  '#(L E)L!%!6!6Y7 "7 " L *   	r   r   r>   r   r   r6   r<   r9   r   r     s    %CC0 "NI"!#OY# OT   $L $ $ # #  $%9% % 	%

%T  $)9) ) 	)

)r<   r   z0.1.0z1.0)messageremovalc                       e Zd ZU dZded<   	 ded<   	 ded<   	 edd       Zd fd	Z	 d	 	 	 	 	 	 	 dd
Z	 d	 	 	 	 	 	 	 ddZ	ddZ
 xZS )LLMSingleActionAgentz$Base class for single action agents.r.   	llm_chainr   output_parserr   stopc                Z    t        t        | j                  j                        dhz
        S )r   rC   listsetr   rP   r7   s    r9   rP   zLLMSingleActionAgent.input_keys  s'     C1126J5KKLLr<   c                *    t         |          }|d= |S r   r   rk   rr   r   s      r9   rr   zLLMSingleActionAgent.dict      /"r<   c                     | j                   j                  d|| j                  |d|}| j                  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.
        rC   r   rD   r6   )r   runr   r   r   r8   rC   rD   rE   r5   s        r9   rF   zLLMSingleActionAgent.plan  sO    " $## 
1
 	
 !!''//r<   c                   K    | j                   j                  d|| j                  |d| d{   }| j                  j	                  |      S 7 w)rI   r  Nr6   )r   arunr   r   r   r  s        r9   rJ   zLLMSingleActionAgent.aplan  s]     " +t~~** 
1
 	
 
 !!''//
s   .AA Ac                ^    dt        | j                        dk(  rddS | j                  d   dS )r   rU   r   
llm_prefixobservation_prefix)lenr   r7   s    r9   r   z,LLMSingleActionAgent.tool_run_logging_kwargs  s8     (+DII!(;"
 	
AE1
 	
r<   r   r   r>   r   r   )r   r   r   r   r   r   rP   rr   rF   rJ   r   r   r   s   @r9   r   r   w  s     /$$$)
O%M M  $090 0 	0
 
)08  $090 0 	0
 
)02
r<   r   c                      e Zd ZU dZded<   	 ded<   	 dZded<   	 d fd	Zdd
Zed d       Z	d!dZ
ed d       Z	 	 	 	 d"dZ	 d#	 	 	 	 	 	 	 d$dZ	 d#	 	 	 	 	 	 	 d$dZ	 	 	 	 	 	 d%dZed d       Z ed      d&d       Zeed'd              Zeed'd              Zeed(d              Zed)d       Zeed*d              Ze	 	 d+	 	 	 	 	 	 	 	 	 	 	 d,d       Z	 	 	 	 	 	 	 	 d-dZd.dZ xZS )/AgentzAgent that calls the language model and deciding the action.

    This is driven by a LLMChain. The prompt in the LLMChain MUST include
    a variable called "agent_scratchpad" where the agent can put its
    intermediary work.
    r.   r   r   r   Nr   allowed_toolsc                *    t         |          }|d= |S r   r   r   s      r9   rr   z
Agent.dict  r   r<   c                    | j                   S )zGet allowed tools.)r  r7   s    r9   r?   zAgent.get_allowed_tools  s    !!!r<   c                    dgS r3   r6   r7   s    r9   r:   zAgent.return_values  r;   r<   c                    t        d      )zsFix the text.

        Args:
            text: Text to fix.

        Returns:
            str: Fixed text.
        z(fix_text not implemented for this agent.rY   r   s     r9   	_fix_textzAgent._fix_text  s     CDDr<   c                v    d| j                   j                          d| j                   j                          gS )N
z
	)r
  rstripr7   s    r9   _stopzAgent._stop  sB     ((//1234**11345
 	
r<   c                ~    d}|D ]5  \  }}||j                   z  }|d| j                   | d| j                   z  }7 |S )zJConstruct the scratchpad that lets the agent continue its thought process.rU   r  )logr
  r	  )r8   rC   thoughtsactionobservations        r9   _construct_scratchpadzAgent._construct_scratchpad  s[     #5 	WFK

"H"T445k]"T__DUVVH	W r<   c                     | j                   |fi |} | j                  j                  dd|i|}| j                  j	                  |      S )rA   rD   r6   )get_full_inputsr   predictr   r   )r8   rC   rD   rE   full_inputsfull_outputs         r9   rF   z
Agent.plan  sQ    " +d**+=HH,dnn,,PyPKP!!''44r<   c                   K    | j                   |fi |} | j                  j                  dd|i| d{   }| j                  j	                  |       d{   }|S 7 )7 w)rI   rD   Nr6   )r   r   apredictr   aparse)r8   rC   rD   rE   r"  r#  agent_outputs          r9   rJ   zAgent.aplan#  sj     " +d**+=HH3DNN33WiW;WW!//66{CC XCs!   5A%A!"A%A#A%#A%c                R    | j                  |      }|| 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  )r8   rC   rE   r  
new_inputsr"  s         r9   r   zAgent.get_full_inputs9  s8     --.@A*2DJJG
..:.r<   c                Z    t        t        | j                  j                        dhz
        S )rO   r*  r   r7   s    r9   rP   zAgent.input_keysK  s'     C1126H5IIJJr<   aftermodec                x   | j                   j                  }d|j                  vrt        j	                  d       |j                  j                  d       t        |t              r|xj                  dz  c_        | S t        |t              r|xj                  dz  c_
        | S 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   promptinput_variablesloggerwarningappendrm   r   templater   r   rY   type)r8   r1  s     r9   validate_promptzAgent.validate_promptS  s     &&V%;%;;NN= ""))*<=&.1#99
 	 F$9:!77  !#>tF|n!MNNr<   c                     y)z&Prefix to append the observation with.Nr6   r7   s    r9   r
  zAgent.observation_prefixp  rG   r<   c                     y)z#Prefix to append the LLM call with.Nr6   r7   s    r9   r	  zAgent.llm_prefixu  rG   r<   c                     y)zCreate a prompt for this class.

        Args:
            tools: Tools to use.

        Returns:
            BasePromptTemplate: Prompt template.
        Nr6   r`   rb   s     r9   create_promptzAgent.create_promptz  rG   r<   c                     y)zgValidate that appropriate tools are passed in.

        Args:
            tools: Tools to use.
        Nr6   r<  s     r9   _validate_toolszAgent._validate_tools  s     	r<   c                     y)z)Get default output parser for this class.Nr6   )r`   rE   s     r9   _get_default_output_parserz Agent._get_default_output_parser  rG   r<   c                    | j                  |       t        || j                  |      |      }|D cg c]  }|j                   }}|xs | j	                         }	 | d|||	d|S c c}w )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.
        )ra   r1  rc   )r   r  r   r6   )r?  r.   r=  namerA  )
r`   ra   rb   rc   r   rE   r   tool
tool_names_output_parsers
             r9   rd   zAgent.from_llm_and_tools  s    * 	E"$$U+-
	
 -22Ddii2
2&J#*H*H*J 
$(
 	
 	
 3s   A(c                   |dk(  rt        ddid      S |dk(  rd}|D ]5  \  }}||j                  z  }|d| j                   | d| j                   z  }7 |dz  }|| j                  d}i ||} | j
                  j                  d
i |}	| j                  j                  |	      }
t        |
t               r|
S t        d|	i|	      S t        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'].
        rS   r5   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 r6   )r   r  r
  r	  r  r   r!  r   r   rm   rY   )r8   r[   rC   rE   r  r  r  r+  r"  r#  parsed_outputs              r9   r\   zAgent.return_stopped_response  s   ( !G+PQSU  #j0H'9 #FJJ&001+b@QR VH /7

KJ2V2z2K0$..00?;?K ..44[AM-5$$ #Hk#:KHH,-/ r<   c                4    | j                   | j                  dS )r   r  r  r7   s    r9   r   zAgent.tool_run_logging_kwargs  s     //"&"9"9
 	
r<   r   r   r   )r   rn   r   rn   )rC   r   r   zUnion[str, list[BaseMessage]]r>   r   )rC   r   rE   r	   r   zbuiltins.dict[str, Any]r   r(   r   )rb   r   r   r   )rb   r   r   r   )rE   r	   r   r   )NN)ra   r   rb   r   rc   r   r   zOptional[AgentOutputParser]rE   r	   r   r  r   r   )r   r   r   r   r   r  rr   r?   r   r:   r  r  r  rF   rJ   r   rP   r'   r8  r   r
  r	  r   r=  r?  rA  rd   r\   r   r   r   s   @r9   r  r    s/    $$$))-M&-F"  	E 
 
"?	&  $595 5 	5
 
)50  $9  	
 
),"?KN	 $ K K '" #8 5  5 2  2      8  8 
 ;?59!
!
 "!
 8	!

 3!
 !
 
!
 !
F5"5 :5 	5
 
5n
r<   r  c                  ^    e Zd ZU dZdZded<   	 dZded<   	 	 d
	 	 	 	 	 ddZ	 d
	 	 	 	 	 dd	Zy)ExceptionToolz!Tool that just returns the query.
_Exceptionrn   rC  zException tooldescriptionNc                    |S r>   r6   r8   queryrun_managers      r9   _runzExceptionTool._run   s	    
 r<   c                   K   |S wr>   r6   rQ  s      r9   _arunzExceptionTool._arun  s     
 s   r>   )rR  rn   rS  z#Optional[CallbackManagerForToolRun]r   rn   )rR  rn   rS  z(Optional[AsyncCallbackManagerForToolRun]r   rn   )	r   r   r   r   rC  r   rO  rT  rV  r6   r<   r9   rM  rM    sn    +D#'K'"
 <@ 9 
	 AE > 
	r<   rM  c                      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	 d5	 	 	 	 	 	 	 	 	 d6d       Z ed      d7d       Z ed      ed8d              Zed9d       Zd:dZd:dZ	 d5ddd 	 	 	 	 	 	 	 	 	 d;d!Zed<d"       Zed<d#       Zd=d$Zd>d%Z	 d5	 	 	 	 	 	 	 d?d&Z	 d5	 	 	 	 	 	 	 d@d'Z	 	 	 	 dAd(Z	 d5	 	 	 	 	 	 	 	 	 	 	 dBd)Z	 d5	 	 	 	 	 	 	 	 	 	 	 dCd*Z	 d5	 	 	 	 	 	 	 	 	 dDd+Z	 d5	 	 	 	 	 	 	 	 	 	 	 dEd,Z	 d5	 	 	 	 	 	 	 	 	 	 	 dFd-Z 	 d5	 	 	 	 	 	 	 	 	 dGd.Z!	 d5	 	 	 	 	 dHd/Z"	 d5	 	 	 	 	 dId0Z#	 	 	 	 dJd1Z$	 	 	 	 dKd2Z%	 d5	 	 	 	 	 	 	 dLd3Z&	 d5	 	 	 	 	 	 	 dMd4Z'y)NAgentExecutorzAgent that is using tools.<Union[BaseSingleActionAgent, BaseMultiActionAgent, Runnable]agentr   rb   Fr   return_intermediate_steps   zOptional[int]max_iterationsNzOptional[float]max_execution_timerS   rn   r[   z8Union[bool, str, Callable[[OutputParserException], str]]handle_parsing_errorszTUnion[int, Callable[[list[tuple[AgentAction, str]]], list[tuple[AgentAction, str]]]]trim_intermediate_stepsc                     | 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.
        )rZ  rb   rD   r6   r6   )r`   rZ  rb   rD   rE   s        r9   from_agent_and_toolsz"AgentExecutor.from_agent_and_toolsC  s)    &  

 	
 	
r<   r-  r.  c           	         | j                   }| j                  }|j                         }|Yt        |      t        |D cg c]  }|j                   c}      k7  r*t        d| d|D cg c]  }|j                   c} d      | S c c}w c c}w )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.
        zAllowed tools (z!) different than provided tools ())rZ  rb   r?   r   rC  rY   )r8   rZ  rb   r  rD  s        r9   validate_toolszAgentExecutor.validate_tools]  s     



//1$=!S)F$)))F%GG %m_ 5'>C'Dd		'D&EQH   *G (Es   B
'Bbeforec                <   |j                  d      }|rpt        |t              r`	 |j                  }|t        t
        t           t        f   k(  }|j                  dd      }|rt        ||      |d<   |S t        ||      |d<   |S # t        $ r}d}Y d}~Hd}~ww xY w)zConvert runnable to agent if passed in.

        Args:
            values: Values to validate.

        Returns:
            Dict: Validated values.
        rZ  FNr   T)r   r   )getrm   r   
OutputTyper   r   r   r   	Exceptionpopr   r   )r`   valuesrZ  output_typemulti_action_r   s          r9   validate_runnable_agentz%AgentExecutor.validate_runnable_agentu  s     

7#Zx0T#..  +eD4E{4R.SS$jj):DAO":"O#w  #0"O#w   %$%s   B 	BBBc                    t        | j                  t              rt        t        | j                        S | j                  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.
        )rm   rZ  r   r   RunnableAgentTyper7   s    r9   _action_agentzAgentExecutor._action_agent  s.     djj(+)4::66::r<   c                    t        d      )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(...)`r  r8   r   s     r9   r   zAgentExecutor.save  s     !
 	
r<   c                8    | j                   j                  |      S )zZSave the underlying agent.

        Args:
            file_path: Path to save to.
        )rt  r   rv  s     r9   
save_agentzAgentExecutor.save_agent  s     !!&&y11r<   )include_run_infoasync_c               6    t        | ||| j                  |      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.
        )tagsry  )r*   r|  )r8   r   rD   ry  rz  s        r9   iterzAgentExecutor.iter  s$    & %-
 	
r<   c                .    | j                   j                  S )rO   )rt  rP   r7   s    r9   rP   zAgentExecutor.input_keys  s     !!,,,r<   c                z    | j                   r| j                  j                  dgz   S | j                  j                  S )z@Return the singular output key.

        :meta private:
        rC   )r[  rt  r:   r7   s    r9   output_keyszAgentExecutor.output_keys  s:     ))%%337K6LLL%%333r<   c                \    | j                   D ci c]  }|j                  | c}|   S c c}w )zLookup tool by name.

        Args:
            name: Name of tool.

        Returns:
            BaseTool: Tool object.
        )rb   rC  )r8   rC  rD  s      r9   lookup_toolzAgentExecutor.lookup_tool  s)     -1JJ7D		47==7s   )c                t    | j                   || j                   k\  ry| j                  || j                  k\  ryy)NFT)r]  r^  )r8   
iterationstime_elapseds      r9   _should_continuezAgentExecutor._should_continue  s>    *zT=P=P/P##/ 7 77r<   c                    |r|j                  |d| j                         |j                  }| j                  r||d<   |S Ngreen)colorverboserC   on_agent_finishr  r:   r[  r8   r5   rC   rS  r   s        r9   _returnzAgentExecutor._return  sE     ''gt||'T++))1CL-.r<   c                   K   |r&|j                  |d| j                         d {    |j                  }| j                  r||d<   |S 7 #wr  r  r  s        r9   _areturnzAgentExecutor._areturn  s_      --gt|| .    ++))1CL-.s   $AA
$Ac                    t        |d   t              rt        |      dk(  sJ |d   S |D cg c]+  }t        |t              s|j                  |j
                  f- c}S c c}w )Nr`     )rm   r   r  r   r  r  )r8   rm  as      r9   _consume_next_stepz AgentExecutor._consume_next_step  sc     fRj+.v;!###": 4:./Z9=U1==)  s   A A c           	     p    | j                  | j                  |||||      D cg c]  }| c}      S c c}w r>   )r  _iter_next_stepr8   name_to_tool_mapcolor_mappingr   rC   rS  r  s          r9   _take_next_stepzAgentExecutor._take_next_step%  sN     && --$!&	 	
 	
	s   	3c              #  |  K   	 | j                  |      } | j                  j                  |fd|r|j                         ndi|}t        |t,              r| yt        |t              r|g}n|}|D ]  }|  |D ]  }| j/                  ||||        y# t        $ r}t        | j                  t              r| j                   }nd}|rt        dt        |             t        |      }	t        | j                  t              r:|j                  r+t        |j                        }
t        |j                        }	n\d}
nYt        | j                  t              r| j                  }
n2t        | j                        r| j                  |      }
nt        d      t        d|
|	      }|r|j                  |d	       | j                  j!                         } t#               j$                  |j&                  f| j(                  d|r|j                         ndd
|}
t+        ||
       Y d}~yd}~ww xY ww)Take a single step in the thought-action-observation loop.

        Override this to take control of how the agent makes and acts on choices.
        rD   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`rN  r  r  r  r  rD   r  r  )_prepare_intermediate_stepsrt  rF   	get_childr   rm   r_  r   rY   rn   send_to_llmr  
llm_outputcallabler   on_agent_actionr   rM  r  
tool_inputr  r   r   _perform_agent_action)r8   r  r  r   rC   rS  r5   eraise_errorr   r  tool_run_kwargsactionsagent_actions                 r9   r  zAgentExecutor._iter_next_step:  s9    .	!%!A!ABT!U -T'',,"5@+//1d FZ fk*L fk*hGG# 	L	# 	L,, -{ 	g % %	$44d;"&"<"<<# * +.a&3  q6D$44d;=="%amm"4Kq||,D"BKD66<"88$445"88; !QRR {DAF++F'+B"00HHJO--/--!!5@+//1d	
 "K 6{CCK%	s1   H<AB AH<
H9$FH4/H<4H99H<c                f   |r|j                  |d       |j                  |v r||j                     }|j                  }||j                     }| j                  j	                         }|rd|d<    |j
                  |j                  f| j                  ||r|j                         nd d|}	ny| j                  j	                         } t               j
                  |j                  t        |j                               df| j                  d |r|j                         nd d|}	t        ||	      S )Nr  r  rU   r	  r  requested_tool_nameavailable_tool_namesr  )r  rD  return_directrt  r   r  r  r  r  r,   r   keysr   
r8   r  r  r  rS  rD  r  r  r  r  s
             r9   r  z#AgentExecutor._perform_agent_action  s;    ''G'D 00#L$5$56D ..M!,"3"34E"00HHJO02-"$((''5@+//1d	
 "K #00HHJO++-+++7+<+<,01A1F1F1H,I	
 5@+//1d	 "	K +FFr<   c           	        K   | j                  | j                  |||||      2 cg c3 d {   }|7 6 c}      S c c}w wr>   )r  _aiter_next_stepr  s          r9   _atake_next_stepzAgentExecutor._atake_next_step  s]      &&  $44$!& 	 	 	 	
 	
	s&   #A=5
35
=5
=Ac                 K   	 | j                  |      } | j                  j                  |fd|r|j                         ndi| d{   }t        |t*              r| yt        |t              r|g}n|}|D ]  }| 	 t-        j.                  |D cg c]  }| j1                  ||||       c}  d{   }|D ]  }| 	 y7 # t        $ r}t        | j                  t              r| j                   }nd}|rt        dt        |             t        |      }	t        | j                  t              r:|j                  r+t        |j                        }
t        |j                        }	n\d}
nYt        | j                  t              r| j                  }
n2t        | j                        r| j                  |      }
nt        d      t        d|
|	      }| j                  j                         } t!               j"                  |j$                  f| j&                  d|r|j                         ndd| d{  7  }
t)        ||
	       Y d}~yd}~ww xY wc c}w 7 w)
r  rD   NFr  r  r  rN  r  r  )r  rt  rJ   r  r   rm   r_  r   rY   rn   r  r  r  r  r   r   rM  r  r  r  r   r   asynciogather_aperform_agent_action)r8   r  r  r   rC   rS  r5   r  r  r   r  r  r  r  resultr   s                   r9   r  zAgentExecutor._aiter_next_step  sp    ,	!%!A!ABT!U 44--33"5@+//1d  FV fk*L fk*hGG# 	L	 ~~
 %,	 ! ++$m\;
 
  	EK	E
 % #	$44d;"&"<"<<# * +.a&3  q6D$44d;=="%amm"4Kq||,D"BKD66<"88$445"88; !QRR {DAF"00HHJO 4 4 4!!!5@+//1d	!
 "!  K 6{CCG#	h
sg   I.AC 	C
C AI.I&4I.;I+<I.C 
I#E*IIII.I##	I.c                  K   |r&|j                  || j                  d       d {    |j                  |v r||j                     }|j                  }||j                     }| j                  j                         }|rd|d<    |j                  |j                  f| j                  ||r|j                         nd d| d {   }	n| j                  j                         } t               j                  |j                  t        |j                               df| j                  d |r|j                         nd d| d {   }	t        ||	      S 7 27 7 w)Nr  )r  r  rU   r	  r  r  r  )r  r  rD  r  rt  r   r  r  r  r,   r   r  r   r  s
             r9   r  z$AgentExecutor._aperform_agent_action  sq     --dll' .     00#L$5$56D ..M!,"3"34E"00HHJO02- )		''!5@+//1d	!
 "! K #00HHJO 2 2 2+7+<+<,01A1F1F1H,I	!
 5@+//1d	! "	! 	K +FF?	s5   $EEBEEBEEEEEc                   | j                   D ci c]  }|j                  | }}t        | j                   D cg c]  }|j                   c}ddg      }g }d}d}t        j                         }	| j	                  ||      r| j                  |||||      }
t        |
t              r| j                  |
||      S |j                  |
       t        |
      dk(  r,|
d   }| j                  |      }|| j                  |||      S |dz  }t        j                         |	z
  }| j	                  ||      r | j                  j                  | j                  |fi |}| j                  |||      S c c}w c c}w )z(Run text through and get agent response.r  redexcluded_colorsr           rS  r  )rb   rC  r$   timer  r  rm   r   r  extendr  _get_tool_returnrt  r\   r[   r8   r   rS  rD  r  r  rC   r  r  
start_timenext_step_outputnext_step_actiontool_returnr5   s                 r9   _callzAgentExecutor._callA  s    9=

CDIItOCC)#'::.4TYY.%@P
 =?
YY[
##J=#33 "'  4   *K8||$&8k $   %%&67#$)#3A#6 "334DE*<<#%7[ (   !OJ99;3L/ ##J=0 <##;;&&(:
>D
 ||F$6K|PPM D /s
   E2E7c                  K   | j                   D ci c]  }|j                  | }}t        | j                   D cg c]  }|j                   c}dg      }g }d}d}t        j                         }		 t	        | j
                        4 d{    | j                  ||      r| j                  |||||       d{   }
t        |
t              r-| j                  |
||       d{   cddd      d{    S |j                  |
       t        |
      dk(  rE|
d   }| j                  |      }|-| j                  |||       d{   cddd      d{    S |dz  }t        j                         |	z
  }| j                  ||      r | j                  j                  | j                   |fi |}| j                  |||       d{   cddd      d{    S c c}w c c}w 7 d7 77 7 7 7 7 /7 !# 1 d{  7  sw Y   yxY w# t"        t$        j"                  f$ rH  | j                  j                  | j                   |fi |}| j                  |||       d{  7  cY S w xY ww)z.Async run text through and get agent response.r  r  r   r  Nr  r  )rb   rC  r$   r  r/   r^  r  r  rm   r   r  r  r  r  rt  r\   r[   TimeoutErrorr  r  s                 r9   _acallzAgentExecutor._acallp  s     9=

CDIItOCC)#'::.4TYY.	
 =?
YY[
*	&t'>'>? ! !++JE-1-B-B(%*$/ .C . ($ ""2K@%)]],.(3 &3 &  ! ! !  '--.>?+,1+;A+>(&*&;&;<L&M&2)- +-?[ *7 * $-! ! !4 !OJ#'99;#;L5 ++JE6 D++CC..0BFL "]].K +  ?! ! ! D /!( !,$-!>?! ! ! !D g223 	?T''??**,>BHF * '    	s6  I<G%I<G*$I<2H G/H ,H;G2<+H'G5(H+H 7G88H <I<=AHG;HH G=H  I<!.H?HG?HH H H $I</H 2H5H8H ;H=H ?HH H	H
HH I<H AI90I31I96I<8I99I<c                D   |\  }}| j                   D ci c]  }|j                  | }}d}t        | j                  j                        dkD  r| j                  j                  d   }|j
                  |v r'||j
                     j                  rt        ||id      S yc c}w )z&Check if the tool is a returning tool.r5   r   rU   N)rb   rC  r  rt  r:   rD  r  r   )r8   r  r  r  rD  r  return_value_keys          r9   r  zAgentExecutor._get_tool_return  s     %5!k8<

CDIItOCC#t!!//014#11??B 00 1 12@@"%{3   Ds   Bc                    t        | j                  t              r| j                  dkD  r|| j                   d  S t        | j                        r| j                  |      S |S )Nr   )rm   ra  intr  )r8   rC   s     r9   r  z)AgentExecutor._prepare_intermediate_steps  s_     t33S9,,q0%t'C'C&C&EFFd223//0BCC%%r<   c           	   +     K   t        |      }t        | ||j                  d      f|j                  d      |j                  d      |j                  d      |j                  d      dd|}|E d{    y7 w)	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.
        rD   r|  metadatarun_namerun_idTr|  r  r  r  yield_actionsNr!   r*   ri  )r8   inputr   rE   iterators        r9   r   zAgentExecutor.stream  s}       v&(JJ{#

 F#ZZ
+ZZ
+::h'

 

 s   A0A:2A83A:c           	      K   t        |      }t        | ||j                  d      f|j                  d      |j                  d      |j                  d      |j                  d      dd|}|2 3 d{   }| 7 
6 yw)	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.
        rD   r|  r  r  r  Tr  Nr  )r8   r  r   rE   r  steps         r9   r   zAgentExecutor.astream  s     " v&(JJ{#

 F#ZZ
+ZZ
+::h'

 

 # 	 	$J	(s*   A-B/B 3A>4B 7B>B  Br>   )
rZ  rY  rb   r   rD   r   rE   r	   r   rX  rK  )rm  rr   r   r	   )r   z2Union[BaseSingleActionAgent, BaseMultiActionAgent]r   )
r   r	   rD   r   ry  r   rz  r   r   r*   r   )rC  rn   r   r#   )r  r  r  floatr   r   )r5   r   rC   r   rS  $Optional[CallbackManagerForChainRun]r   dict[str, Any])r5   r   rC   r   rS  )Optional[AsyncCallbackManagerForChainRun]r   r  )rm  NextStepOutputr   1Union[AgentFinish, list[tuple[AgentAction, str]]])r  dict[str, BaseTool]r  dict[str, str]r   r  rC   r   rS  r  r   r  )r  r  r  r  r   r  rC   r   rS  r  r   z4Iterator[Union[AgentFinish, AgentAction, AgentStep]])
r  r  r  r  r  r   rS  r  r   r   )r  r  r  r  r   r  rC   r   rS  r  r   r  )r  r  r  r  r   r  rC   r   rS  r  r   z9AsyncIterator[Union[AgentFinish, AgentAction, AgentStep]])
r  r  r  r  r  r   rS  r  r   r   )r   r  rS  r  r   r  )r   r  rS  r  r   r  )r  ztuple[AgentAction, str]r   zOptional[AgentFinish])rC   r   r   r   )r  Union[dict[str, Any], Any]r   Optional[RunnableConfig]rE   r	   r   zIterator[AddableDict])r  r  r   r  rE   r	   r   zAsyncIterator[AddableDict])(r   r   r   r   r   r[  r]  r^  r[   r_  ra  r   rc  r'   rf  rq  r   rt  r   rx  r}  rP   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r   r6   r<   r9   rX  rX    s   $GG3-&+t+3$&NM&9 +/. ")3( 	 S  	    
  $	
K
 "
 	

 
 

 
2 '" #. (#  $:  
2  $

 "'

 

 
 
 

6 - - 4 4	>	 =A	 ! :	
 
" BF	 ! ?	
 
	$		:	" =A
-
 &
 	

 :
 :
 
;
6 =AK-K &K 	K
 :K :K 
>Kd =A%G-%G &%G "	%G
 :%G 
%GZ BF
-
 &
 	

 :
 ?
 
;
6 BFS-S &S 	S
 :S ?S 
CSt BF'G-'G &'G "	'G
 ?'G 
'GX =A-Q-Q :-Q 
	-Qd BF<< ?< 
	<| 7	$&"?&	&&  ,0) ) 	
 
B ,0) ) 	
 
$r<   rX  )`r   
__future__r   r  builtinsr   loggingr  abcr   collections.abcr   r   r   pathlibr   typingr	   r
   r   r   r   r   langchain_core._apir   langchain_core.agentsr   r   r   langchain_core.callbacksr   r   r   r   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.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.llmr.   langchain.utilities.asyncior/   	getLoggerr   r3  r1   r   r   r   r   r   r   r   r  rM  r  rs  rX  r6   r<   r9   <module>r     s   K "       = =    * E E  < < / : 5 A 8 L L 6 ) 8 ; ; " @ A 2 . ' ) 7			8	$gI gTR9 Rj3({K/G)HI 3U4,k9:;*j) jZr3 rj %
P
0 P

P
f %
a
! a

a
H	H . eKi?@A-)AAB vE vr<   