o
    ZhF@                     @  s  d dl mZ d dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
mZmZmZm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 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( erzd dl)m*Z*m+Z+ e,e-Z.G dd dZ/dS )    )annotationsN)	TYPE_CHECKINGAnyAsyncIteratorDictIteratorListOptionalTupleUnion)UUID)AgentActionAgentFinish	AgentStep)AsyncCallbackManagerAsyncCallbackManagerForChainRunCallbackManagerCallbackManagerForChainRun	Callbacks)dumpd)RunInfo)AddableDict)BaseTool)get_color_mapping)RUN_KEY)asyncio_timeout)AgentExecutorNextStepOutputc                   @  s6  e Zd ZU dZ	dLddddddddMddZded< d
ed	< ded< ded< ded< ded< ded< ded< edNddZejdOddZedPdd Z	e	jdQd!d Z	edRd#d$Z
edNd%d&ZdSd'd(ZdSd)d*ZdTd0d1ZdUd5d6ZdVd8d9ZdWd=d>ZdXd@dAZdYdBdCZdZdDdEZd[dHdIZd\dJdKZdS )]AgentExecutorIteratorzIterator for AgentExecutor.NF)tagsmetadatarun_namerun_idinclude_run_infoyield_actionsagent_executorr   inputsr   	callbacksr   r   Optional[list[str]]r    Optional[Dict[str, Any]]r!   Optional[str]r"   Optional[UUID]r#   boolr$   c          
      C  sB   || _ || _|| _|| _|| _|| _|| _|| _|	| _| 	  dS )a+  
        Initialize the AgentExecutorIterator with the given AgentExecutor,
        inputs, and optional callbacks.

        Args:
            agent_executor (AgentExecutor): The AgentExecutor to iterate over.
            inputs (Any): The inputs to the AgentExecutor.
            callbacks (Callbacks, optional): The callbacks to use during iteration.
                Defaults to None.
            tags (Optional[list[str]], optional): The tags to use during iteration.
                Defaults to None.
            metadata (Optional[Dict[str, Any]], optional): The metadata to use
                during iteration. Defaults to None.
            run_name (Optional[str], optional): The name of the run. Defaults to None.
            run_id (Optional[UUID], optional): The ID of the run. Defaults to None.
            include_run_info (bool, optional): Whether to include run info
                in the output. Defaults to False.
            yield_actions (bool, optional): Whether to yield actions as they
                are generated. Defaults to False.
        N)
_agent_executorr&   r'   r   r    r!   r"   r#   r$   reset)
selfr%   r&   r'   r   r    r!   r"   r#   r$    r0   V/var/www/html/lang_env/lib/python3.10/site-packages/langchain/agents/agent_iterator.py__init__1   s   !zAgentExecutorIterator.__init__Dict[str, str]_inputsreturnc                 C     | j S )z The inputs to the AgentExecutor.)r4   r/   r0   r0   r1   r&   f      zAgentExecutorIterator.inputsNonec                 C  s   | j || _d S N)r%   Zprep_inputsr4   )r/   r&   r0   r0   r1   r&   k   s   c                 C  r6   )z"The AgentExecutor to iterate over.)r-   r7   r0   r0   r1   r%   o   r8   z$AgentExecutorIterator.agent_executorc                 C  s   || _ | j| _d S r:   )r-   r&   )r/   r%   r0   r0   r1   r%   t   s   Dict[str, BaseTool]c                 C  s   dd | j jD S )z!A mapping of tool names to tools.c                 S  s   i | ]}|j |qS r0   name.0Ztoolr0   r0   r1   
<dictcomp>}   s    z:AgentExecutorIterator.name_to_tool_map.<locals>.<dictcomp>)r%   toolsr7   r0   r0   r1   name_to_tool_mapz   s   z&AgentExecutorIterator.name_to_tool_mapc                 C  s   t dd | jjD ddgdS )z"A mapping of tool names to colors.c                 S  s   g | ]}|j qS r0   r<   r>   r0   r0   r1   
<listcomp>   s    z7AgentExecutorIterator.color_mapping.<locals>.<listcomp>greenred)Zexcluded_colors)r   r%   rA   r7   r0   r0   r1   color_mapping   s   z#AgentExecutorIterator.color_mappingc                 C  s*   t d g | _d| _d| _t | _dS )z}
        Reset the iterator to its initial state, clearing intermediate steps,
        iterations, and time elapsed.
        z0(Re)setting AgentExecutorIterator to fresh stater   g        N)loggerdebugintermediate_steps
