o
    h                    @  s  U 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mZ d dl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mZmZmZm Z  dd
l!m"Z" ddl#m$Z$m%Z% ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> ddl?m@Z@mAZAmBZB ddlCmCZC ddlDmEZEmFZF ddlGmHZH ddlImJZJmKZK ddlLmMZM ddlNmOZOmPZP ddlQmRZRmSZS ddlTmUZUmVZVmWZWmXZX ddlYmZZZ ddl[m\Z\m]Z] ddl^m_Z_m`Z`maZambZbmcZc ddldmeZe ddlfmgZg ddlhmiZimjZj ddlkmlZl d Zmdand!eod"< d?d'd(Zpd@d)d*ZqdAd,d-ZreG d.d/ d/ZseG d0d1 d1eeS Zte
ete	 geles f ZueG d2d3 d3ZvG d4d5 d5eeeS ZwG d6d7 d7ZxG d8d! d!Zyey anee=Zzd9eod:< dBd=d>Z{dS )C    )annotationsN)	dataclassfield)AnyCallableGenericcastget_args)ResponseCompletedEventResponseOutputItemDoneEvent)ResponsePromptParam)NotRequired	TypedDictUnpack   )	AgentToolUseTrackerNextStepFinalOutputNextStepHandoffNextStepRunAgainQueueCompleteSentinelRunImplSingleStepResultTraceCtxManagerget_model_tracing_impl)Agent)AgentOutputSchemaAgentOutputSchemaBase)AgentsExceptionInputGuardrailTripwireTriggeredMaxTurnsExceededModelBehaviorError OutputGuardrailTripwireTriggeredRunErrorDetails	UserError)InputGuardrailInputGuardrailResultOutputGuardrailOutputGuardrailResult)HandoffHandoffInputFilterhandoff)HandoffCallItemItemHelpersModelResponseRunItemToolCallItemToolCallItemTypesTResponseInputItem)AgentHooksBaseRunHooksRunHooksBase)logger)SessionSessionInputCallback)ModelSettings)ModelModelProvider)MultiProvider)	RunResultRunResultStreaming)RunContextWrapperTContext)AgentUpdatedStreamEventRawResponsesStreamEventRunItemStreamEventStreamEvent)Tool)ToolInputGuardrailResultToolOutputGuardrailResult)Span	SpanError
agent_spanget_current_tracetrace)AgentSpanData)Usage)_coro_error_tracing)MaybeAwaitable
   AgentRunnerDEFAULT_AGENT_RUNNERrunnerAgentRunner | NonereturnNonec                 C  s   | pt  adS )p
    WARNING: this class is experimental and not part of the public API
    It should not be used directly.
    N)rR   rS   )rT    rY   K/var/www/html/openai_agents/venv/lib/python3.10/site-packages/agents/run.pyset_default_agent_runnerT   s   r[   c                   C  s   t S )rX   )rS   rY   rY   rY   rZ   get_default_agent_runner]   s   r\   boolc                  C  s   t dd} |   dv S )zYReturns the default value for trace_include_sensitive_data based on environment variable.*OPENAI_AGENTS_TRACE_INCLUDE_SENSITIVE_DATAtrue)1r_   yeson)osgetenvstriplower)valrY   rY   rZ   %_default_trace_include_sensitive_dataf   s   rh   c                   @  s"   e Zd ZU dZded< ded< dS )ModelInputDataz6Container for the data that will be sent to the model.list[TResponseInputItem]input
str | NoneinstructionsN__name__
__module____qualname____doc____annotations__rY   rY   rY   rZ   ri   l   s   
 ri   c                   @  s*   e Zd ZU dZded< ded< ded< dS )	CallModelDatazGData passed to `RunConfig.call_model_input_filter` prior to model call.ri   
model_dataAgent[TContext]agentTContext | NonecontextNrn   rY   rY   rY   rZ   rt   t   s
   
 rt   c                   @  s   e Zd ZU dZdZded< 	 eedZded< 	 dZ	ded	< 	 dZ
