o
    JjgF@                     @  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   W/var/www/html/zoom/venv/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%   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.0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)excluded_colors)r   r%   rC   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)rM   rO   rP   rN   rJ   rK   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)return_only_outputs)r"   )r   r%   prep_outputsr&   r#   r   r"   r   )r/   rS   rU   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stepsr_   intermediate_step)#rJ   rK   r.   r   	configurer'   r%   verboser   r    on_chain_startr   r&   r"   r!   _should_continuerM   rN   _iter_next_steprD   rI   rL   appendr$   
isinstancer   r   r_   r   _consume_next_steprR   _process_next_step_outputBaseExceptionon_chain_error_stop	r/   callback_managerrU   next_step_seqchunk	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=   Nr]   r`   rb   )'rJ   rK   r.   r   rc   r'   r%   rd   r   r    re   r   r&   r"   r!   r   max_execution_timerf   rM   rN   _aiter_next_steprD   rI   rL   rh   r$   ri   r   r   r_   r   rj   rR   _aprocess_next_step_outputTimeoutErrorasyncio_astoprl   rm   ro   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rU   +Updated intermediate_steps with step outputrQ   r   Nrb   )rJ   rK   ri   r   _returnrL   extendlenr%   _get_tool_returnr   r/   r   rU   next_step_actiontool_returnr0   r0   r1   rk   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 logicr   Nr   rQ   r   r   )rJ   rK   ri   r   _areturnrL   r   r   r%   r   r   r   r0   r0   r1   r{   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 conditionr   )	rJ   warningr%   _action_agentreturn_stopped_responseearly_stopping_methodrL   r&   r   r/   rU   rt   r0   r0   r1   rn   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   r   N)	rJ   r   r%   r   r   r   rL   r&   r   r   r0   r0   r1   r~   }  s   
zAgentExecutorIterator._astoprt   r   c                 C  s4   | j j|| j|d}|j|d< || | ||S )z:
        Return the final output of the iterator.
        r   r_   )r%   r   rL   r_   on_chain_endrZ   r/   rt   rU   returned_outputr0   r0   r1   r     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.
        r   Nr_   )r%   r   rL   r_   r   rZ   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   )rS   rT   rU   rV   r5   r   )r/   r[   r5   r\   )r5   rx   )r   r   rU   r   r5   r   )r   r   rU   r   r5   r   )rU   r   r5   r   )rU   r   r5   r   )rt   r   rU   r   r5   r   )rt   r   rU   r   r5   r   )__name__
__module____qualname____doc__r2   __annotations__propertyr&   setterr%   rD   rI   r.   rR   rZ   rw   r   rk   r{   rn   r~   r   r   r0   r0   r0   r1   r   .   sT   
 ,





>
L



r   )0
__future__r   r}   loggingrO   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   langchain.schemar   langchain.utilities.asyncior   langchain.agents.agentr   r   	getLoggerr   rJ   r   r0   r0   r0   r1   <module>   s&    ,
