o
    h0                     @  sr  d dl mZ d dlZd dlZd dlmZ d dlmZmZ d dl	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mZmZm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$ ddl%m&Z& ddl'm(Z( ddl)m*Z*m+Z+ e
rddlmZ dd	lmZ ddl,m-Z-m.Z. edZ/eG dd dej0Z1eG dd de1Z2eG dd de1Z3dS )    )annotationsN)AsyncIterator)	dataclassfield)TYPE_CHECKINGAnycast)TypeVar   )QueueCompleteSentinel)Agent)AgentOutputSchemaBase)AgentsExceptionInputGuardrailTripwireTriggeredMaxTurnsExceededRunErrorDetails)InputGuardrailResultOutputGuardrailResult)ItemHelpersModelResponseRunItemTResponseInputItem)logger)RunContextWrapper)StreamEvent)Trace)pretty_print_result!pretty_print_run_result_streaming)ToolInputGuardrailResultToolOutputGuardrailResultTc                   @  s   e Zd ZU ded< 	 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ejd&ddZd'd(ddZd)d d!Z	ed*d#d$Z
d%S )+RunResultBasezstr | list[TResponseInputItem]inputzlist[RunItem]	new_itemszlist[ModelResponse]raw_responsesr   final_outputzlist[InputGuardrailResult]input_guardrail_resultszlist[OutputGuardrailResult]output_guardrail_resultszlist[ToolInputGuardrailResult]tool_input_guardrail_resultszlist[ToolOutputGuardrailResult]tool_output_guardrail_resultszRunContextWrapper[Any]context_wrapperreturn
Agent[Any]c                 C  s   dS )The last agent that was run.N selfr.   r.   N/var/www/html/openai_agents/venv/lib/python3.10/site-packages/agents/result.py
last_agentH   s    zRunResultBase.last_agentFclstype[T]raise_if_incorrect_typeboolr    c                 C  s,   |rt | j|std|j tt| jS )a  A convenience method to cast the final output to a specific type. By default, the cast
        is only for the typechecker. If you set `raise_if_incorrect_type` to True, we'll raise a
        TypeError if the final output is not of the given type.

        Args:
            cls: The type to cast the final output to.
            raise_if_incorrect_type: If True, we'll raise a TypeError if the final output is not of
                the given type.

        Returns:
            The final output casted to the given type.
        zFinal output is not of type )
isinstancer%   	TypeError__name__r   r    )r0   r3   r5   r.   r.   r1   final_output_asM   s   zRunResultBase.final_output_aslist[TResponseInputItem]c                 C  s$   t | j}dd | jD }|| S )zVCreates a new input list, merging the original input with all the new items generated.c                 S  s   g | ]}|  qS r.   )to_input_item).0itemr.   r.   r1   
<listcomp>b   s    z/RunResultBase.to_input_list.<locals>.<listcomp>)r   input_to_new_input_listr"   r#   )r0   original_itemsr#   r.   r.   r1   to_input_list_   s   zRunResultBase.to_input_list
str | Nonec                 C  s   | j sdS | j d jS )zEConvenience method to get the response ID of the last model response.N)r$   response_idr/   r.   r.   r1   last_response_idf   s   zRunResultBase.last_response_idNr+   r,   )F)r3   r4   r5   r6   r+   r    )r+   r;   )r+   rC   )r9   
__module____qualname____annotations__propertyabcabstractmethodr2   r:   rB   rF   r.   r.   r.   r1   r!   '   s4   
 
r!   c                   @  s.   e Zd ZU ded< ed
ddZdddZd	S )	RunResultr,   _last_agentr+   c                 C     | j S )r-   )rO   r/   r.   r.   r1   r2   s   s   zRunResult.last_agentstrc                 C     t | S N)r   r/   r.   r.   r1   __str__x      zRunResult.__str__NrG   r+   rQ   )r9   rH   rI   rJ   rK   r2   rT   r.   r.   r.   r1   rN   o   s
   
 rN   c                   @  s8  e Zd ZU dZded< 	 ded< 	 ded< 	 ded< 	 ed	d
