o
    h,                     @  s   d dl mZ d dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlZddlmZ ddlmZmZ dd	lmZ dd
lmZ G dd deZG dd deZG dd deZe ZeeZdddZdddZdS )    )annotationsN)cached_property)Any   )logger   )TracingExporterTracingProcessor)Span)Tracec                   @  s   e Zd ZdZd	ddZdS )
ConsoleSpanExporterz+Prints the traces and spans to the console.itemslist[Trace | Span[Any]]returnNonec                 C  sD   |D ]}t |trtd|j d|j  qtd|   qd S )Nz[Exporter] Export trace_id=z, name=z[Exporter] Export span: )
isinstancer   printtrace_idnameexport)selfr   item r   Z/var/www/html/openai_agents/venv/lib/python3.10/site-packages/agents/tracing/processors.pyr      s
   
zConsoleSpanExporter.exportNr   r   r   r   )__name__
__module____qualname____doc__r   r   r   r   r   r      s    r   c                   @  sf   e Zd Z							d#d$ddZd%ddZedd Zedd Zedd Zd&dd Z	d!d" Z
dS )'BackendSpanExporterN'https://api.openai.com/v1/traces/ingest         ?      >@api_key
str | Noneorganizationprojectendpointstrmax_retriesint
base_delayfloat	max_delayc                 C  sF   || _ || _|| _|| _|| _|| _|| _tjtj	dddd| _
dS )a  
        Args:
            api_key: The API key for the "Authorization" header. Defaults to
                `os.environ["OPENAI_API_KEY"]` if not provided.
            organization: The OpenAI organization to use. Defaults to
                `os.environ["OPENAI_ORG_ID"]` if not provided.
            project: The OpenAI project to use. Defaults to
                `os.environ["OPENAI_PROJECT_ID"]` if not provided.
            endpoint: The HTTP endpoint to which traces/spans are posted.
            max_retries: Maximum number of retries upon failures.
            base_delay: Base delay (in seconds) for the first backoff.
            max_delay: Maximum delay (in seconds) for backoff growth.
        <         @)timeoutconnectr1   N)_api_key_organization_projectr(   r*   r,   r.   httpxClientTimeout_client)r   r$   r&   r'   r(   r*   r,   r.   r   r   r   __init__   s   zBackendSpanExporter.__init__c                 C  s   d| j v r	| j d= || _dS )zSet the OpenAI API key for the exporter.

        Args:
            api_key: The OpenAI API key to use. This is the same key used by the OpenAI Python
                client.
        r$   N)__dict__r4   )r   r$   r   r   r   set_api_keyA   s   

zBackendSpanExporter.set_api_keyc                 C     | j ptjdS )NOPENAI_API_KEY)r4   osenvirongetr   r   r   r   r$   O      zBackendSpanExporter.api_keyc                 C  r>   )NOPENAI_ORG_ID)r5   r@   rA   rB   rC   r   r   r   r&   S   rD   z BackendSpanExporter.organizationc                 C  r>   )NOPENAI_PROJECT_ID)r6   r@   rA   rB   rC   r   r   r   r'   W   rD   zBackendSpanExporter.projectr   r   r   r   c           
   
   C  s  |sd S | j std d S dd |D }d|i}d| j  ddd}| jr+| j|d	< | jr3| j|d
< d}| j}	 |d7 }zF| jj| j||d}|j	dk r[t
dt| d W d S d|j	  krfdk rxn ntd|j	 d|j  W d S td|j	 d W n tjy } ztd|  W Y d }~nd }~ww || jkrtd d S |tdd|  }	t|	 t|d | j}q9)Nz0OPENAI_API_KEY is not set, skipping trace exportc                 S  s   g | ]
}|  r|  qS r   )r   ).0r   r   r   r   
<listcomp>c   s    z.BackendSpanExporter.export.<locals>.<listcomp>datazBearer zapplication/jsonz	traces=v1)AuthorizationzContent-TypezOpenAI-BetazOpenAI-OrganizationzOpenAI-Projectr   Tr   )urlheadersjsoni,  z	Exported z itemsi  i  z![non-fatal] Tracing client error z: z"[non-fatal] Tracing: server error z, retrying.z%[non-fatal] Tracing: request failed: zB[non-fatal] Tracing: max retries reached, giving up on this batch.g?r   )r$   r   warningr&   r'   r,   r:   postr(   status_codedebuglenerrortextr7   RequestErrorr*   randomuniformtimesleepminr.   )
r   r   rI   payloadrL   attemptdelayresponseexc
sleep_timer   r   r   r   [   sV   







zBackendSpanExporter.exportc                 C  s   | j   dS )z!Close the underlying HTTP client.N)r:   closerC   r   r   r   ra      s   zBackendSpanExporter.close)NNNr    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   ra   r   r   r   r   r      s$    
"



