o
    hxM                     @  s   U d dl mZ d dl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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 dd
l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%m&Z&m'Z' ddl(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 e
rddl:m;Z;m<Z< ddl m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC eG dd dZDee/e0 eEe3 ge9eD f ZFdeGd< 	 G d d! d!eZHG d"d# d#eZIeG d$d% d%ee0 ZJeG d&d' d'eJee0 ZKdS )(    )annotationsN)	Awaitable)	dataclassfield)TYPE_CHECKINGAnyCallableGenericLiteralcast)ResponsePromptParam)NotRequired	TypeAlias	TypedDict   AgentOutputSchemaBase)InputGuardrailOutputGuardrail)Handoff)ItemHelpers)logger)MCPUtil)ModelSettings)get_default_model_settings!gpt_5_reasoning_settings_requiredis_gpt_5_defaultModel)DynamicPromptFunctionPrompt
PromptUtil)RunContextWrapperTContext)FunctionToolFunctionToolResultToolfunction_tool)_transforms)MaybeAwaitable)
AgentHooksRunHooks)	MCPServer)Session)	RunResult)	RunConfigc                   @  s$   e Zd ZU ded< 	 dZded< dS )ToolsToFinalOutputResultboolis_final_outputNz
Any | Nonefinal_output)__name__
__module____qualname____annotations__r3    r8   r8   M/var/www/html/openai_agents/venv/lib/python3.10/site-packages/agents/agent.pyr0   (   s
   
 r0   r   ToolsToFinalOutputFunctionc                   @  s   e Zd ZU ded< dS )StopAtToolsz	list[str]stop_at_tool_namesN)r4   r5   r6   r7   r8   r8   r8   r9   r;   >   s   
 r;   c                   @  s   e Zd ZU dZded< dS )	MCPConfigzConfiguration for MCP servers.zNotRequired[bool]convert_schemas_to_strictN)r4   r5   r6   __doc__r7   r8   r8   r8   r9   r=   C   s   
 r=   c                   @  s~   e Zd ZU dZded< 	 dZded< 	 eedZded	< 	 eedZ	d
ed< 	 edd dZ
ded< 	 dddZdddZdS )	AgentBasez+Base class for `Agent` and `RealtimeAgent`.strnameN
str | Nonehandoff_descriptiondefault_factory
list[Tool]toolszlist[MCPServer]mcp_serversc                   C  s   t  S N)r=   r8   r8   r8   r9   <lambda>e   s    zAgentBase.<lambda>r=   
mcp_configrun_contextRunContextWrapper[TContext]returnc                   s(   | j dd}t| j||| I dH S )z1Fetches the available tools from the MCP servers.r>   FN)rL   getr   get_all_function_toolsrI   )selfrM   r>   r8   r8   r9   get_mcp_toolsh   s
   

zAgentBase.get_mcp_toolsc                   sd    I dH }dfdd tj fdd	jD  I dH }d
d tj|D }g ||S )z8All agent tools, including MCP tools and function tools.Ntoolr&   rO   r1   c                   sN   t | tsdS | j}t |tr|S | }t|r#t|I d H S t|S )NT)
isinstancer$   
is_enabledr1   inspectisawaitable)rT   attrres)rM   rR   r8   r9   _check_tool_enableds   s   



z4AgentBase.get_all_tools.<locals>._check_tool_enabledc                 3  s    | ]} |V  qd S rJ   r8   ).0t)r[   r8   r9   	<genexpr>   s    z*AgentBase.get_all_tools.<locals>.<genexpr>c                 S  s   g | ]\}}|r|qS r8   r8   )r\   r]   okr8   r8   r9   
<listcomp>   s    z+AgentBase.get_all_tools.<locals>.<listcomp>)rT   r&   rO   r1   )rS   asynciogatherrH   zip)rR   rM   	mcp_toolsresultsenabledr8   )r[   rM   rR   r9   get_all_toolso   s    zAgentBase.get_all_tools)rM   rN   rO   rG   )r4   r5   r6   r?   r7   rD   r   listrH   rI   rL   rS   rg   r8   r8   r8   r9   r@   L   s   
 	