d
ed< 	 dZded< 	 dZded< 	 dZded< 	 eedZded< 	 dZded< 	 dZded< 	 dZded< 	 dZded< 	 dZded< 	 dZded< dS ) 	RunConfigz-Configures settings for the entire agent run.Nzstr | Model | Nonemodel)default_factoryr:   model_providerzModelSettings | Nonemodel_settingszHandoffInputFilter | Nonehandoff_input_filterz list[InputGuardrail[Any]] | Noneinput_guardrailsz!list[OutputGuardrail[Any]] | Noneoutput_guardrailsFr]   tracing_disabledtrace_include_sensitive_datazAgent workflowstrworkflow_namerl   trace_idgroup_idzdict[str, Any] | Nonetrace_metadataSessionInputCallback | Nonesession_input_callbackzCallModelInputFilter | Nonecall_model_input_filter)ro   rp   rq   rr   r{   rs   r   r;   r}   r~   r   r   r   r   rh   r   r   r   r   r   r   r   rY   rY   rY   rZ   rz      s@   
 rz   c                   @  sV   e Zd ZU dZded< 	 ded< 	 ded< 	 ded	< 	 d
ed< 	 d
ed< 	 ded< dS )
RunOptionsz&Arguments for ``AgentRunner`` methods.zNotRequired[TContext | None]ry   zNotRequired[int]	max_turnsz&NotRequired[RunHooks[TContext] | None]hookszNotRequired[RunConfig | None]
run_configzNotRequired[str | None]previous_response_idconversation_idzNotRequired[Session | None]sessionNrn   rY   rY   rY   rZ   r      s    
 r   c                	   @  sj   e Zd ZededddddddddZededddddddddZededddddfdddZdS )RunnerNry   r   r   r   r   r   r   starting_agentrv   rk   str | list[TResponseInputItem]ry   rx   r   intr   RunHooks[TContext] | Noner   RunConfig | Noner   rl   r   r   Session | NonerV   r<   c                  s(   t }
|
j|||||||||	d	I dH S )a	  
        Run a workflow starting at the given agent.

        The agent will run in a loop until a final output is generated. The loop runs like so:

          1. The agent is invoked with the given input.
          2. If there is a final output (i.e. the agent produces something of type
             `agent.output_type`), the loop terminates.
          3. If there's a handoff, we run the loop again, with the new agent.
          4. Else, we run tool calls (if any), and re-run the loop.

        In two cases, the agent may raise an exception:

          1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised.
          2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
             exception is raised.

        Note:
            Only the first agent's input guardrails are run.

        Args:
            starting_agent: The starting agent to run.
            input: The initial input to the agent. You can pass a single string for a
                user message, or a list of input items.
            context: The context to run the agent with.
            max_turns: The maximum number of turns to run the agent for. A turn is
                defined as one AI invocation (including any tool calls that might occur).
            hooks: An object that receives callbacks on various lifecycle events.
            run_config: Global settings for the entire agent run.
            previous_response_id: The ID of the previous response. If using OpenAI
                models via the Responses API, this allows you to skip passing in input
                from the previous turn.
            conversation_id: The conversation ID
                (https://platform.openai.com/docs/guides/conversation-state?api-mode=responses).
                If provided, the conversation will be used to read and write items.
                Every agent will have access to the conversation history so far,
                and its output items will be written to the conversation.
                We recommend only using this if you are exclusively using OpenAI models;
                other model providers don't write to the Conversation object,
                so you'll end up having partial conversations stored.
            session: A session for automatic conversation history management.

        Returns:
            A run result containing all the inputs, guardrail results and the output of
            the last agent. Agents may perform handoffs, so we don't know the specific
            type of the output.
        r   N)rS   runclsr   rk   ry   r   r   r   r   r   r   rT   rY   rY   rZ   r      s   >z