iterationstime_elapsedtime
start_timer7   r0   r0   r1   r.      s
   
zAgentExecutorIterator.resetc                 C  s@   |  j d7  _ t | j | _td| j  d| jdd dS )zQ
        Increment the number of iterations and update the time elapsed.
           zAgent Iterations: z (z.2fz
s elapsed)N)rJ   rL   rM   rK   rG   rH   r7   r0   r0   r1   update_iterations   s
   z'AgentExecutorIterator.update_iterationsoutputsDict[str, Any]run_managerBUnion[CallbackManagerForChainRun, AsyncCallbackManagerForChainRun]r   c                 C  s2   t | jj| j|dd}| jrt|jd|t< |S )NT)Zreturn_only_outputs)r"   )r   r%   Zprep_outputsr&   r#   r   r"   r   )r/   rP   rR   Zprepared_outputsr0   r0   r1   make_final_outputs   s   z(AgentExecutorIterator.make_final_outputsr/   'AgentExecutorIterator'Iterator[AddableDict]c           	   
   c  sn   t d |   t| j| jj| jj| j| jj| j	| jj	}|j
t| j| j| j| jd}zm| j| j| jrg }| j| j| j| j| j|D ]'}|| | jrpt|trbt|g|jdV  qIt|trpt|g|jdV  qI| j|}|   | ||}d|v}| jr|r|V  |rW d S | j| j| js9W n t y } z|!|  d }~ww | "|V  d S )Nz"Initialising AgentExecutorIteratorr<   actionsmessagesZstepsrY   intermediate_step)#rG   rH   r.   r   	configurer'   r%   verboser   r    on_chain_startr   r&   r"   r!   _should_continuerJ   rK   Z_iter_next_steprB   rF   rI   appendr$   
isinstancer   r   rY   r   _consume_next_steprO   _process_next_step_outputBaseExceptionon_chain_error_stop	r/   Zcallback_managerrR   Znext_step_seqchunkZ	next_stepoutputis_finaler0   r0   r1   __iter__   sn   
	



$
zAgentExecutorIterator.__iter__AsyncIterator[AddableDict]c           	   
   C s  t d |   t| j| jj| jj| j| jj| j	| jj	}|j
t| j| j| j| jdI dH }zt| jj4 I dH  | j| j| jrg }| j| j| j| j| j|2 z+3 dH W }|| | jrt|trtt|g|jdV  qWt|trt|g|jdV  qW6 | j|}|    | !||I dH }d|v}| jr|r|V  |r	 W d  I dH  W dS | j| j| jsGW d  I dH  n1 I dH sw   Y  W n* t"t#j"fy   | $|I dH V  Y dS  t%y } z	|&|I dH   d}~ww | $|I dH V  dS )z
        N.B. __aiter__ must be a normal method, so need to initialize async run manager
        on first __anext__ call where we can await it
        z*Initialising AgentExecutorIterator (async)r<   NrW   rZ   r[   )'rG   rH   r.   r   r\   r'   r%   r]   r   r    r^   r   r&   r"   r!   r   Zmax_execution_timer_   rJ   rK   Z_aiter_next_steprB   rF   rI   r`   r$   ra   r   r   rY   r   rb   rO   _aprocess_next_step_outputTimeoutErrorasyncio_astoprd   re   rg   r0   r0   r1   	__aiter__   s   
	





