
    h2                     J   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
 d dlmZ 	 d dlmZ dZ ed	 eD              s ed
      d dlmc mZ dZd dlmZ  e j4                  e      Zer! G d de      Z G d dej<                        Zyy# e$ r dZ G d d      ZY Ow xY w)    N)datetimetimezone)Optional	TypedDict)uuid4)	run_trees)get_current_run_tree)tracing)TracingProcessorTraceSpanResponseSpanDatac              #   <   K   | ]  }t        t        |        y wN)hasattrr
   ).0names     `/var/www/html/aiagenthome/venv/lib/python3.12/site-packages/langsmith/wrappers/_openai_agents.py	<genexpr>r      s     ;($ww%(s   z&The `agents` package is not installed.TFc                       e Zd ZdZd Zy)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                     t        d      )NzeThe `agents` package is not installed. Please install it with `pip install langsmith[openai-agents]`.)ImportError)selfargskwargss      r   __init__z%OpenAIAgentsTracingProcessor.__init__P   s    Q     N)__name__
__module____qualname____doc__r    r   r   r   r      s    2	h	r   r   )clientc                   V    e Zd ZU eed<   eed<   eed<   eed<   ee   ed<   ee   ed<   y)RunDataidtrace_id
start_timedotted_orderparent_run_idproject_nameN)r   r    r!   str__annotations__r   r   r#   r   r   r&   r&   ]   s,    }$sm#r   r&   c                      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	Z
d
ej                  ddfdZd
ej                  ddfdZdej                  ddfdZdej                  ddfdZddZddZy)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tagsr,   r   r$   r0   r1   r,   r   c                    |xs t        j                         | _        || _        || _        || _        || _        i | _        i | _        i | _	        y r   )
rtget_cached_clientr$   	_metadata_tags_project_name_name_first_response_inputs_last_response_outputs_runs)r   r$   r0   r1   r,   r   s         r   r   z%OpenAIAgentsTracingProcessor.__init__   sM     !:B$8$8$:DK%DNDJ!-DDJ02D'02D'-/DJr   tracereturnc                    t               }| j                  r| j                  }n|j                  r|j                  }nd}t        t	                     }t        j                  t        j                        }| j                  }|Qt        |j                        }t        |j                        }|j                  }	| j                  xs |j                  }n|}d }d }	t        j                  |||	      }
t!        ||||
||      | j"                  |j                  <   d| j$                  xs i i}|j'                         xs i }|j)                  d      |d   |d   d<   	 t+        |i d||||
|d || j,                  |      } | j.                  j0                  d
i | y # t2        $ r"}t4        j7                  d	|        Y d }~y d }~ww xY w)NzAgent workflowr)   run_idparent_dotted_orderr'   r(   r)   r*   r+   r,   r0   group_id	thread_idchain)r   inputsrun_typer'   r(   r+   r*   r)   revision_idextrar1   r,   zError creating trace run: r#   )r	   r8   r   r-   r   r   nowr   utcr7   r(   r'   r*   session_nameagent_utilsensure_dotted_orderr&   r;   r5   exportgetdictr6   r$   
create_run	Exceptionlogger	exception)r   r<   current_run_treerun_nametrace_run_idr)   r,   r(   r+   rA   r*   	run_extra
trace_dictrun_dataes                  r   on_trace_startz+OpenAIAgentsTracingProcessor.on_trace_start   s   35zz:: ::+uw<L!hll3J  --L+/889 #$4$7$7 8&6&C&C##11R5E5R5R' $&*#&::%#$7L
 *1!%)+)*DJJu~~& $T^^%9r:I-2J~~j)55?
5K	*%k2C!%!$#%"/!-) $#!-" '&&22 C  #=aS!ABBCs   =F 	G$GGc                 "   | j                   j                  |j                  d       }|j                         xs i }i |j	                  d      xs i | j
                  xs i }|r~	 | j                  j                  |d   |d   |d   |d   | j                  j                  |j                  i       | j                  j                  |j                  i       d|i|d          y y # t        $ r"}t        j                  d|        Y d }~y d }~ww xY w)	Nr0   r'   r(   r+   r*   r,   )r@   r(   r+   r*   rF   outputsrI   r,   zError updating trace run: )r;   popr(   rO   rP   r5   r$   
update_runr9   r:   rS   rT   rU   )r   r<   runrZ   r0   r\   s         r   on_trace_endz)OpenAIAgentsTracingProcessor.on_trace_end   s   **..6C-2JW:>>*5;WAUSUWHGKK**"4y!$Z&)/&:%(%8#::>>u~~rR $ ; ; ? ?PR S)84%(%8 + 	  ! G$$'A!%EFFGs   %A<C# #	D,D		Dspanc                 "   |j                   r%| j                  j                  |j                         n$| j                  j                  |j                        }|#t        j                  d|j                          y |d   }t        t                     }|j                  rt        j                  |j                        n"t        j                  t        j                        }t        j                   |||r|d   nd       }t#        |||||d   |d         | j                  |j                  <   t        j$                  |      }t        j&                  |      }t        j(                  |      }		 t+        |||||d   ||	j                  di       |d   	      }
|j                  r"t        j                  |j                        |
d
<    | j,                  j.                  di |
 y # t0        $ r"}t        j3                  d|        Y d }~y d }~ww xY w)Nz(No trace info found for span, skipping: r(   r*   r?   r'   r,   rB   rF   )r   rG   r'   r(   r+   r*   rF   r,   r)   zError creating span run: r#   )	parent_idr;   rP   r(   rT   warningspan_idr-   r   
started_atr   fromisoformatrJ   r   rK   rM   rN   r&   get_run_nameget_run_typeextract_span_datarQ   r$   rR   rS   rU   )r   rd   
parent_runr(   span_run_idspan_start_timer*   rW   rG   	extractedr[   r\   s               r   on_span_startz*OpenAIAgentsTracingProcessor.on_span_start  s    >> 

t~~.ZZ^^DMM2  !>t||nM !*-Heg,K ?? &&t7\\(,,/ 
 '::*"BLJ~$>RVL
 (/!*)(.'7(DJJt||$ #//5H"//5H#55d;IB!%!%"%",T"2!-$==26!+N!;	" ??-5-C-CDOO-TH\*&&&22 B  #<QC!@AABs   /A3G# #	H,H		Hc                 h   | j                   j                  |j                  d       }|rt        j                  |      }|j                  di       }|j                  |d<   |j                  |d<   |j                  |d<   ||d<   |j                  di       }|j                  di       }t        |d   |d   |d	   |d
   |j                  rt        |j                        nd ||||d   	      }|j                  r"t        j                  |j                        |d<   t        |j                  t         j"                        rY| j$                  j                  |j                        xs || j$                  |j                  <   || j&                  |j                  <    | j(                  j*                  di | y y )Nr0   openai_parent_idopenai_trace_idopenai_span_idr_   rF   r'   r(   r*   r+   r,   )	r@   r(   r*   r+   errorr_   rF   rI   r,   end_timer#   )r;   r`   rh   rM   rm   rP   rf   r(   rQ   rw   r-   ended_atr   rj   
isinstance	span_datar
   r   r9   r:   r$   ra   )r   rd   rb   rq   r0   r_   rF   r[   s           r   on_span_endz(OpenAIAgentsTracingProcessor.on_span_end>  s{   **..t4C'99$?	$==R8/3~~+,.2mm*+-1\\)*(0	*%#--	26"x4!%t9 _!$^!4"%o"6-1ZZ#djj/T#!#!$^!4
" ==+3+A+A$--+PHZ(dnng.F.FG3377FP& //> BID//>&&&22; r   c                 8    | j                   j                          y r   r$   flushr   s    r   shutdownz%OpenAIAgentsTracingProcessor.shutdown_      KKr   c                 8    | j                   j                          y r   r~   r   s    r   force_flushz(OpenAIAgentsTracingProcessor.force_flushb  r   r   r   )r=   N)r   r    r!   r"   r   	ls_clientClientrQ   listr-   r   r
   r   r]   rc   r   rr   r|   r   r   r#   r   r   r   r   e   s    6	t 26	0 (,(,*."&	0Y--.	0 tn		0
 49%	0 #3-	0 3-	0&?	C ?	C$ ?	CB	Ggmm 	G 	G(6	Bgll 6	Bt 6	Bp	3GLL 	3T 	3B	 	 r   )loggingr   r   typingr   r   uuidr   	langsmithr   r3   langsmith.run_helpersr	   agentsr
   requiredallr   langsmith.wrappers._agent_utilswrappers_agent_utilsrM   HAVE_AGENTSr   r$   r   	getLoggerr   rT   r&   r   r#   r   r   <module>r      s     ' &  % 6KH ;(;;BCC99K@ *			8	$$) $~ w'?'? ~  G  <K9 9<s   *B B"!B"