o
    Zhh-                     @   s   d dl Z d dlmZmZ d dlmZmZ d dlmZ d dlm	Z
 zd dlmZ d dlm  mZ dZW n eyE   dZG d	d
 d
ZY nw d dlmZ e eZerfG dd deZG dd
 d
ejZdS dS )    N)datetimetimezone)Optional	TypedDict)uuid4)	run_trees)tracingTFc                   @   s   e Zd ZdZdd ZdS )OpenAIAgentsTracingProcessora  Tracing processor for the `OpenAI Agents SDK <https://openai.github.io/openai-agents-python/>`_.

        Traces all intermediate steps of your OpenAI Agent to LangSmith.

        Requirements: Make sure to install ``pip install -U langsmith[openai-agents]``.

        Args:
            client: An instance of langsmith.client.Client. If not provided,
                a default client is created.

        Example:
            .. code-block:: python

                from agents import (
                    Agent,
                    FileSearchTool,
                    Runner,
                    WebSearchTool,
                    function_tool,
                    set_trace_processors,
                )

                from langsmith.wrappers import OpenAIAgentsTracingProcessor

                set_trace_processors([OpenAIAgentsTracingProcessor()])


                @function_tool
                def get_weather(city: str) -> str:
                    return f"The weather in {city} is sunny"


                haiku_agent = Agent(
                    name="Haiku agent",
                    instructions="Always respond in haiku form",
                    model="o3-mini",
                    tools=[get_weather],
                )
                agent = Agent(
                    name="Assistant",
                    tools=[WebSearchTool()],
                    instructions="speak in spanish. use Haiku agent if they ask for a haiku or for the weather",
                    handoffs=[haiku_agent],
                )

                result = await Runner.run(
                    agent,
                    "write a haiku about the weather today and tell me a recent news story about new york",
                )
                print(result.final_output)
        c                 O   s   t d)NzeThe `agents` package is not installed. Please install it with `pip install langsmith[openai-agents]`.)ImportError)selfargskwargs r   X/var/www/html/lang_env/lib/python3.10/site-packages/langsmith/wrappers/_openai_agents.py__init__F   s   %OpenAIAgentsTracingProcessor.__init__N)__name__
__module____qualname____doc__r   r   r   r   r   r	      s    4r	   )clientc                   @   s:   e Zd ZU eed< eed< eed< eed< ee ed< dS )RunDataidtrace_id
start_timedotted_orderparent_run_idN)r   r   r   str__annotations__r   r   r   r   r   r   r   S   s   
 r   c                   @   s   e Zd ZdZ	dddddddeej dee deee	  dee	 dee	 f
d	d
Z
dejddfddZdejddfddZdejddfddZdejddfddZdddZdddZdS )r	   a  Tracing processor for the `OpenAI Agents SDK <https://openai.github.io/openai-agents-python/>`_.

        Traces all intermediate steps of your OpenAI Agent to LangSmith.

        Requirements: Make sure to install ``pip install -U langsmith[openai-agents]``.

        Args:
            client: An instance of langsmith.client.Client. If not provided,
                a default client is created.
            metadata: Metadata to associate with all traces.
            tags: Tags to associate with all traces.
            project_name: LangSmith project to trace to.
            name: Name of the root trace.

        Example:
            .. code-block:: python

                from agents import (
                    Agent,
                    FileSearchTool,
                    Runner,
                    WebSearchTool,
                    function_tool,
                    set_trace_processors,
                )

                from langsmith.wrappers import OpenAIAgentsTracingProcessor

                set_trace_processors([OpenAIAgentsTracingProcessor()])


                @function_tool
                def get_weather(city: str) -> str:
                    return f"The weather in {city} is sunny"


                haiku_agent = Agent(
                    name="Haiku agent",
                    instructions="Always respond in haiku form",
                    model="o3-mini",
                    tools=[get_weather],
                )
                agent = Agent(
                    name="Assistant",
                    tools=[WebSearchTool()],
                    instructions="speak in spanish. use Haiku agent if they ask for a haiku or for the weather",
                    handoffs=[haiku_agent],
                )

                result = await Runner.run(
                    agent,
                    "write a haiku about the weather today and tell me a recent news story about new york",
                )
                print(result.final_output)
        N)metadatatagsproject_namenamer   r   r    r!   r"   c                C   s<   |pt  | _|| _|| _|| _|| _i | _i | _i | _	d S N)