Runner.runc                C      t }
|
j|||||||||	d	S )a  
        Run a workflow synchronously, starting at the given agent.

        Note:
            This just wraps the `run` method, so it will not work if there's already an
            event loop (e.g. inside an async function, or in a Jupyter notebook or async
            context like FastAPI). For those cases, use the `run` method instead.

        The agent will run in a loop until a final output is generated. The loop runs:

          1. The agent is invoked with the given input.
          2. If there is a final output (i.e. the agent produces something of type
             `agent.output_type`), the loop terminates.
          3. If there's a handoff, we run the loop again, with the new agent.
          4. Else, we run tool calls (if any), and re-run the loop.

        In two cases, the agent may raise an exception:

          1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised.
          2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
             exception is raised.

        Note:
            Only the first agent's input guardrails are run.

        Args:
            starting_agent: The starting agent to run.
            input: The initial input to the agent. You can pass a single string for a
                user message, or a list of input items.
            context: The context to run the agent with.
            max_turns: The maximum number of turns to run the agent for. A turn is
                defined as one AI invocation (including any tool calls that might occur).
            hooks: An object that receives callbacks on various lifecycle events.
            run_config: Global settings for the entire agent run.
            previous_response_id: The ID of the previous response, if using OpenAI
                models via the Responses API, this allows you to skip passing in input
                from the previous turn.
            conversation_id: The ID of the stored conversation, if any.
            session: A session for automatic conversation history management.

        Returns:
            A run result containing all the inputs, guardrail results and the output of
            the last agent. Agents may perform handoffs, so we don't know the specific
            type of the output.
        r   )rS   run_syncr   rY   rY   rZ   r   4  s   <zRunner.run_syncr=   c
                 C  r   )a  
        Run a workflow starting at the given agent in streaming mode.

        The returned result object contains a method you can use to stream semantic
        events as they are generated.

        The agent will run in a loop until a final output is generated. The loop runs like so:

          1. The agent is invoked with the given input.
          2. If there is a final output (i.e. the agent produces something of type
             `agent.output_type`), the loop terminates.
          3. If there's a handoff, we run the loop again, with the new agent.
          4. Else, we run tool calls (if any), and re-run the loop.

        In two cases, the agent may raise an exception:

          1. If the max_turns is exceeded, a MaxTurnsExceeded exception is raised.
          2. If a guardrail tripwire is triggered, a GuardrailTripwireTriggered
             exception is raised.

        Note:
            Only the first agent's input guardrails are run.

        Args:
            starting_agent: The starting agent to run.
            input: The initial input to the agent. You can pass a single string for a
                user message, or a list of input items.
            context: The context to run the agent with.
            max_turns: The maximum number of turns to run the agent for. A turn is
                defined as one AI invocation (including any tool calls that might occur).
            hooks: An object that receives callbacks on various lifecycle events.
            run_config: Global settings for the entire agent run.
            previous_response_id: The ID of the previous response, if using OpenAI
                models via the Responses API, this allows you to skip passing in input
                from the previous turn.
            conversation_id: The ID of the stored conversation, if any.
            session: A session for automatic conversation history management.

        Returns:
            A result object that contains data about the run, as well as a method to
            stream events.
        r   )rS   run_streamedr   rY   rY   rZ   r   }  s   8zRunner.run_streamed)r   rv   rk   r   ry   rx   r   r   r   r   r   r   r   rl   r   rl   r   r   rV   r<   )r   rv   rk   r   ry   rx   r   r   r   r   r   r   r   rl   r   rl   r   r   rV   r=   )ro   rp   rq   classmethodDEFAULT_MAX_TURNSr   r   r   rY   rY   rY   rZ   r      s8    JHr   c                   @  s"  e Zd ZdZdrd
