U
    hF@                     @  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rd 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                   @  s  e Zd ZU dZdMdddddddddddd	d
dddd	d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ddddZejdddddZedddd Z	e	jddd!d"d Z	ed#dd$d%Z
eddd&d'Zddd(d)Zddd*d+Zd,d-d.d/d0d1Zd2d3d4d5d6Zd7dd8d9Zd:d;d.d<d=d>Zd:d?d.d<d@dAZd;d.dBdCdDZd?d.dBdEdFZdGd;d.dHdIdJZdGd?d.dHdKdLZdS )NAgentExecutorIteratorzIterator for AgentExecutor.NF)tagsmetadatarun_namerun_idinclude_run_infoyield_actionsr   r   r   zOptional[list[str]]zOptional[Dict[str, Any]]zOptional[str]zOptional[UUID]bool)	agent_executorinputs	callbacksr   r    r!   r"   r#   r$   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$    r,   C/tmp/pip-unpacked-wheel-bo69hh5q/langchain/agents/agent_iterator.py__init__1   s    !zAgentExecutorIterator.__init__zDict[str, str]_inputsr(   r   r    r!   r"   r#   r$   )returnc                 C  s   | j S )z The inputs to the AgentExecutor.)r/   r+   r,   r,   r-   r'   f   s    zAgentExecutorIterator.inputsNone)r'   r0   c                 C  s   | j || _d S N)r&   Zprep_inputsr/   )r+   r'   r,   r,   r-   r'   k   s    c                 C  s   | j S )z"The AgentExecutor to iterate over.)r)   r1   r,   r,   r-   r&   o   s    z$AgentExecutorIterator.agent_executor)r&   r0   c                 C  s   || _ | j| _d S r3   )r)   r'   )r+   r&   r,   r,   r-   r&   t   s    z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 r,   name.0Ztoolr,   r,   r-   
<dictcomp>}   s      z:AgentExecutorIterator.name_to_tool_map.<locals>.<dictcomp>)r&   toolsr1   r,   r,   r-   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 r,   r4   r6   r,   r,   r-   
<listcomp>   s     z7AgentExecutorIterator.color_mapping.<locals>.<listcomp>ZgreenZred)Zexcluded_colors)r   r&   r9   r1   r,   r,   r-   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_timer1   r,   r,   r-   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)r@   rB   rC   rA   r=   r>   r1   r,   r,   r-   update_iterations   s
    z'AgentExecutorIterator.update_iterationszDict[str, Any]zBUnion[CallbackManagerForChainRun, AsyncCallbackManagerForChainRun]r   )outputsrun_managerr0   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+   rF   rG   Zprepared_outputsr,   r,   r-   make_final_outputs   s      z(AgentExecutorIterator.make_final_outputsz'AgentExecutorIterator'zIterator[AddableDict])r+   r0   c           	   
   c  sn  t d |   t| j| jj| jj| j| jj| j	| jj	}|j
t| j| j| j| jd}z| j| j| jr*g }| j| j| j| j| j|D ]N}|| | jrt|trt|g|jdV  qt|trt|g|jdV  q| j|}|   | ||}d|k}| jr|r|V  |r^W d S q^W n0 t k
r\ } z|!|  W 5 d }~X Y nX | "|V  d S )Nz"Initialising AgentExecutorIteratorr4   actionsmessagesZstepsrK   intermediate_step)#r=   r>   r*   r   	configurer(   r&   verboser   r    on_chain_startr   r'   r"   r!   _should_continuer@   rA   Z_iter_next_stepr:   r<   r?   appendr$   
isinstancer   r   rK   r   _consume_next_steprE   _process_next_step_outputBaseExceptionon_chain_error_stop	r+   Zcallback_managerrG   Znext_step_seqchunkZ	next_stepoutputis_finaler,   r,   r-   __iter__   s`    
	 



zAgentExecutorIterator.__iter__z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 }zt| jj4 I dH  | j| j| jrhg }| j| j| j| j| j|2 zV3 dH W }|| | jrt|trt|g|jdV  qt|trt|g|jdV  q6 | j|}|    | !||I dH }d|k}| jrF|rL|V  |r|W 5 Q I dH R  W dS q|W 5 Q I dH R X W nd t"t#j"fk
r   | $|I dH V  Y dS  t%k
r } z|&|I dH   W 5 d}~X Y nX | $|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)r4   NrI   rL   rM   )'r=   r>   r*   r   rN   r(   r&   rO   r   r    rP   r   r'   r"   r!   r   Zmax_execution_timerQ   r@   rA   Z_aiter_next_stepr:   r<   r?   rR   r$   rS   r   r   rK   r   rT   rE   _aprocess_next_step_outputTimeoutErrorasyncio_astoprV   rW   rY   r,   r,   r-   	__aiter__   sz    
	 

 

  
,zAgentExecutorIterator.__aiter__z1Union[AgentFinish, List[Tuple[AgentAction, str]]]r   )next_step_outputrG   r0   c                 C  s   t d t|tr,t d | j||dS | j| t d t|dkrx|d }| j	|}|dk	rx| 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rG   +Updated intermediate_steps with step outputrD   r   NrM   )r=   r>   rS   r   _returnr?   extendlenr&   _get_tool_returnr   r+   rd   rG   Znext_step_actionZtool_returnr,   r,   r-   rU   8  s    	


z/AgentExecutorIterator._process_next_step_outputr   c                   s   t d t|tr2t d | j||dI dH S | j| t d t|dkr|d }| j	|}|dk	r| 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 logicre   Nrf   rD   r   rg   )r=   r>   rS   r   _areturnr?   ri   rj   r&   rk   r   rl   r,   r,   r-   r_   T  s    	


z0AgentExecutorIterator._aprocess_next_step_output)rG   r0   c                 C  s4   t d | jjj| jj| jf| j}| j||dS )zb
        Stop the iterator and raise a StopIteration exception with the stopped response.
        ;Stopping agent prematurely due to triggering stop conditionre   )	r=   warningr&   _action_agentreturn_stopped_responseearly_stopping_methodr?   r'   rh   r+   rG   r[   r,   r,   r-   rX   p  s    
zAgentExecutorIterator._stopc                   s:   t d | jjj| jj| jf| j}| j||dI dH S )zu
        Stop the async iterator and raise a StopAsyncIteration exception with
        the stopped response.
        rn   re   N)	r=   ro   r&   rp   rq   rr   r?   r'   rm   rs   r,   r,   r-   rb   }  s    
zAgentExecutorIterator._astopr   )r[   rG   r0   c                 C  s4   | j j|| j|d}|j|d< || | ||S )z:
        Return the final output of the iterator.
        re   rK   )r&   rh   r?   rK   on_chain_endrH   r+   r[   rG   Zreturned_outputr,   r,   r-   rh     s      

zAgentExecutorIterator._returnc                   s@   | j j|| j|dI dH }|j|d< ||I dH  | ||S )z@
        Return the final output of the async iterator.
        re   NrK   )r&   rm   r?   rK   rt   rH   ru   r,   r,   r-   rm     s      
zAgentExecutorIterator._areturn)N)__name__
__module____qualname____doc__r.   __annotations__propertyr'   setterr&   r:   r<   r*   rE   rH   r^   rc   rU   r_   rX   rb   rh   rm   r,   r,   r,   r-   r   .   sR   
 ",
>Lr   )0
__future__r   ra   loggingrB   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   	getLoggerrv   r=   r   r,   r,   r,   r-   <module>   s$   ,