Zded< ed	d
Zded< d	Zded< 	 ee	j
d	dZded< ee	j
d	dZded< edd	dZded< edd	dZded< edd	dZded< edd	dZded< ed4dd Zd5d"d#Zd6d%d&Zd7d(d)Zd*d+ Zd,d- Zd8d/d0Zd9d2d3ZdS ):RunResultStreamingaJ  The result of an agent run in streaming mode. You can use the `stream_events` method to
    receive semantic events as they are generated.

    The streaming method will raise:
    - A MaxTurnsExceeded exception if the agent exceeds the max_turns limit.
    - A GuardrailTripwireTriggered exception if a guardrail is tripped.
    r,   current_agentintcurrent_turn	max_turnsr   r%   F)reprzAgentOutputSchemaBase | None_current_agent_output_schemazTrace | Nonetracer6   is_complete)default_factoryr\   z2asyncio.Queue[StreamEvent | QueueCompleteSentinel]_event_queuez#asyncio.Queue[InputGuardrailResult]_input_guardrail_queueN)defaultr\   asyncio.Task[Any] | None_run_impl_task_input_guardrails_task_output_guardrails_taskzException | None_stored_exceptionr+   c                 C  rP   )zThe last agent that was run. Updates as the agent run progresses, so the true last agent
        is only available after the agent run is complete.
        )rX   r/   r.   r.   r1   r2      s   zRunResultStreaming.last_agentNonec                 C  sR   |    d| _| j s| j  | j r| j s'| j  | j rdS dS )zaCancels the streaming run, stopping all background tasks and marking the run as
        complete.TN)_cleanup_tasksr_   ra   empty
get_nowaitrb   r/   r.   r.   r1   cancel   s   




zRunResultStreaming.cancelAsyncIterator[StreamEvent]c              	   C s   z_	 |    | jrtd d| _n?| jr| j rn6z
| j I dH }W n
 tj	y0   Y n"w t
|trI| | jI dH  | j  |    n	|V  | j  qW | | jI dH  |   n| | jI dH  |   w | jru| jdS )a  Stream deltas for new items as they are generated. We're using the types from the
        OpenAI Responses API, so these are semantic events: each event has a `type` field that
        describes the type of the event, along with the data for that event.

        This will raise:
        - A MaxTurnsExceeded exception if the agent exceeds the max_turns limit.
        - A GuardrailTripwireTriggered exception if a guardrail is tripped.
        Tz Breaking due to stored exceptionN)_check_errorsrh   r   debugr_   ra   rk   getasyncioCancelledErrorr7   r   _await_task_safelyrf   	task_donere   rj   )r0   r>   r.   r.   r1   stream_events   s>   	



 

z RunResultStreaming.stream_eventsr   c              	   C  s$   t | j| j| j| j| j| j| jdS )zRReturn a `RunErrorDetails` object considering the current attributes of the class.)r"   r#   r$   r2   r*   r&   r'   )r   r"   r#   r$   rX   r*   r&   r'   r/   r.   r.   r1   _create_error_details   s   z(RunResultStreaming._create_error_detailsc                 C  sd  | j | jkrtd| j d}|  |_|| _| j s6| j }|j	j
r1t|}|  |_|| _| j r| jr\| j r\| j }|r\t|tr\t|trY|jd u rY|  |_|| _| jr| j r| j }|rt|trt|tr|jd u r|  |_|| _| jr| j r| j }|rt|trt|tr|jd u r|  |_|| _d S d S d S d S d S )NzMax turns (z
) exceeded)rZ   r[   r   rw   run_datarh   rb   rk   rl   outputtripwire_triggeredr   re   done	exceptionr7   	Exceptionr   rf   rg   )r0   max_turns_excguardrail_resulttripwire_excrun_impl_excin_guard_excout_guard_excr.   r.   r1   ro      s>   











z RunResultStreaming._check_errorsc                 C  sZ   | j r| j  s| j   | jr| j s| j  | jr)| j s+| j  d S d S d S rS   )re   r{   rm   rf   rg   r/   r.   r.   r1   rj     s   

z!RunResultStreaming._cleanup_tasksrQ   c                 C  rR   rS   )r   r/   r.   r.   r1   rT   %  rU   zRunResultStreaming.__str__taskc                   sP   |r$|  s&z|I dH  W dS  tjy   Y dS  ty#   Y dS w dS dS )zAwait a task if present, ignoring cancellation and storing exceptions elsewhere.

        This ensures we do not lose late guardrail exceptions while not surfacing
        CancelledError to callers of stream_events.
        N)r{   rr   rs   r}   )r0   r   r.   r.   r1   rt   (  s   z%RunResultStreaming._await_task_safelyrG   )r+   ri   )r+   rn   )r+   r   rV   )r   rd   r+   ri   )r9   rH   rI   __doc__rJ   r   r]   r^   r_   rr   Queuera   rb   re   rf   rg   rh   rK   r2   rm   rv   rw   ro   rj   rT   rt   r.   r.   r.   r1   rW   |   sB   
 


1$

rW   )4
__future__r   rL   rr   collections.abcr   dataclassesr   r   typingr   r   r   typing_extensionsr	   	_run_implr   agentr   agent_outputr   
exceptionsr   r   r   r   	guardrailr   r   itemsr   r   r   r   r   run_contextr   rv   r   tracingr   util._pretty_printr   r   tool_guardrailsr   r   r    ABCr!   rN   rW   r.   r.   r.   r1   <module>   s:    G