
    .Ui0                       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
rddlmZ dd	lmZ ddl,m-Z-m.Z.  ed      Z/e G d dej`                               Z1e G d de1             Z2e G d de1             Z3y)    )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                      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              ZdddZddZ	edd       Z
y)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_wrapperc                     y)The last agent that was run.N selfs    i/home/jay/workspace/tools/ai-image-gen/jaaz-app/server/venv/lib/python3.12/site-packages/agents/result.py
last_agentzRunResultBase.last_agentH   s        c                    |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!   )r1   clsraise_if_incorrect_types      r2   final_output_aszRunResultBase.final_output_asM   s@     #:d6G6G+M:3<<.IJJAt(())r4   c                    t        j                  | j                        }| j                  D cg c]  }|j	                          }}||z   S c c}w )zVCreates a new input list, merging the original input with all the new items generated.)r   input_to_new_input_listr$   r%   to_input_item)r1   original_itemsitemr%   s       r2   to_input_listzRunResultBase.to_input_list_   sJ    3>3V3VW[WaWa3b6:nnEdT'')E	E	)) Fs   Ac                N    | j                   sy| j                   d   j                  S )zEConvenience method to get the response ID of the last model response.N)r&   response_idr0   s    r2   last_response_idzRunResultBase.last_response_idf   s'     !!!!"%111r4   Nreturn
Agent[Any])F)r9   ztype[T]r:   boolrG   r!   )rG   zlist[TResponseInputItem])rG   z
str | None)r8   
__module____qualname____annotations__propertyabcabstractmethodr3   r;   rA   rE   r/   r4   r2   r#   r#   '   s    ))  '&L'77399>"@@N#BBO++0+  +*$* 2 2r4   r#   c                  2    e Zd ZU ded<   edd       ZddZy)	RunResultrH   _last_agentc                    | j                   S )r.   )rR   r0   s    r2   r3   zRunResult.last_agents   s     r4   c                    t        |       S N)r   r0   s    r2   __str__zRunResult.__str__x   s    "4((r4   NrF   rG   str)r8   rJ   rK   rL   rM   r3   rV   r/   r4   r2   rQ   rQ   o   s       )r4   rQ   c                     e Zd ZU dZded<   	 ded<   	 ded<   	 ded<   	  ed	
      Zded<    ed	
      Zded<   d	Zded<   	  ee	j                  d	      Zded<    ee	j                  d	      Zded<    edd	      Zded<    edd	      Zded<    edd	      Zded<    edd	      Zded<   ed&d       Zd'dZd(d Zd)d!Zd" Zd# Zd*d$Zd+d%Zy),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.
    rH   current_agentintcurrent_turn	max_turnsr   r'   F)reprzAgentOutputSchemaBase | None_current_agent_output_schemazTrace | NonetracerI   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_exceptionc                    | j                   S )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.
        )r[   r0   s    r2   r3   zRunResultStreaming.last_agent   s    
 !!!r4   c                p   | j                          d| _        | j                  j                         s5| j                  j	                          | j                  j                         s5| j
                  j                         s6| j
                  j	                          | j
                  j                         s5yy)zaCancels the streaming run, stopping all background tasks and marking the run as
        complete.TN)_cleanup_tasksrb   rd   empty
get_nowaitre   r0   s    r2   cancelzRunResultStreaming.cancel   s     	 ##))+((* ##))+--335''224 --335r4   c               Z  K   	 	 | j                          | j                  rt        j                  d       d| _        n| j                  r| j
                  j                         rn	 | j
                  j                          d{   }t        |t              rN| j                  | j                         d{    | j
                  j                          | j                          n!| | j
                  j                          | j                  | j                         d{    | j!                          | j                  r| j                  y7 # t        j                  $ r Y cw xY w7 7 J# | j                  | j                         d{  7   | j!                          w xY ww)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_errorsrk   r   debugrb   rd   ro   getasyncioCancelledErrorr6   r   _await_task_safelyri   	task_donerh   rn   )r1   r@   s     r2   stream_eventsz RunResultStreaming.stream_events   sn    #	"""$))LL!CD'+D$##(9(9(?(?(A!%!2!2!6!6!88D d$9: 11$2M2MNNN%%//1 &&(
!!++-9 @ ))$*=*=>>>!!!((( "3 9--  O ?$))$*=*=>>>!s~   F+A!E2 &E EE .E2 6E.7AE2 F+%E0&-F+E E+(E2 *E++E2 0F+2F(FF((F+c           	         t        | j                  | j                  | j                  | j                  | j
                  | j                  | j                        S )zRReturn a `RunErrorDetails` object considering the current attributes of the class.)r$   r%   r&   r3   r,   r(   r)   )r   r$   r%   r&   r[   r,   r(   r)   r0   s    r2   _create_error_detailsz(RunResultStreaming._create_error_details   sJ    **nn,,)) 00$($@$@%)%B%B
 	
r4   c                   | j                   | j                  kD  r5t        d| j                   d      }| j                         |_        || _        | j                  j                         sr| j                  j                         }|j                  j                  r't        |      }| j                         |_        || _        | j                  j                         sr| j                  r~| j                  j                         rd| j                  j                         }|rHt        |t               r8t        |t"              r!|j                  | j                         |_        || _        | j$                  r~| j$                  j                         rd| j$                  j                         }|rHt        |t               r8t        |t"              r!|j                  | j                         |_        || _        | j&                  r| j&                  j                         rg| j&                  j                         }|rJt        |t               r9t        |t"              r!|j                  | j                         |_        || _        y y y y y )NzMax turns (z
) exceeded)r]   r^   r   r|   run_datark   re   ro   rp   outputtripwire_triggeredr   rh   done	exceptionr6   	Exceptionr   ri   rj   )r1   max_turns_excguardrail_resulttripwire_excrun_impl_excin_guard_excout_guard_excs          r2   rs   z RunResultStreaming._check_errors   s    t~~-,{4>>:J*-UVM%)%?%?%AM"%2D" --335#::EEG&&99>?OP(,(B(B(D%)5& --335 4#6#6#;#;#=..88:L
< ClO<AVAVA^,0,F,F,HL))5&&&4+F+F+K+K+M66@@BL
< ClO<AVAVA^,0,F,F,HL))5&''D,H,H,M,M,O 88BBDMM9!Em_=-BXBXB`-1-G-G-IM*)6& "F} -P'r4   c                   | j                   r4| j                   j                         s| j                   j                          | j                  r4| j                  j                         s| j                  j                          | j                  r6| j                  j                         s| j                  j                          y y y rU   )rh   r   rq   ri   rj   r0   s    r2   rn   z!RunResultStreaming._cleanup_tasks  s    t':':'?'?'A&&(&&t/J/J/O/O/Q''..0''0L0L0Q0Q0S((//1 1T'r4   c                    t        |       S rU   )r   r0   s    r2   rV   zRunResultStreaming.__str__%  s    066r4   c                   K   |r|j                         s	 | d{    yyy7 # t        j                  $ r Y yt        $ r Y yw xY ww)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   rv   rw   r   )r1   tasks     r2   rx   z%RunResultStreaming._await_task_safely(  sK      		

 $4))  s;   A% #% A% AAAAAArF   )rG   None)rG   zAsyncIterator[StreamEvent])rG   r   rW   )r   rg   rG   r   )r8   rJ   rK   __doc__rL   r   r`   ra   rb   rv   Queuerd   re   rh   ri   rj   rk   rM   r3   rq   rz   r|   rs   rn   rV   rx   r/   r4   r2   rZ   rZ   |   s     ,"N<[AFEAR ">RU+E<+K1 HMEHLD  CHEC? 
 05T/NN,N7<TPU7V4V8=dQV8W5W*/5*I'I" "
5/)b

"7H27r4   rZ   )4
__future__r   rN   rv   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   rz   r   tracingr   util._pretty_printr   r   tool_guardrailsr   r    r!   ABCr#   rQ   rZ   r/   r4   r2   <module>r      s    " 
  ) ( + + % ,  /  C J J  * & 
 0TCL D2CGG D2 D2N 	) 	) 	) y y yr4   