rtZget_cached_clientr   	_metadata_tags_project_name_name_first_response_inputs_last_response_outputs_runs)r   r   r   r    r!   r"   r   r   r   r      s   	
r   tracereturnc           
      C   s  | j r| j }n	|jr|j}nd}tt }ttj}tj	||d}t
||||d d| j|j< d| jp4i i}| p;i }|dd urK|d |d d< zt|i d||||d || j| jd}| jjd
i | W d S  ty }	 ztd	|	  W Y d }	~	d S d }	~	ww )NzAgent workflow)r   run_idr   r   r   r   r   r   Zgroup_idZ	thread_idchain)r"   inputsrun_typer   r   r   r   Zrevision_idextrar    r!   zError creating trace run: r   )r(   r"   r   r   r   nowr   utcagent_utilsensure_dotted_orderr   r+   r   r%   exportgetdictr&   r'   r   
create_run	Exceptionlogger	exception)
r   r,   run_nameZtrace_run_idr   r   Z	run_extra
trace_dictrun_dataer   r   r   on_trace_start   sR   
z+OpenAIAgentsTracingProcessor.on_trace_startc              
   C   s   | j |jd }| pi }i |dpi | jpi }|r]z#| jj|d |d |d | j|ji | j	|ji d|id W d S  t
y\ } ztd|  W Y d }~d S d }~ww d S )Nr   r   r   r   )r.   r   r   r1   outputsr3   zError updating trace run: )r+   popr   r8   r9   r%   r   
update_runr)   r*   r<   r=   r>   )r   r,   runr@   r   rB   r   r   r   on_trace_end   s$   z)OpenAIAgentsTracingProcessor.on_trace_endspanc                 C   sP  |j r
| j|j n| j|j}|d u r td|j  d S |d }tt }|j	r2t
|j	nt
tj}tj|||rB|d nd d}t|||||d d| j|j< t|}t|}t|}	z(t|||||d ||	di d}
|j	rt
|j	|
d	< | jjdi |
 W d S  ty } ztd
|  W Y d }~d S d }~ww )Nz(No trace info found for span, skipping: r   r   )r   r.   Zparent_dotted_orderr   r/   r1   )r"   r2   r   r   r   r   r1   r   zError creating span run: r   )	parent_idr+   r9   r   r=   warningspan_idr   r   Z
started_atr   fromisoformatr4   r   r5   r6   r7   r   Zget_run_nameZget_run_typeextract_span_datar:   r   r;   r<   r>   )r   rI   Z
parent_runr   Zspan_run_idZspan_start_timer   r?   r2   	extractedrA   rB   r   r   r   on_span_start   s^   






	z*OpenAIAgentsTracingProcessor.on_span_startc              
   C   s  | j |jd }|rt|}|di }|j|d< |j|d< |j|d< ||d< |di }|di }t|d |d |d	 |d
 |j	rIt
|j	nd |||d}|jr[t|j|d< t|jtjru| j|jpj|| j|j< || j|j< | jjdi | d S d S )Nr   Zopenai_parent_idZopenai_trace_idZopenai_span_idrD   r1   r   r   r   r   )r.   r   r   r   errorrD   r1   r3   Zend_timer   )r+   rE   rL   r6   rN   r9   rJ   r   r:   rQ   r   Zended_atr   rM   
isinstanceZ	span_datar   ZResponseSpanDatar)   r*   r   rF   )r   rI   rG   rO   r   rD   r1   rA   r   r   r   on_span_end  s8   





z(OpenAIAgentsTracingProcessor.on_span_endc                 C      | j   d S r#   r   flushr   r   r   r   shutdown>     z%OpenAIAgentsTracingProcessor.shutdownc                 C   rT   r#   rU   rW   r   r   r   force_flushA  rY   z(OpenAIAgentsTracingProcessor.force_flushr#   )r-   N)r   r   r   r   r   	ls_clientZClientr:   listr   r   r   TracerC   rH   SpanrP   rS   rX   rZ   r   r   r   r   r	   Z   s2    :

06
 )loggingr   r   typingr   r   uuidr   Z	langsmithr   r$   Zagentsr   Zlangsmith.wrappers._agent_utilsZwrappersZ_agent_utilsr6   ZHAVE_AGENTSr
   r	   r   r[   	getLoggerr   r=   r   ZTracingProcessorr   r   r   r   <module>   s&    ?