dZdrddZdsddZedtddZe	dud d!Z
e	dvd)d*Ze	dwd3d4Ze	dxd<d=Ze	dydAdBZe	dCdDdzdNdOZe	d{dPdQZe	d|dSdTZe	d}dYdZZe	d~d^d_Ze	dd`daZe	ddcddZe	ddedfZe	ddhdiZe	ddldmZe	ddpdqZdCS )rR   z~
    WARNING: this class is experimental and not part of the public API
    It should not be used directly or subclassed.
    r   rv   rk   r   kwargsUnpack[RunOptions[TContext]]rV   r<   c           !        s  | d}| dt}ttt | | d}| d}| d}| d}	| d}
|d u r4t }|}| ||
|jI d H }t	 }t
|j|j|j|j|jd d	}t|}g }g }t|d
}g }g }g }d }|}d}| |
|g I d H  zczG	 t||I d H }|d u rdd t||I d H D }t| }r| }nd}t|j||d}|jdd dd |D |j_|d7 }||krt|tdd|id td| dt !d|j d| d |dkrt"#| $||j%|j%pg  t||| j&|||||||||||	dI d H \}}n| j&|||||||||||	dI d H }d}|'|j( |j)}|j*}|+|j, |+|j- t.|j/t0r| 1|j2|j2pQg  ||j/j3|I d H }t4||||j/j3||||||d
}| |
g |j5I d H  |W W |r|j6dd W  d    S t.|j/t7rtt8t |j/j9}|j6dd d }d}nt.|j/t:r| |
g |j5I d H  n
t;dt<|j/ q~ t;y }  zt=||||||g d| _> d } ~ ww |r|j6dd w w 1 sw   Y  d S ) Nry   r   r   r   r   r   r   r   r   r   metadatadisabledr   ry   Tc                 S     g | ]}|j qS rY   
agent_name.0hrY   rY   rZ   
<listcomp>      z#AgentRunner.run.<locals>.<listcomp>r   namehandoffsoutput_typemark_as_currentc                 S  r   rY   r   r   trY   rY   rZ   r         r   Max turns exceededmessagedatazMax turns (z
) exceededzRunning agent z (turn ))rw   	all_toolsoriginal_inputgenerated_itemsr   context_wrapperr   should_run_agent_start_hookstool_use_trackerr   r   F)
rk   	new_itemsraw_responsesfinal_output_last_agentinput_guardrail_resultsoutput_guardrail_resultstool_input_guardrail_resultstool_output_guardrail_resultsr   reset_currentzUnknown next step type: rk   r   r   
last_agentr   r   r   )?getr   r   r3   r?   _validate_run_hooksrz   _prepare_input_with_sessionr   r   r   r   r   r   r   r   _copy_str_or_listr>   _save_result_to_sessionrR   _get_all_tools_get_handoffs_get_output_schemar   rI   start	span_datatoolsrO   attach_error_to_spanrH   r   r5   debugasynciogather_run_input_guardrailsr   _run_single_turnappendmodel_responser   r   extendr   r   
isinstance	next_stepr   _run_output_guardrailsr   outputr<   new_step_itemsfinishr   r   	new_agentr   r   typer"   run_data)!selfr   rk   r   ry   r   r   r   r   r   r   original_user_inputprepared_inputr   current_turnr   r   model_responsesr   r   r   r   current_spancurrent_agentr   r   handoff_namesoutput_schemaoutput_type_nameturn_resultr   resultexcrY   rY   rZ   r     sH  









  v	 zAgentRunner.runc                 K  sn   | d}| dt}| d}| d}| d}| d}	| d}
t | j|||
||||||	d	S )	Nry   r   r   r   r   r   r   )r   ry   r   r   r   r   r   )r   r   r   get_event_looprun_until_completer   )r   r   rk   r   ry   r   r   r   r   r   r   rY   rY   rZ   r     s(   





zAgentRunner.run_syncr=   c                 K  s   | d}| dt}ttt | | d}| d}| d}| d}	| d}
|d u r3t }t r8d nt|j	|j
|j|j|jd}t|}t|d	}tt|g |g d d
d|g g g g |||d}t| j|||||||||	|
d
|_|S )Nry   r   r   r   r   r   r   r   r   Fr   )rk   r   r   r   r   is_completer   r   r   r   r   r   _current_agent_output_schemarK   r   )
starting_inputstreamed_resultr   r   r   r   r   r   r   r   )r   r   r   r3   r?   r   rz   rJ   rK   r   r   r   r   r   rR   r   r>   r=   r   r   create_task_start_streaming_run_impl_task)r   r   rk   r   ry   r   r   r   r   r   r   	new_tracer   r   r  rY   rY   rZ   r     sn   





zAgentRunner.run_streamedr   LRunHooksBase[Any, Agent[Any]] | AgentHooksBase[Any, Agent[Any]] | Any | NoneRunHooks[Any]c                 C  sT   | d u r	t t  S t| j}t| trtd| dt| ts(td| d| S )NzFRun hooks must be instances of RunHooks. Received agent-scoped hooks (z;). Attach AgentHooks to an Agent via Agent(..., hooks=...).z2Run hooks must be instances of RunHooks. Received .)r3   r   r   ro   r   r2   	TypeErrorr4   )r   input_hook_typerY   rY   rZ   r     s   



zAgentRunner._validate_run_hooksrw   r   rz   r   RunContextWrapper[TContext]input_itemsrj   system_instructionsrl   ri   c             
     s   |}|}|j du rt||dS z-t| |d}t|||jd}	| |	}
t|
r0|
I dH n|
}t|ts;td|W S  t	yW } zt
tddt|id  d}~ww )zApply optional call_model_input_filter to modify model input.

        Returns a `ModelInputData` that will be sent to the model.
        N)rk   rm   )ru   rw   ry   z=call_model_input_filter must return a ModelInputData instancez Error in call_model_input_filtererrorr   )r   ri   copyrt   ry   inspectisawaitabler   r#   	ExceptionrO   attach_error_to_current_spanrH   r   )r   rw   r   r   r  r  effective_instructionseffective_inputmodel_inputfilter_payloadmaybe_updatedupdatederY   rY   rZ   _maybe_filter_model_input  s6   


z%AgentRunner._maybe_filter_model_input
Agent[Any]
guardrailslist[InputGuardrail[TContext]]ry   r  parent_span	Span[Any]c              	     s   |j } fdd|D }g }	z-t|D ]%}
|
I d H }|jjr2t|td|j	 ddd |
| |	| qW n tyO   |D ]}|  qG w |	|_d S )Nc              
     "   g | ]}t t |qS rY   r   r  r   run_single_input_guardrailr   	guardrailrw   ry   rk   rY   rZ   r   -      z@AgentRunner._run_input_guardrails_with_queue.<locals>.<listcomp>Guardrail tripwire triggeredinput_guardrail)r%  r   r   )_input_guardrail_queuer   as_completedr   tripwire_triggeredrO   r   rH   r%  get_name
put_nowaitr   r  cancelr   )r   rw   r  rk   ry   r  r  queueguardrail_tasksguardrail_resultsdoner   r   rY   r&  rZ    _run_input_guardrails_with_queue   s8   





z,AgentRunner._run_input_guardrails_with_queuer   r   r   RunHooks[TContext]r   r   r   r   c                   s  |j r|j jdd d }|}d}d}t }|jt|d zt||
|jI d H }||_	t
|
|g I d H  	 |jr?nt| ||I d H }|d u rdd | ||I d H D }| | }rf| }nd}t|j||d}|jdd d	d |D }||j_|d
7 }||_||krt|tdd|id |jt  n|d
krt| ||j|jpg  t|||||_z| ||||||||||	
I d H }d}|j |j!g |_ |j"|_	|j#|_$t%|j&t'r|j&j(}|j)dd d }d}|jt|d nat%|j&t*rMt| +|j,|j,pg  ||j&j-||_.z|j.I d H }W n t/y.   g }Y nw ||_0|j&j-|_1d|_t
|
g |j2I d H  |jt  nt%|j&t3r_t
|
g |j2I d H  W nQ t4y } zd|_|jt  t5|j	|j$|j |||j6|j0d|_7 d }~w t/y } z|rt|tddt8|id d|_|jt   d }~ww q:d|_W |r|j)dd |j r|j j)dd d S d S |r|j)dd |j r|j j)dd w w )NTr   r   )r   c                 S  r   rY   r   r   rY   rY   rZ   r   x  r   z0AgentRunner._start_streaming.<locals>.<listcomp>r   r   c                 S  r   rY   r   r   rY   rY   rZ   r     r   r   r   r   r   Fr   r   zError in agent runr  )9rK   r   r   _event_queuer.  r@   rR   r   r   rk   r   r   r   r   r   r   rI   r   r   r   rO   r   rH   r   r   r  r4  r   r,   input_to_new_input_list_input_guardrails_task_run_single_turn_streamedr   r   r   r   r   r   r   r   r   r   r   r   r   r   _output_guardrails_taskr  r   r   r   r   r   r"   r   r   r   )r   r   r  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   
tool_namesr   r   r   r  rY   rY   rZ   r  K  s2  








	
 zAgentRunner._start_streamingr   r]   r   r   r   
list[Tool]r   c                   s2  t  |rt||||jr|j||nt I d H  | |}||_	||_
t||||I d H \}}| ||I d H }| ||}|j|j}t|||}d }t|j}|dd |jD  | j|||||dI d H }t||||j|j|jr|j|||j|jnt I d H  |j|j|j||||t|j|j|	|
|d
2 z~3 d H W }t|t r|j!j"rt#d|j!j"j$|j!j"j%|j!j"j&|j!j"j'|j!j"j(dnt# }t)|j!j*||j!j+d}|j",| t|t-r$|j.}t|t/r$t0|dt0|d	d   r$ vr$,  t1t2t3||d
}|j45t6|dd |j45t7|d q6 |d urPt|jrB|j8|||nt |8|||I d H  |sWt9d| j:||j|j|||||||||j4dI d H }dd l;}|j<}r fdd|D }dd |D }|j=||d}t>||j4 |S )Nc                 S     g | ]}|  qS rY   to_input_itemr   itemrY   rY   rZ   r   ,      z9AgentRunner._run_single_turn_streamed.<locals>.<listcomp>rw   r   r   r  r  )r   r   promptr   )requestsinput_tokensoutput_tokenstotal_tokensinput_tokens_detailsoutput_tokens_details)r   usageresponse_idcall_idid)raw_itemrw   tool_called)rA  r   )r   z'Model did not produce a final response!)rw   r   pre_step_itemsnew_responser   r   r   r   r   r   r   event_queuer   c              	     s>   g | ]}t |trt|jd t|jdd  r v s|qS )rM  rN  N)r   r/   getattrrO  r@  rM  emitted_tool_call_idsrY   rZ   r     s    
	c                 S  s   g | ]	}t |ts|qS rY   r   r+   r@  rY   rY   rZ   r     
    
)r   )?setr   r   on_agent_startr   on_startrN   noop_coroutiner   r   r   get_system_prompt
get_promptr   
_get_modelr~   resolver   maybe_reset_tool_choicer,   r7  rk   r   r   r  on_llm_startrm   stream_responser   r   r   r   r
   responserK  rM   rF  rG  rH  rI  rJ  r-   r   rN  addr   rA  _TOOL_CALL_TYPESrT  r/   r   r0   r6  r.  rB   rA   
on_llm_endr    %_get_single_step_result_from_responsedataclassesr   replacestream_step_result_to_queue)r   r  rw   r   r   r   r   r   r   r   r   r   system_promptprompt_configr   r{   r~   final_responserk   filteredeventrK  output_item	tool_itemsingle_step_result_dcitems_to_filterfiltered_resultrY   rU  rZ   r9     s   


		


	


8

z%AgentRunner._run_single_turn_streamedr   r   list[RunItem]c                  s   |rt ||||jr|j||nt I d H  t ||||I d H \}}| 	|}| 
||I d H }t|}|dd |D  | ||||||||||	|
||I d H }| j|||||||||||	dI d H S )Nc                 S  r=  rY   r>  )r   generated_itemrY   rY   rZ   r     rB  z0AgentRunner._run_single_turn.<locals>.<listcomp>)rw   r   rQ  rR  r   r   r   r   r   r   r   )r   r   rZ  r   r[  rN   r\  r]  r^  r   r   r,   r7  r   _get_new_responserh  )r   rw   r   r   r   r   r   r   r   r   r   r   rl  rm  r   r   rk   rR  rY   rY   rZ   r     sX   

	


zAgentRunner._run_single_turnN)rS  rQ  rR  r-   r   AgentOutputSchemaBase | Noner   list[Handoff]rS  9asyncio.Queue[StreamEvent | QueueCompleteSentinel] | Nonec                  s~   t j|||||d}|||j |d ur.|jr.dd |jD }|r.t ttt || t j	||||||||	|
d	I d H S )Nrw   r   rd  r   r   c                 S  s   g | ]	}t |tr|qS rY   rW  r@  rY   rY   rZ   r     rX  zEAgentRunner._get_single_step_result_from_response.<locals>.<listcomp>	rw   r   rQ  rR  processed_responser   r   r   r   )
r   process_model_responseadd_tool_use
tools_usedr   stream_step_items_to_queuer   listr.   execute_tools_and_side_effects)r   rw   r   r   rQ  rR  r   r   r   r   r   r   rS  r  handoff_itemsrY   rY   rZ   rh    s4   z1AgentRunner._get_single_step_result_from_responsec       
           s   |j }|j}|j}tj|||||d}|j |
||j t | tj|||||||||	d	I d H } fdd|j	D }t|| |S )Nr}  r~  c                   s   g | ]}| vr|qS rY   rY   r@  new_items_processed_responserY   rZ   r   T  s
    zNAgentRunner._get_single_step_result_from_streamed_response.<locals>.<listcomp>)
rk   r   r6  r   r  r  r  r  r  r   )r   rw   r   r  rR  r   r   r   r   r   r   r   rQ  rS  r  rs  r   rY   r  rZ   ._get_single_step_result_from_streamed_response+  s<   
z:AgentRunner._get_single_step_result_from_streamed_responselist[InputGuardrailResult]c           
        s   |sg S  fdd|D }g }t |D ]+}|I d H }|jjr=|D ]}	|	  q$ttdd|j	 id t
||| q|S )Nc              
     r!  rY   r"  r$  r&  rY   rZ   r   h  r'  z5AgentRunner._run_input_guardrails.<locals>.<listcomp>r(  r%  r   )r   r+  r   r,  r/  rO   r  rH   r%  r-  r   r   )
r   rw   r  rk   ry   r1  r2  r3  r   r   rY   r&  rZ   r   ]  *   

z!AgentRunner._run_input_guardrailslist[OutputGuardrail[TContext]]agent_outputr   list[OutputGuardrailResult]c           
        s   |sg S  fdd|D }g }t |D ]+}|I d H }|jjr=|D ]}	|	  q$ttdd|j	 id t
||| q|S )Nc              
     s"   g | ]}t t| qS rY   )r   r  r   run_single_output_guardrailr$  rw   r  ry   rY   rZ   r     r'  z6AgentRunner._run_output_guardrails.<locals>.<listcomp>r(  r%  r   )r   r+  r   r,  r/  rO   r  rH   r%  r-  r!   r   )
r   r  rw   r  ry   r1  r2  r3  r   r   rY   r  rZ   r     r  z"AgentRunner._run_output_guardrailsrl  rm  ResponsePromptParam | Nonec                   s   | j ||	|||dI d H }| ||	}|j|	j}t||
|}t||||j	|j
|jr;|j|||j	|j
nt I d H  |j|j	|j
||||t|	j|	j|||d
I d H }|j|j t|jrp|j|||nt ||||I d H  |S )NrC  )
r  rk   r~   r   r   r   tracingr   r   rD  )r  r_  r~   r`  r   ra  r   r   rb  rm   rk   r   rN   r\  get_responser   r   r   rK  re  rg  )r   rw   rl  rk   r   r   r   r   r   r   r   r   r   rm  ro  r{   r~   rR  rY   rY   rZ   ry    sX   

	zAgentRunner._get_new_responsec                 C  s4   |j d u s
|j tu rd S t|j tr|j S t|j S N)r   r   r   r   r   )r   rw   rY   rY   rZ   r     s
   