=r   c                   @  s~   e Zd ZdZ				d.d/ddZd0ddZd1ddZd1ddZd2ddZd2ddZ	d3d4d#d$Z
d%d& Zd'd( Zd5d6d,d-Zd S )7BatchTraceProcessorzSome implementation notes:
    1. Using Queue, which is thread-safe.
    2. Using a background thread to export spans, to minimize any performance issues.
    3. Spans are stored in memory until they are exported.
           r0   ffffff?exporterr   max_queue_sizer+   max_batch_sizeschedule_delayr-   export_trigger_ratioc                 C  sh   || _ tj|d| _|| _|| _|| _t | _	t
dt|| | _t | j | _d| _t | _dS )a  
        Args:
            exporter: The exporter to use.
            max_queue_size: The maximum number of spans to store in the queue. After this, we will
                start dropping spans.
            max_batch_size: The maximum number of spans to export in a single batch.
            schedule_delay: The delay between checks for new spans to export.
            export_trigger_ratio: The ratio of the queue size at which we will trigger an export.
        )maxsizer   N)	_exporterqueueQueue_queue_max_queue_size_max_batch_size_schedule_delay	threadingEvent_shutdown_eventmaxr+   _export_trigger_sizerX   _next_export_time_worker_threadLock_thread_start_lock)r   rf   rg   rh   ri   rj   r   r   r   r;      s   
zBatchTraceProcessor.__init__r   r   c                 C  s~   | j r
| j  r
d S | j( | j r| j  r	 W d    d S tj| jdd| _ | j   W d    d S 1 s8w   Y  d S )NT)targetdaemon)ry   is_aliver{   rs   Thread_runstartrC   r   r   r   _ensure_thread_started   s   "z*BatchTraceProcessor._ensure_thread_startedtracer   c                 C  <   |    z	| j| W d S  tjy   td Y d S w )NzQueue is full, dropping trace.r   ro   
put_nowaitrm   Fullr   rN   r   r   r   r   r   on_trace_start      z"BatchTraceProcessor.on_trace_startc                 C     d S Nr   r   r   r   r   on_trace_end      z BatchTraceProcessor.on_trace_endspan	Span[Any]c                 C  r   r   r   r   r   r   r   r   on_span_start   r   z!BatchTraceProcessor.on_span_startc                 C  r   )NzQueue is full, dropping span.r   r   r   r   r   on_span_end   r   zBatchTraceProcessor.on_span_endNr1   float | Nonec                 C  s<   | j   | jr| j r| jj|d dS | jdd dS )z`
        Called when the application stops. We signal our thread to stop, then join it.
        r3   TforceN)ru   setry   r~   join_export_batches)r   r1   r   r   r   shutdown   s   
zBatchTraceProcessor.shutdownc                 C  s   | j dd dS )z@
        Forces an immediate flush of all queued spans.
        Tr   N)r   rC   r   r   r   force_flush   s   zBatchTraceProcessor.force_flushc                 C  sr   | j  s1t }| j }|| jks|| jkr'| jdd t | j | _nt	d | j  r| jdd d S )NFr   g?T)
ru   is_setrX   ro   qsizerx   rw   r   rr   rY   )r   current_time
queue_sizer   r   r   r      s   



zBatchTraceProcessor._runFr   boolc                 C  s~   	 g }| j  s4|st|| jk r4z
|| j   W n
 tjy%   Y nw | j  s4|st|| jk s|s8dS | j	| q)zDrains the queue and exports in batches. If force=True, export everything.
        Otherwise, export up to `max_batch_size` repeatedly until the queue is completely empty.
        TN)
ro   emptyrR   rq   append
get_nowaitrm   Emptyrl   r   )r   r   items_to_exportr   r   r   r     s&   

	z#BatchTraceProcessor._export_batches)rc   rd   r0   re   )
rf   r   rg   r+   rh   r+   ri   r-   rj   r-   )r   r   )r   r   r   r   )r   r   r   r   r   )r1   r   )F)r   r   )r   r   r   r   r;   r   r   r   r   r   r   r   r   r   r   r   r   r   rb      s     	
"

	

	rb   r   c                   C     t S )zOThe default exporter, which exports traces and spans to the backend in batches.)_global_exporterr   r   r   r   default_exporter/  r   r   c                   C  r   )zPThe default processor, which exports traces and spans to the backend in batches.)_global_processorr   r   r   r   default_processor4  r   r   )r   r   )r   rb   )
__future__r   r@   rm   rV   rs   rX   	functoolsr   typingr   r7   r   processor_interfacer   r	   spansr
   tracesr   r   r   rb   r   r   r   r   r   r   r   r   <module>   s*     