r@   c                   @  s  e Zd ZU dZdZded< 	 dZded< 	 eedZ	ded	< 	 dZ
d
ed< 	 eedZded< 	 ee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d Zd>d"d#Z								d?d@d5d6ZdAd9d:ZdBd<d=ZdS )CAgentaI  An agent is an AI model configured with instructions, tools, guardrails, handoffs and more.

    We strongly recommend passing `instructions`, which is the "system prompt" for the agent. In
    addition, you can pass `handoff_description`, which is a human-readable description of the
    agent, used when the agent is used inside tools/handoffs.

    Agents are generic on the context type. The context is a (mutable) object you create. It is
    passed to tool functions, handoffs, guardrails, etc.

    See `AgentBase` for base parameters that are shared with `RealtimeAgent`s.
    NzZstr | Callable[[RunContextWrapper[TContext], Agent[TContext]], MaybeAwaitable[str]] | Noneinstructionsz%Prompt | DynamicPromptFunction | NonepromptrE   z)list[Agent[Any] | Handoff[TContext, Any]]handoffszstr | Model | Nonemodelr   model_settingszlist[InputGuardrail[TContext]]input_guardrailszlist[OutputGuardrail[TContext]]output_guardrailsz(type[Any] | AgentOutputSchemaBase | Noneoutput_typezAgentHooks[TContext] | Nonehooksrun_llm_againzYLiteral['run_llm_again', 'stop_on_first_tool'] | StopAtTools | ToolsToFinalOutputFunctiontool_use_behaviorTr1   reset_tool_choicec                 C  s@  ddl m} t| jtstdt| jj | jd ur-t| jts-tdt| jj t| j	t