zAgentRunner._get_output_schemaRunContextWrapper[Any]c                   s   g }j D ]}t|tr|| qt|tr|t| qdfdd tj fdd|D  I d H }d	d
 t||D }|S )Nhandoff_objr(   rV   r]   c                   s@   | j }t|tr|S | }t|rt|I d H S t|S r  )
is_enabledr   r]   r  r  )r  attrres)rw   r   rY   rZ   _check_handoff_enabled  s   


z9AgentRunner._get_handoffs.<locals>._check_handoff_enabledc                 3  s    | ]} |V  qd S r  rY   r   )r  rY   rZ   	<genexpr>  s    z,AgentRunner._get_handoffs.<locals>.<genexpr>c                 S  s   g | ]\}}|r|qS rY   rY   )r   r   okrY   rY   rZ   r     s    z-AgentRunner._get_handoffs.<locals>.<listcomp>)r  r(   rV   r]   )	r   r   r(   r   r   r*   r   r   zip)r   rw   r   r   handoff_itemresultsenabledrY   )r  rw   r   rZ   r     s   


	zAgentRunner._get_handoffsc                   s   | |I d H S r  )get_all_tools)r   rw   r   rY   rY   rZ   r     s   zAgentRunner._get_all_toolsr9   c                 C  sL   t |jtr	|jS t |jtr|j|jS t |jtr|jS |j|jS r  )r   r{   r9   r   r}   	get_model)r   rw   r   rY   rY   rZ   r_    s   zAgentRunner._get_modelr   r   c                   s   |du r|S t |tr|std| I dH }t|}|du r&|| S t|r;|||}t|r9|I dH S |S td| d)z>Prepare input by combining it with session history if enabled.Na<  When using session memory, list inputs require a `RunConfig.session_input_callback` to define how they should be merged with the conversation history. If you don't want to use a callback, provide your input as a string instead, or disable session memory (session=None) and pass a list to manage the history manually.z(Invalid `session_input_callback` value: z6. Choose between `None` or a custom callable function.)	r   r  r#   	get_itemsr,   r7  callabler  r  )r   rk   r   r   historynew_input_listr  rY   rY   rZ   r   %  s&   	




