a
    ~gF@                     @  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,   d/var/www/html/emsaiapi.evdpl.com/venv/lib/python3.9/site-packages/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.0toolr,   r,   r-   
<dictcomp>}       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>   r:   z7AgentExecutorIterator.color_mapping.<locals>.<listcomp>greenred)excluded_colors)r   r&   r;   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)rE   rG   rH   rF   rB   rC   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+   rK   rL   Zprepared_outputsr,   r,   r-   make_final_outputs   s    z(AgentExecutorIterator.make_final_outputsz'AgentExecutorIterator'zIterator[AddableDict])r+   r0   c           	   
   c  sp  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|v}| jr|r|V  |r^W d S q^W n2 t y^ } z|!|  W Y d }~n
d }~0 0 | "|V  d S )Nz"Initialising AgentExecutorIteratorr4   actionsmessagesstepsrP   intermediate_step)#rB   rC   r*   r   	configurer(   r&   verboser   r    on_chain_startr   r'   r"   r!   _should_continuerE   rF   _iter_next_stepr<   rA   rD   appendr$   
isinstancer   r   rP   r   _consume_next_steprJ   _process_next_step_outputBaseExceptionon_chain_error_stop	r+   callback_managerrL   Znext_step_seqchunkZ	next_stepoutputZ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 }z8t| jj4 I dH  | j| j| jrlg }| 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|v}| jrH|rN|V  |r~W d  I dH  W dS q~W d  I dH  q1 I dH s0    Y  W nd t"t#j"fy   | $|I dH V  Y dS  t%y  } z|&|I dH   W Y d}~n
d}~0 0 | $|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   NrN   rQ   rS   )'rB   rC   r*   r   rT   r(   r&   rU   r   r    rV   r   r'   r"   r!   r   max_execution_timerW   rE   rF   _aiter_next_stepr<   rA   rD   rY   r$   rZ   r   r   rP   r   r[   rJ   _aprocess_next_step_outputTimeoutErrorasyncio_astopr]   r^   r`   r,   r,   r-   	__aiter__   sr    
	




LzAgentExecutorIterator.__aiter__z1Union[AgentFinish, List[Tuple[AgentAction, str]]]r   )next_step_outputrL   r0   c                 C  s   t d t|tr,t d | j||dS | j| t d t|dkrx|d }| j	|}|du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rL   +Updated intermediate_steps with step outputrI   r   NrS   )rB   rC   rZ   r   _returnrD   extendlenr&   _get_tool_returnr   r+   rm   rL   next_step_actiontool_returnr,   r,   r-   r\   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u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 logicrn   Nro   rI   r   rp   )rB   rC   rZ   r   _areturnrD   rr   rs   r&   rt   r   ru   r,   r,   r-   rh   T  s    	


z0AgentExecutorIterator._aprocess_next_step_output)rL   r0   c                 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 conditionrn   )	rB   warningr&   _action_agentreturn_stopped_responseearly_stopping_methodrD   r'   rq   r+   rL   rc   r,   r,   r-   r_   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.
        ry   rn   N)	rB   rz   r&   r{   r|   r}   rD   r'   rx   r~   r,   r,   r-   rk   }  s    
zAgentExecutorIterator._astopr   )rc   rL   r0   c                 C  s4   | j j|| j|d}|j|d< || | ||S )z:
        Return the final output of the iterator.
        rn   rP   )r&   rq   rD   rP   on_chain_endrM   r+   rc   rL   Zreturned_outputr,   r,   r-   rq     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.
        rn   NrP   )r&   rx   rD   rP   r   rM   r   r,   r,   r-   rx     s    
zAgentExecutorIterator._areturn)N)__name__
__module____qualname____doc__r.   __annotations__propertyr'   setterr&   r<   rA   r*   rJ   rM   re   rl   r\   rh   r_   rk   rq   rx   r,   r,   r,   r-   r   .   sR   
 ",
>Lr   )0
__future__r   rj   loggingrG   typingr   r   r   r   r   r   r	   r
   r   uuidr   langchain_core.agentsr   r   r   langchain_core.callbacksr   r   r   r   r   langchain_core.load.dumpr   langchain_core.outputsr   langchain_core.runnables.utilsr   langchain_core.toolsr   langchain_core.utils.inputr   Zlangchain.schemar   langchain.utilities.asyncior   langchain.agents.agentr   r   	getLoggerr   rB   r   r,   r,   r,   r-   <module>   s$   ,