(+zAgentExecutorIterator.__aiter__next_step_output1Union[AgentFinish, List[Tuple[AgentAction, str]]]r   c                 C  s   t d t|trt d | j||dS | j| t d t|dkr<|d }| j	|}|dur<| j||dS t
|dS )	zj
        Process the output of the next step,
        handling AgentFinish and tool return cases.
        z$Processing output of Agent loop stepzBHit AgentFinish: _return -> on_chain_end -> run final output logicrR   +Updated intermediate_steps with step outputrN   r   Nr[   )rG   rH   ra   r   _returnrI   extendlenr%   _get_tool_returnr   r/   rs   rR   Znext_step_actionZtool_returnr0   r0   r1   rc   8  s   
	


z/AgentExecutorIterator._process_next_step_outputr   c                   s   t d t|trt d | j||dI dH S | j| t d t|dkrC|d }| j	|}|durC| j||dI dH S t
|dS )	zp
        Process the output of the next async step,
        handling AgentFinish and tool return cases.
        z*Processing output of async Agent loop stepzCHit AgentFinish: _areturn -> on_chain_end -> run final output logicru   Nrv   rN   r   rw   )rG   rH   ra   r   _areturnrI   ry   rz   r%   r{   r   r|   r0   r0   r1   rn   T  s   
	


z0AgentExecutorIterator._aprocess_next_step_outputc                 C  s8   t d | jjj| jj| jfi | j}| j||dS )zb
        Stop the iterator and raise a StopIteration exception with the stopped response.
        ;Stopping agent prematurely due to triggering stop conditionru   )	rG   warningr%   _action_agentreturn_stopped_responseearly_stopping_methodrI   r&   rx   r/   rR   ri   r0   r0   r1   rf   p  s   
zAgentExecutorIterator._stopc                   s@   t d | jjj| jj| jfi | j}| j||dI dH S )zu
        Stop the async iterator and raise a StopAsyncIteration exception with
        the stopped response.
        r~   ru   N)	rG   r   r%   r   r   r   rI   r&   r}   r   r0   r0   r1   rq   }  s   
zAgentExecutorIterator._astopri   r   c                 C  s4   | j j|| j|d}|j|d< || | ||S )z:
        Return the final output of the iterator.
        ru   rY   )r%   rx   rI   rY   on_chain_endrT   r/   ri   rR   Zreturned_outputr0   r0   r1   rx     s   

zAgentExecutorIterator._returnc                   sB   | j j|| j|dI dH }|j|d< ||I dH  | ||S )z@
        Return the final output of the async iterator.
        ru   NrY   )r%   r}   rI   rY   r   rT   r   r0   r0   r1   r}     s   
zAgentExecutorIterator._areturnr:   )r%   r   r&   r   r'   r   r   r(   r    r)   r!   r*   r"   r+   r#   r,   r$   r,   )r5   r3   )r&   r   r5   r9   )r5   r   )r%   r   r5   r9   )r5   r;   )r5   r9   )rP   rQ   rR   rS   r5   r   )r/   rU   r5   rV   )r5   rm   )rs   rt   rR   r   r5   r   )rs   rt   rR   r   r5   r   )rR   r   r5   r   )rR   r   r5   r   )ri   r   rR   r   r5   r   )ri   r   rR   r   r5   r   )__name__
__module____qualname____doc__r2   __annotations__propertyr&   setterr%   rB   rF   r.   rO   rT   rl   rr   rc   rn   rf   rq   rx   r}   r0   r0   r0   r1   r   .   sT   
 ,





>
L



r   )0
__future__r   rp   loggingrL   typingr   r   r   r   r   r   r	   r
   r   uuidr   Zlangchain_core.agentsr   r   r   Zlangchain_core.callbacksr   r   r   r   r   Zlangchain_core.load.dumpr   Zlangchain_core.outputsr   Zlangchain_core.runnables.utilsr   Zlangchain_core.toolsr   Zlangchain_core.utils.inputr   Zlangchain.schemar   Zlangchain.utilities.asyncior   Zlangchain.agents.agentr   r   	getLoggerr   rG   r   r0   r0   r0   r1   <module>   s&    ,