z'AgentRunner._prepare_input_with_sessionr   rW   c                   sB   |du rdS t |}dd |D }|| }||I dH  dS )z
        Save the conversation turn to session.
        It does not account for any filtering or modification performed by
        `RunConfig.session_input_callback`.
        Nc                 S  r=  rY   r>  r@  rY   rY   rZ   r   `  rB  z7AgentRunner._save_result_to_session.<locals>.<listcomp>)r,   r7  	add_items)r   r   r   r   
input_listnew_items_as_inputitems_to_saverY   rY   rZ   r   M  s   
z#AgentRunner._save_result_to_session)r   rv   rk   r   r   r   rV   r<   )r   rv   rk   r   r   r   rV   r=   )r   r  rV   r  )rw   rv   r   rz   r   r  r  rj   r  rl   rV   ri   )rw   r  r  r  rk   r   ry   r  r  r=   r  r   )r   r   r  r=   r   rv   r   r   r   r5  r   r  r   rz   r   rl   r   rl   r   r   )r  r=   rw   rv   r   r5  r   r  r   rz   r   r]   r   r   r   r<  r   rl   r   rl   rV   r   )rw   rv   r   r<  r   r   r   rw  r   r5  r   r  r   rz   r   r]   r   r   r   rl   r   rl   rV   r   )rw   rv   r   r<  r   r   rQ  rw  rR  r-   r   rz  r   r{  r   r5  r   r  r   rz   r   r   rS  r|  rV   r   )rw   rv   r   r<  r  r=   rR  r-   r   rz  r   r{  r   r5  r   r  r   rz   r   r   rV   r   )
rw   r  r  r  rk   r   ry   r  rV   r  )
r  r  rw   rv   r  r   ry   r  rV   r  )rw   rv   rl  rl   rk   rj   r   rz  r   r<  r   r{  r   r5  r   r  r   rz   r   r   r   rl   r   rl   rm  r  rV   r-   )rw   r  rV   rz  )rw   r  r   r  rV   r{  )rw   r  r   r  rV   r<  )rw   r  r   rz   rV   r9   )rk   r   r   r   r   r   rV   r   )r   r   r   r   r   rw  rV   rW   )ro   rp   rq   rr   r   r   r   staticmethodr   r   r  r4  r  r9  r   rh  r  r   r   ry  r   r   r   r_  r   r   rY   rY   rY   rZ   rR     sV    
 
:
H(* 5 9B.1%%I
'ztuple[type, ...]rf  rk   r   c                 C  s   t | tr| S |  S r  )r   r   r  )rk   rY   rY   rZ   r   k  s   
r   )rT   rU   rV   rW   )rV   rR   )rV   r]   )rk   r   rV   r   )|
__future__r   r   r  rc   ri  r   r   typingr   r   r   r   r	   openai.types.responsesr
   r   ,openai.types.responses.response_prompt_paramr   typing_extensionsr   r   r   	_run_implr   r   r   r   r   r   r   r   r   rw   r   r  r   r   
exceptionsr   r   r   r    r!   r"   r#   r%  r$   r%   r&   r'   r   r(   r)   r*   itemsr+   r,   r-   r.   r/   r0   r1   	lifecycler2   r3   r4   r5   memoryr6   r7   r~   r8   models.interfacer9   r:   models.multi_providerr;   r   r<   r=   run_contextr>   r?   stream_eventsr@   rA   rB   rC   toolrD   tool_guardrailsrE   rF   r  rG   rH   rI   rJ   rK   tracing.span_datarL   rK  rM   utilrN   rO   util._typesrP   r   rS   rs   r[   r\   rh   ri   rt   CallModelInputFilterrz   r   r   rR   rf  r   rY   rY   rY   rZ   <module>   sx    ,$	$	

	
		M \         -