s>tdt| j	j t| jt
sOtdt| jj t| jts`tdt| jj | jd ur{t| jts{t| js{tdt| jj | jd urt| jst| jd	std
t| jj t| jt
stdt| jj | jd urt| jtsddlm} t| j|stdt| jj t| jtstdt| jj | jd urt du rt| jtdu st| jdu r| jt krt | _t| jt
stdt| jj t| jt
s!tdt| jj | jd urIddlm} t| jt|fsI|| jd usItdt| jj | j d urgddl!m"} t| j |sgtdt| j j t| j#trt| j#dv st| j#tst| j#stdt| j#j t| j$t%stdt| j$j d S )Nr   )
get_originz!Agent name must be a string, got z8Agent handoff_description must be a string or None, got z Agent tools must be a list, got z&Agent mcp_servers must be a list, got z%Agent mcp_config must be a dict, got z<Agent instructions must be a string, callable, or None, got rP   zCAgent prompt must be a Prompt, DynamicPromptFunction, or None, got z#Agent handoffs must be a list, got r   r   z2Agent model must be a string, Model, or None, got z;Agent model_settings must be a ModelSettings instance, got TFz+Agent input_guardrails must be a list, got z,Agent output_guardrails must be a list, got r   zFAgent output_type must be a type, AgentOutputSchemaBase, or None, got )AgentHooksBasez8Agent hooks must be an AgentHooks instance or None, got )rs   stop_on_first_toolzjAgent tool_use_behavior must be 'run_llm_again', 'stop_on_first_tool', StopAtTools dict, or callable, got z/Agent reset_tool_choice must be a boolean, got )&typingrv   rU   rB   rA   	TypeErrortyper4   rD   rH   rh   rI   rL   dictrj   callablerk   hasattrrl   rm   models.interfacer   rn   r   r   r   r   ro   rp   rq   agent_outputr   rr   	lifecyclerw   rt   ru   r1   )rR   rv   r   r   rw   r8   r8   r9   __post_init__   s   
















zAgent.__post_init__kwargsr   rO   Agent[TContext]c                 K  s   t j| fi |S )ad  Make a copy of the agent, with the given arguments changed.
        Notes:
            - Uses `dataclasses.replace`, which performs a **shallow copy**.
            - Mutable attributes like `tools` and `handoffs` are shallow-copied:
              new list objects are created only if overridden, but their contents
              (tool functions and handoff objects) are shared with the original.
            - To modify these independently, pass new lists when calling `clone()`.
        Example:
            ```python
            new_agent = agent.clone(instructions="New instructions")
            ```
        )dataclassesreplace)rR   r   r8   r8   r9   cloneo  s   zAgent.clone	tool_namerC   tool_descriptioncustom_output_extractor,Callable[[RunResult], Awaitable[str]] | NonerV   Obool | Callable[[RunContextWrapper[Any], AgentBase[Any]], MaybeAwaitable[bool]]
run_configRunConfig | None	max_turns
int | NoneRunHooks[TContext] | Noneprevious_response_idconversation_idsessionSession | Noner&   c              
     s>   t |ptj|pd|dd fdd	}|S )aD  Transform this agent into a tool, callable by other agents.

        This is different from handoffs in two ways:
        1. In handoffs, the new agent receives the conversation history. In this tool, the new agent
           receives generated input.
        2. In handoffs, the new agent takes over the conversation. In this tool, the new agent is
           called as a tool, and the conversation is continued by the original agent.

        Args:
            tool_name: The name of the tool. If not provided, the agent's name will be used.
            tool_description: The description of the tool, which should indicate what it does and
                when to use it.
            custom_output_extractor: A function that extracts the output from the agent. If not
                provided, the last message from the agent will be used.
            is_enabled: Whether the tool is enabled. Can be a bool or a callable that takes the run
                context and agent and returns whether the tool is enabled. Disabled tools are hidden
                from the LLM at runtime.
         )name_overridedescription_overriderV   contextr"   inputrA   rO   c                   sd   ddl m}m} d urn|}|j || j| d	I d H }r,|I d H S t|jS )Nr   )DEFAULT_MAX_TURNSRunner)	starting_agentr   r   r   r   rr   r   r   r   )runr   r   r   r   text_message_outputs	new_items)r   r   r   r   resolved_max_turnsoutputr   r   rr   r   r   r   rR   r   r8   r9   	run_agent  s"   z Agent.as_tool.<locals>.run_agentN)r   r"   r   rA   rO   rA   )r'   r(   transform_string_function_stylerB   )rR   r   r   r   rV   r   r   rr   r   r   r   r   r8   r   r9   as_tool~  s   !zAgent.as_toolrM   rN   c                   s   t | jtr
| jS t| jrPt| j}t|j }t	|dkr3t
dt	| ddd |D  t| jrGttt | || I d H S tt| || S | jd uratdt| jj  d S )N   zR'instructions' callable must accept exactly 2 arguments (context, agent), but got z: c                 S  s   g | ]}|j qS r8   )rB   )r\   pr8   r8   r9   r`     s    z+Agent.get_system_prompt.<locals>.<listcomp>z:Instructions must be a string or a callable function, got )rU   rj   rA   r}   rW   	signaturerh   
parametersvalueslenrz   iscoroutinefunctionr   r   r   errorr{   r4   )rR   rM   sigparamsr8   r8   r9   get_system_prompt  s0   


zAgent.get_system_promptResponsePromptParam | Nonec                   s   t | j|| I dH S )zGet the prompt for the agent.N)r!   to_model_inputrk   )rR   rM   r8   r8   r9   
get_prompt  s   zAgent.get_prompt)r   r   rO   r   )NTNNNNNN)r   rC   r   rC   r   r   rV   r   r   r   r   r   rr   r   r   rC   r   rC   r   r   rO   r&   )rM   rN   rO   rC   )rM   rN   rO   r   )r4   r5   r6   r?   rj   r7   rk   r   rh   rl   rm   r   rn   ro   rp   rq   rr   rt   ru   r   r   r   r   r   r8   r8   r8   r9   ri      sP   
 

 

=ri   )L
__future__r   ra   r   rW   collections.abcr   r   r   ry   r   r   r   r	   r
   r   ,openai.types.responses.response_prompt_paramr   typing_extensionsr   r   r   r   r   	guardrailr   r   rl   r   itemsr   r   mcpr   rn   r   models.default_modelsr   r   r   r   r   promptsr   r    r!   rM   r"   r#   rT   r$   r%   r&   r'   utilr(   util._typesr)   r   r*   r+   r,   memory.sessionr-   resultr.   r   r/   r0   rh   r:   r7   r;   r=   r@   ri   r8   r8   r8   r9   <module>   sV     	7