o
    `+ iSA                     @  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 d dl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	rxd dl'm(Z(m)Z) e*e+Z,G dd dZ-dS )    )annotationsN)AsyncIteratorIterator)TYPE_CHECKINGAnyOptional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	dKddddddddLd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dMddZejdNddZedOdd Z	e	jdPd!d Z	edQd#d$Z
edMd%d&ZdRd'd(ZdRd)d*ZdSd0d1ZdTd4d5ZdUd7d8ZdVd<d=ZdWd?d@ZdXdAdBZdYdCdDZdZdGdHZd[dIdJ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!    r-   k/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/langchain/agents/agent_iterator.py__init__-   s   !zAgentExecutorIterator.__init__dict[str, str]_inputsreturnc                 C     | j S )z The inputs to the AgentExecutor.)r1   r,   r-   r-   r.   r#   b      zAgentExecutorIterator.inputsNonec                 C  s   | j || _d S N)r"   Zprep_inputsr1   )r,   r#   r-   r-   r.   r#   g   s   c                 C  r3   )z"The AgentExecutor to iterate over.)r*   r4   r-   r-   r.   r"   k   r5   z$AgentExecutorIterator.agent_executorc                 C  s   || _ | j| _d S r7   )r*   r#   )r,   r"   r-   r-   r.   r"   p   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 r-   name.0Ztoolr-   r-   r.   
<dictcomp>y   s    z:AgentExecutorIterator.name_to_tool_map.<locals>.<dictcomp>)r"   toolsr4   r-   r-   r.   name_to_tool_mapv   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-   r9   r;   r-   r-   r.   
<listcomp>   s    z7AgentExecutorIterator.color_mapping.<locals>.<listcomp>greenred)Zexcluded_colors)r   r"   r>   r4   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_timer4   r-   r-   r.   r+      s
   
zAgentExecutorIterator.resetc                 C  s4   |  j d7  _ t | j | _td| j | j dS )zQ
        Increment the number of iterations and update the time elapsed.
           z$Agent Iterations: %s (%.2fs elapsed)N)rG   rI   rJ   rH   rD   rE   r4   r-   r-   r.   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,   rM   rO   Zprepared_outputsr-   r-   r.   make_final_outputs   s   z(AgentExecutorIterator.make_final_outputsr,   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 AgentExecutorIteratorr9   actionsmessagesZstepsrU   intermediate_step)#rD   rE   r+   r   	configurer$   r"   verboser   r   on_chain_startr   r#   r   r   _should_continuerG   rH   Z_iter_next_stepr?   rC   rF   appendr!   
isinstancer
   r   rU   r   _consume_next_steprL   _process_next_step_outputBaseExceptionon_chain_error_stop	r,   Zcallback_managerrO   Znext_step_seqchunkZ	next_stepoutputis_finaler-   r-   r.   __iter__   sr   
	



%
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)r9   NrS   rV   rW   )'rD   rE   r+   r   rX   r$   r"   rY   r   r   rZ   r   r#   r   r   r   Zmax_execution_timer[   rG   rH   Z_aiter_next_stepr?   rC   rF   r\   r!   r]   r
   r   rU   r   r^   rL   _aprocess_next_step_outputTimeoutErrorasyncio_astopr`   ra   rc   r-   r-   r.   	__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rO   +Updated intermediate_steps with step outputrK   r   NrW   )rD   rE   r]   r   _returnrF   extendlenr"   _get_tool_returnr   r,   ro   rO   Znext_step_actionZtool_returnr-   r-   r.   r_   =  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 logicrq   Nrr   rK   r   rs   )rD   rE   r]   r   _areturnrF   ru   rv   r"   rw   r   rx   r-   r-   r.   rj   Y  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 conditionrq   )	rD   warningr"   _action_agentreturn_stopped_responseearly_stopping_methodrF   r#   rt   r,   rO   re   r-   r-   r.   rb   u  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.
        rz   rq   N)	rD   r{   r"   r|   r}   r~   rF   r#   ry   r   r-   r-   r.   rm     s   
zAgentExecutorIterator._astopre   r   c                 C  s4   | j j|| j|d}|j|d< || | ||S )z:
        Return the final output of the iterator.
        rq   rU   )r"   rt   rF   rU   on_chain_endrQ   r,   re   rO   Zreturned_outputr-   r-   r.   rt     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.
        rq   NrU   )r"   ry   rF   rU   r   rQ   r   r-   r-   r.   ry     s   
zAgentExecutorIterator._areturnr7   )r"   r   r#   r   r$   r   r   r%   r   r&   r   r'   r   r(   r    r)   r!   r)   )r2   r0   )r#   r   r2   r6   )r2   r   )r"   r   r2   r6   )r2   r8   )r2   r6   )rM   rN   rO   rP   r2   r   )r,   r   r2   rR   )r2   ri   )ro   rp   rO   r   r2   r   )ro   rp   rO   r   r2   r   )rO   r   r2   r   )rO   r   r2   r   )re   r   rO   r   r2   r   )re   r   rO   r   r2   r   )__name__
__module____qualname____doc__r/   __annotations__propertyr#   setterr"   r?   rC   r+   rL   rQ   rh   rn   r_   rj   rb   rm   rt   ry   r-   r-   r-   r.   r   *   sT   
 ,




?
P



r   ).
__future__r   rl   loggingrI   collections.abcr   r   typingr   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   rD   r   r-   r-   r-   r.   <module>   s(    
