o
    S۷i$                     @   s$  d dl 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mZ d dl	m
Z
 d dlmZ d dlmZmZ d dlZd dlZd dlmZ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 m!Z!m"Z"m#Z# d dl$m%Z% e%rd 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+ d dl$m,Z, d dl-m.Z. e/dZ0dZ1G dd deZ2ddde3fddZ4ddde3fddZ5e j6		ddd d!d d"d d#d$d%e3d&e3d'e7dd(fd)d*Z8	+	,	-	.		dd/d0Z9dd3d4Z:d5e3d6d$d7d8d9d8d:d$d;d$de3fd<d=Z;	-	.	;	$	7	8	9	8		dd>d?Z<dd@dAZ=ddBdCZ>	D	$		EddFdGZ?dd dHe7dd$fdIdJZ@G dKdL dLZAG dMdN dNZBdOdPdQe7de3fdRdSZCddVdWZDdddejEf	Y	Z	$	[		\	]		 dd^d_ZFdddbdcZGdddddeZHdfdgdhd$didjdeIfdkdlZJ	m	n	o	p		jddqdrZKdsd dte7ddufdvdwZL	dd\dxdZe7dydde7fdzd{ZMd\dxde7fd|d}ZNd\dxd~e3dddydddf
ddZOdddZPd\dxd~e3dd ddfddZQd-dd\dxd~e3dZe7dd dddydddfddZRd-dd\dxd~e3dd ddf
ddZSddde3fddZTddde7ddfddZUd dlVmWZWmXZXmYZY e%rd dlVmZZZ dS dS )    N)MappingMutableMapping)	timedelta)Random)quoteunquote)OPSPANDATA
SPANSTATUSSPANTEMPLATE)capture_internal_exceptionsfilename_for_moduleloggermatch_regex_listqualname_from_function	safe_repr	to_stringtry_convertis_sentry_url_is_external_source_is_in_project_root_module_in_list)TYPE_CHECKING)Any)Dict)	Generator)Optional)Union)Iterator)Tuple)	FrameTypez5^[ 	]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ 	]*$z(([a-zA-Z0-9+/]{4})*([a-zA-Z0-9+/]{2,3})?c                   @   sP   e Zd Z	ddddeddfddZd	edd
fddZdefddZdddZdS )EnvironHeadersHTTP_environzMapping[str, str]prefixreturnNc                 C   s   || _ || _d S N)r#   r$   )selfr#   r$    r(   N/home/ubuntu/vllm_env/lib/python3.10/site-packages/sentry_sdk/tracing_utils.py__init__B   s   
zEnvironHeaders.__init__keyOptional[Any]c                 C   s   | j | j|dd   S N-_)r#   r$   replaceupper)r'   r+   r(   r(   r)   __getitem__J      zEnvironHeaders.__getitem__c                 C   s   t dd t| D S )Nc                 s   s    | ]}d V  qdS )   Nr(   ).0r/   r(   r(   r)   	<genexpr>N   s    z)EnvironHeaders.__len__.<locals>.<genexpr>)sumiterr'   r(   r(   r)   __len__M   s   zEnvironHeaders.__len__Generator[str, None, None]c                 c   sP    | j D ]!}t|tsq|dd }|| jsq|t| jd  V  qd S r-   )r#   
isinstancestrr0   r1   
startswithr$   len)r'   kr(   r(   r)   __iter__P   s   

zEnvironHeaders.__iter__)r"   )r%   r;   )	__name__
__module____qualname__r=   r*   r2   intr:   rA   r(   r(   r(   r)   r!   A   s    
r!   optionsOptional[Dict[str, Any]]r%   c                 C   s:   | du rdS t | dduo| ddup| dduS )z}
    Returns True if either traces_sample_rate or traces_sampler is
    defined and enable_tracing is set and not false.
    NFenable_tracingtraces_sample_ratetraces_sampler)boolgetrF   r(   r(   r)   has_tracing_enabled\   s   rN   Optional[dict[str, Any]]c                 C   s$   | d u rdS |  dpi  ddkS )NF_experimentstrace_lifecyclestream)rL   rM   r(   r(   r)   has_span_streaming_enabledm   s   rS   Fmanualcursorr   queryparams_list
paramstyleOptional[str]executemanyrecord_cursor_reprspan_originz.Generator[sentry_sdk.tracing.Span, None, None]c                 c   s    t  jd ddr|r|d gkrd }|dkrd}nd }d }t| |}i }|d ur/||d< |d ur7||d< |r=d|d	< |rG| d urG| |d
< t  t j|d|d W d    n1 s]w   Y  t jtj	||d}|
 D ]
\}	}
||	|
 qp|V  W d    d S 1 sw   Y  d S )NrP   record_sql_paramsFpyformatformatz	db.paramszdb.paramstyleTzdb.executemanyz	db.cursorrV   )messagecategorydata)opnameorigin)
sentry_sdk
get_clientrF   rL   _format_sqlr   add_breadcrumb
start_spanr   DBitemsset_data)rU   rV   rW   rX   rZ   r[   r\   rb   spanr@   vr(   r(   r)   record_sql_queriest   s@   
"rp   scopesentry_sdk.Scopern   sentry_sdk.tracing.Spanc                 C   s   |j tjkr| j|jdd|jd d S |j tjkrZd }|jt	j
}|rAd|  kr.dkr3n nd}nd|  kr=dkrAn nd}|rO| jd	d
|j|d d S | jd	d
|jd d S |j dkrl| jdd|j|jd d S d S )Nredis)r`   typera   rb   i  iW  errori  i  warninghttphttplib)ru   ra   rb   level)ru   ra   rb   
subprocess)ru   ra   r`   rb   )rc   r   DB_REDISri   description_tagsHTTP_CLIENT_datarL   r	   HTTP_STATUS_CODE)rq   rn   rz   status_coder(   r(   r)   "maybe_create_breadcrumbs_from_span   s2   




r   framer    c                 C   s    z| j jW S  ty   Y d S w r&   )f_codeco_filename	Exception)r   r(   r(   r)   _get_frame_module_abs_path   s
   
r   is_sentry_sdk_frame	namespacein_app_includeOptional[list[str]]in_app_excludeabs_pathproject_rootc                 C   s6   t ||}t|pt ||}|  o|pt||o| S r&   )r   r   r   )r   r   r   r   r   r   should_be_includedshould_be_excludedr(   r(   r)   _should_be_included   s   
	
r   c                 C   s  t  }|dur=t|}z|jd}W n ty   d}Y nw |duo(|d}t||||||d}|r6n	|j}|dusd}|durz|j	}	W n tyS   d}	Y nw |	dur`| 
tj|j	 z|jd}W n tys   d}Y nw |dur| 
tj| t|}
|
dur|durt||
}n|dur|
|r|
|dtj}n|
}| 
tj| z|jj}W n ty   d}Y nw |dur| 
tj|jj dS dS dS )zB
    Adds OTel compatible source code information to the span
    NrB   zsentry_sdk.)r   r   r   r   r   r    )sys	_getframer   	f_globalsrL   r   r>   r   f_backf_linenorm   r	   CODE_LINENOCODE_NAMESPACEr   r0   lstripossepCODE_FILEPATHr   co_nameCODE_FUNCTION)rn   r   r   r   r   r   r   r   r   linenofilepathin_app_pathcode_functionr(   r(   r)   
add_source   sp   

r   c                 C      t  }| s
dS | jdu s| jdu rdS |jdd}|s!dS | j| j }|jdd}|tdd |k}|s;dS t| |jd |jd	|jd
d dS )zO
    Adds OTel compatible source code information to a database query span
    Nenable_db_query_sourceTdb_query_source_threshold_msr   r4   millisecondsr   r   r   rn   r   r   r   	rf   rg   	is_active	timestampstart_timestamprF   rL   r   r   )rn   clientshould_add_query_sourceduration	threshold
slow_queryr(   r(   r)   add_query_source&  &   


r   c                 C   r   )z]
    Adds OTel compatible source code information to a span for an outgoing HTTP request
    Nenable_http_request_sourceT http_request_source_threshold_msr   r4   r   r   r   r   r   r   )rn   r   should_add_request_sourcer   r   r   r(   r(   r)   add_http_request_sourceD  r   r   header+Optional[Dict[str, Union[str, bool, None]]]c                 C   s   | sdS |  dr| dr| dd } t| }|sdS | \}}}d}|r0dt|d}|r:dt|d}|r@|d	k}|||d
S )zL
    Given a `sentry-trace` header string, return a dictionary of data.
    Nz00-z-00   z{:032x}   z{:016x}0)trace_idparent_span_idparent_sampled)r>   endswithSENTRY_TRACE_REGEXmatchgroupsr_   rE   )r   r   r   r   sampled_strr   r(   r(   r)   extract_sentrytrace_datab  s&   
r   sqlc                 C   sX   d }zt | dr| |}t|tr|| jj}W n ty%   d }Y nw |p+t|S )Nmogrify)	hasattrr   r<   bytesdecode
connectionencodingr   r   )rU   r   real_sqlr(   r(   r)   rh     s   


rh   c                   @   s  e Zd ZdZdZ						d0									
					d1ddZe				 d2ddZede	fddZ
e
jde	ddfddZ
ede	fddZejde	ddfddZed3ddZde	fdd Zd4d"d#Zd5d%d&Zd6d(d)Zde	fd*d+Zd7d,d-Zd8d.d/ZdS )9PropagationContextzJ
    The PropagationContext represents the data of a trace in Sentry.
    )	_trace_id_span_idr   r   baggageNr   rY   span_idr   r   Optional[bool]dynamic_sampling_contextOptional[Dict[str, str]]r   Optional[Baggage]r%   c                 C   sP   || _ 	 || _	 || _	 || _	 || _	 	 |d u r$|d ur&t|| _d S d S d S r&   )r   r   r   r   r   Baggage)r'   r   r   r   r   r   r   r(   r(   r)   r*     s   	zPropagationContext.__init__incoming_dataDict[str, Any]c                 C   st   t  }t|}|t}t|}|d u r|S |t}|r"t|nd }t|s*|S |	| |r4||_
|  |S r&   )r   normalize_incoming_datarL   SENTRY_TRACE_HEADER_NAMEr   BAGGAGE_HEADER_NAMEr   from_incoming_header_should_continue_traceupdater   _fill_sample_rand)clsr   propagation_contextnormalized_datasentry_trace_headersentrytrace_databaggage_headerr   r(   r(   r)   from_incoming_data  s    


z%PropagationContext.from_incoming_datac                 C   s   | j s	t j| _ | j S )z!The trace id of the Sentry trace.)r   uuiduuid4hexr9   r(   r(   r)   r     s   zPropagationContext.trace_idvaluec                 C   
   || _ d S r&   )r   r'   r   r(   r(   r)   r        
c                 C   s    | j st jdd | _ | j S )z+The span id of the currently executed span.r   N)r   r   r   r   r9   r(   r(   r)   r     s   zPropagationContext.span_idc                 C   r   r&   )r   r   r(   r(   r)   r     r   rG   c                 C   s   |    S r&   )get_baggager   r9   r(   r(   r)   r     s   z+PropagationContext.dynamic_sampling_contextc                 C   s   | j  d| j S )Nr.   )r   r   r9   r(   r(   r)   to_traceparent  s   z!PropagationContext.to_traceparentr   c                 C   s   | j d u rt| | _ | j S r&   )r   r   !populate_from_propagation_contextr9   r(   r(   r)   r     s   
zPropagationContext.get_baggageIterator[Tuple[str, str]]c                 c   s2    t |  fV  |   }|rt|fV  dS dS )zw
        Creates a generator which returns the propagation_context's ``sentry-trace`` and ``baggage`` headers.
        N)r   r   r   	serializer   )r'   r   r(   r(   r)   iter_headers  s   zPropagationContext.iter_headers
other_dictc              	   C   s8   |  D ]\}}zt| || W q ty   Y qw dS )zU
        Updates the PropagationContext with data from the given dictionary.
        N)rl   setattrAttributeError)r'   r   r+   r   r(   r(   r)   r     s   zPropagationContext.updatec                 C   s   d | j| j| j| j| jS )Nz\<PropagationContext _trace_id={} _span_id={} parent_span_id={} parent_sampled={} baggage={}>)r_   r   r   r   r   r   r9   r(   r(   r)   __repr__  s   zPropagationContext.__repr__c              
   C   s   | j du rdS tt| j jd}|dur!d|  kr dk r!dS  tt| j jd}t| j|\}}zt| j||fd}W n t	yU   t
d| j d| d	 Y dS w |d
| j jd< dS )a  
        Ensure that there is a valid sample_rand value in the baggage.

        If there is a valid sample_rand value in the baggage, we keep it.
        Otherwise, we generate a sample_rand value according to the following:

          - If we have a parent_sampled value and a sample_rate in the DSC, we compute
            a sample_rand value randomly in the range:
                - [0, sample_rate) if parent_sampled is True,
                - or, in the range [sample_rate, 1) if parent_sampled is False.

          - If either parent_sampled or sample_rate is missing, we generate a random
            value in the range [0, 1).

        The sample_rand is deterministically generated from the trace_id, if present.

        This function does nothing if there is no baggage.
        Nsample_randr   r4   sample_rateintervalz5Could not backfill sample_rand, since parent_sampled=z and sample_rate=..6f)r   r   floatsentry_itemsrL   _sample_rand_ranger   _generate_sample_randr   
ValueErrorr   debug)r'   r   r   lowerr1   r(   r(   r)   r   !  s&   

z$PropagationContext._fill_sample_randc                 C   s   | j du rdS | j jdS )zAConvenience method to get the sample_rand value from the baggage.Nr   )r   r  rL   r9   r(   r(   r)   _sample_randP  s   
zPropagationContext._sample_rand)NNNNNN)r   rY   r   rY   r   rY   r   r   r   r   r   r   r%   N)r   r   r%   r   )r%   rG   )r%   r   )r%   r   )r   r   r%   Nr%   N)r%   rY   )rB   rC   rD   __doc__	__slots__r*   classmethodr   propertyr=   r   setterr   r   r   r   r   r   r   r   r
  r(   r(   r(   r)   r     s^    







	/r   c                   @   s   e Zd ZdZdZdZedZ		d1ddd	e	d
e
fddZedd					 d2ddZed3ddZe				 d4ddZe				 d5d d!Zd6d"d#Zd7d$d%Zd8d'e
de	fd(d)Zede	de	fd*d+Zd9d-d.Zde	fd/d0ZdS ):r   aF  
    The W3C Baggage header information (see https://www.w3.org/TR/baggage/).

    Before mutating a `Baggage` object, calling code must check that `mutable` is `True`.
    Mutating a `Baggage` object that has `mutable` set to `False` is not allowed, but
    it is the caller's responsibility to enforce this restriction.
    r  third_party_itemsmutablezsentry-z^sentry-r   Tr  Dict[str, str]r  r  c                 C   s   || _ || _|| _d S r&   r  )r'   r  r  r  r(   r(   r)   r*   f  s   
zBaggage.__init__N)r
  r   rY   r
  r%   c          
   	   C   s   i }d}d}|rU| dD ]G}d|vrqt 5 | }| d\}}tj|r;t| dd }	t|||	< d}n
||r@dnd| 7 }W d   n1 sOw   Y  q|durat||d	< d}t|||S )
zF
        freeze if incoming header already has sentry baggage
        r   T,=r.   r4   FNr   )splitr   stripr   SENTRY_PREFIX_REGEXr   r   r=   )
r   r   r
  r  r  r  itemr+   valbaggage_keyr(   r(   r)   r   p  s,   

zBaggage.from_incoming_headerrq   sentry_sdk.scope.Scoper   c                 C   s   |j du r	ti S t|j S )zC
        Deprecated: use populate_from_propagation_context
        N)_propagation_contextr   r   )r   rq   r(   r(   r)   from_options  s   
zBaggage.from_optionsr   r   c                 C   s   i }d}d}t  }| st|S |j}|j|d< |dr%|d |d< |dr0|d |d< |jrC|jj|d< |jj	rC|jj	|d< |drPt
|d |d	< t|||S )
Nr   Fr   environmentrelease
public_keyorg_idrI   r   )rf   rg   r   r   rF   r   rL   
parsed_dsnr"  r#  r=   )r   r   r  r  r  r   rF   r(   r(   r)   r     s&   



z)Baggage.populate_from_propagation_contexttransactionsentry_sdk.tracing.Transactionc                 C   s  t  }i }| st|S |jpi }|j|d< |jd|d< |dr*|d |d< |dr5|d |d< |jrH|jj	|d< |jj
rH|jj
|d< |jrU|jtvrU|j|d< |jd	urat|j|d
< |jd	uro|jrkdnd|d< |jr}|jjr}||jj t|ddS )z
        Populate fresh baggage entry with sentry_items and make it immutable
        if this is the head SDK which originates traces.
        r   r  r   r   r!  r"  r#  r%  Nr   truefalsesampledFr  )rf   rg   r   r   rF   r   r
  rL   r$  r"  r#  rd   sourceLOW_QUALITY_TRANSACTION_SOURCESr   r=   r)  _baggager  r   )r   r%  r   r  rF   r(   r(   r)   populate_from_transaction  s4   







z!Baggage.populate_from_transactionc                 C   s
   d| _ d S )NFr*  r9   r(   r(   r)   freeze  s   
zBaggage.freezec                 C   s$   i }| j  D ]\}}|||< q|S r&   )r  rl   )r'   r   r+   r  r(   r(   r)   r     s   
z Baggage.dynamic_sampling_contextFinclude_third_partyc              	   C   s   g }| j  D ]+\}}t  tjt| d tt| }|| W d    n1 s-w   Y  q|r;|| j d	|S )Nr  r  )
r  rl   r   r   SENTRY_PREFIXr   r=   appendr  join)r'   r0  rl   r+   r  r  r(   r(   r)   r     s   
zBaggage.serializec                 C   s   d dd | dD S )zRemove Sentry baggage from the given header.

        Given a Baggage header, return a new Baggage header with all Sentry baggage items removed.
        r  c                 s   s$    | ]}t j| s|V  qd S r&   )r   r  r   r  )r5   r  r(   r(   r)   r6     s    
z/Baggage.strip_sentry_baggage.<locals>.<genexpr>)r3  r  )r   r(   r(   r)   strip_sentry_baggage  s
   zBaggage.strip_sentry_baggageOptional[float]c                 C   s:   t t| jd}|durd|  krdk r|S  dS dS )zConvenience method to get the sample_rand value from the sentry_items.

        We validate the value and parse it as a float before returning it. The value is considered
        valid if it is a float in the range [0, 1).
        r   N              ?)r   r  r  rL   )r'   r   r(   r(   r)   r
    s
   zBaggage._sample_randc                 C   s   d| j dd d| j dS )Nz
<Baggage "T)r0  z", mutable=>)r   r  r9   r(   r(   r)   r   #  r3   zBaggage.__repr__)r   T)r   rY   r
  rY   r%   r   )rq   r  r%   r   )r   r   r%   r   )r%  r&  r%   r   r  )r%   r  )F)r%   r5  )rB   rC   rD   r  r  r1  recompiler  r=   rK   r*   r  r   r  r   r.  r/  r   r   staticmethodr4  r
  r   r(   r(   r(   r)   r   X  sX    


"	 
1

r   r   zsentry_sdk.client.BaseClienturlc                 C   s&   | j d }t| |rdS t||ddS )zy
    Returns True if url matches trace_propagation_targets configured in the given client. Otherwise, returns False.
    trace_propagation_targetsFT)substring_matching)rF   r   r   )r   r<  r=  r(   r(   r)   should_propagate_trace'  s   

r?  r   r   c                 C   sH   i }|   D ]\}}|dr|dd }|dd }|||< q|S )z
    Normalizes incoming data so the keys are all lowercase with dashes instead of underscores and stripped from known prefixes.
    r"      Nr/   r.   )rl   r>   r0   r	  )r   rb   r+   r   r(   r(   r)   r   3  s   

r   rc   Optional[Union[str, OP]]rd   
attributestemplater   c                    s&   ddl m d	 fdd}|S )
a  
    Create a span decorator that can wrap both sync and async functions.

    :param op: The operation type for the span.
    :type op: str or :py:class:`sentry_sdk.consts.OP` or None
    :param name: The name of the span.
    :type name: str or None
    :param attributes: Additional attributes to set on the span.
    :type attributes: dict or None
    :param template: The type of span to create. This determines what kind of
        span instrumentation and data collection will be applied. Use predefined
        constants from :py:class:`sentry_sdk.consts.SPANTEMPLATE`.
        The default is `SPANTEMPLATE.DEFAULT` which is the right choice for most
        use cases.
    :type template: :py:class:`sentry_sdk.consts.SPANTEMPLATE`
    r   )should_send_default_piifr   r%   c                    s   t  d
 fdd}zt |_W n	 ty"   Y nw t  d
 fdd}zt |_W n	 tyE   Y nw t rM|S |S )zD
        Decorator to create a span for the given function.
        argsr   kwargsr%   c            	   	      s   t  }|d u rtdt | i |I d H S pt}p'tp'd}t||} }|j||d,}| p>i  t|||| | | i |I d H }t	||| |W  d    S 1 sgw   Y  d S NzbCannot create a child span for %s. Please start a Sentry transaction before calling this function.r   )rc   rd   
get_current_spanr   r  r   _get_span_op_get_span_namestart_childupdate_data_set_input_attributes_set_output_attributes	rF  rG  current_spanspan_opfunction_name	span_namesend_piirn   resultrB  rE  rd   rc   rD  rC  r(   r)   async_wrapper_  s2   $zDcreate_span_decorator.<locals>.span_decorator.<locals>.async_wrapperc            	   	      s   t  }|d u rtdt | i |S pt}p#tp#d}t||} }|j||d)}| p:i  t|||| | | i |}t	||| |W  d    S 1 s`w   Y  d S rH  rI  rQ  rX  r(   r)   sync_wrapper  s0   $zCcreate_span_decorator.<locals>.span_decorator.<locals>.sync_wrapperN)rF  r   rG  r   r%   r   )	functoolswrapsinspect	signature__signature__r   iscoroutinefunction)rE  rY  rZ  rB  rd   rc   rD  rC  )rE  r)   span_decoratorZ  s"   
z-create_span_decorator.<locals>.span_decoratorN)rE  r   r%   r   )sentry_sdk.scoperD  )rc   rd   rB  rC  rb  r(   ra  r)   create_span_decoratorB  s   Trd  Optional[sentry_sdk.Scope]Optional[Span]c                 C   s   | pt  } | j}|S )zU
    Returns the currently active span if there is one running, otherwise `None`
    )rf   get_current_scopern   )rq   rR  r(   r(   r)   rJ    s   rJ  c                 C   sB   | pt  } | dur| tj | jdur| jtj dS dS dS )z
    Set the status of the current or given span to INTERNAL_ERROR.
    Also sets the status of the transaction (root span) to INTERNAL_ERROR.
    N)rJ  
set_statusr
   INTERNAL_ERRORcontaining_transaction)rn   r(   r(   r)   set_span_errored  s   

rk  r6  r7  r   r   r   tuple[float, float]c                C   sl   |\}}||k st dt| }t|d }t|d }z|||}W |d S  t y5   |}Y |d S w )a  Generate a sample_rand value from a trace ID.

    The generated value will be pseudorandomly chosen from the provided
    interval. Specifically, given (lower, upper) = interval, the generated
    value will be in the range [lower, upper). The value has 6-digit precision,
    so when printing with .6f, the value will never be rounded up.

    The pseudorandom number generator is seeded with the trace ID.
    z/Invalid interval: lower must be less than upperi@B )r  r   rE   	randrange)r   r   r	  r1   rnglower_scaledupper_scaledsample_rand_scaledr(   r(   r)   r    s   r  r   r   r   r5  c                 C   s,   | du s|du r
dS | du rd|fS |dfS )z
    Compute the lower (inclusive) and upper (exclusive) bounds of the range of values
    that a generated sample_rand value must fall into, given the parent_sampled and
    sample_rate values.
    Nrl  Tr6  r7  r(   )r   r   r(   r(   r)   r    s
   r  r+  r+   r,   c                 C   sT   d}t | tr| |}|S t| |r(zt| |}W |S  ty'   d}Y |S w |S )z
    Gets a value from a source object. The source can be a dict or an object.
    It is checked for dictionary keys and object attributes.
    N)r<   dictrL   r   getattrr   )r+  r+   r   r(   r(   r)   
_get_value  s   


ru  zUnion[str, SPANTEMPLATE]rG  c                 C   s   |}| t jkr/d}|r"dD ]}||r!t|| tr!|| } nq|r+d| }|S d}|S | t jkr;d| }|S | t jkrEd| }|S )zF
    Get the name of the span based on the template and the name.
    N)model
model_namezchat chatzinvoke_agent zexecute_tool )r   AI_CHATrL   r<   r=   AI_AGENTAI_TOOL)rC  rd   rG  rU  rv  r+   r(   r(   r)   rL    s&   




rL  c                 C   s2   t jtjt jtjt jtji}|| tj	}t
|S )z>
    Get the operation of the span based on the template.
    )r   ry  r   GEN_AI_CHATrz  GEN_AI_INVOKE_AGENTr{  GEN_AI_EXECUTE_TOOLrL   FUNCTIONr=   )rC  mappingrc   r(   r(   r)   rK  #  s   rK  rV  rF  ztuple[Any, ...]dict[str, Any]c                    sJ  i  | t jt jt jfv rtjtftjtftjtftjtftjt	ftj
tftjtftjtftjtftjt	fd
dtddddf fdd}t| D ]7\}}|d	krft|trf tjg d
|d qK|dkr}t|tr} tjg d|d qK||| qK| t jkr|rt||d tj< tj v rt tj  tj<  S )z;
    Get input attributes for the given span template.
    )
rv  rw  agent
agent_name
max_tokensfrequency_penaltypresence_penaltytemperaturetop_ptop_kr+   r   r   r%   Nc                    s>   | v r|  \}}|d urt ||r| |< d S d S d S d S r&   )r<   )r+   r   	attribute	data_typerB  r  r(   r)   _set_from_keyJ  s   z,_get_input_attributes.<locals>._set_from_keypromptuser)rolecontentsystem_promptsystem)rF  rG  )r   rz  r{  ry  r	   GEN_AI_REQUEST_MODELr=   GEN_AI_AGENT_NAMEGEN_AI_REQUEST_MAX_TOKENSrE    GEN_AI_REQUEST_FREQUENCY_PENALTYr  GEN_AI_REQUEST_PRESENCE_PENALTYGEN_AI_REQUEST_TEMPERATUREGEN_AI_REQUEST_TOP_PGEN_AI_REQUEST_TOP_Klistrl   r<   
setdefaultGEN_AI_REQUEST_MESSAGESr2  r   GEN_AI_TOOL_INPUT)rC  rV  rF  rG  r  r+   r   r(   r  r)   _get_input_attributes1  sF   	


r  usagec                    sH   i  dt ddddf fdd}|tjd |tjd	 |tjd
  S )z
    Get usage attributes.
    r  keysztuple[str, ...]r%   Nc                    s2   |D ]}t |}|d urt|tr| | < qd S r&   )ru  r<   rE   )r  r  r+   r   rB  r  r(   r)   _set_from_keyss  s   
z-_get_usage_attributes.<locals>._set_from_keys)prompt_tokensinput_tokens)completion_tokensoutput_tokens)total_tokens)r=   r	   GEN_AI_USAGE_INPUT_TOKENSGEN_AI_USAGE_OUTPUT_TOKENSGEN_AI_USAGE_TOTAL_TOKENS)r  r  r(   r  r)   _get_usage_attributesm  s   r  rW  c           	      C   s  i }| t jt jt jfv rqt Z |g}t|d}|| t|d}t|d}|| |D ]}|dur;|t| q.t|d}|durOt	|t
rO||tj< t|d}|durbt	|t
rb||tj< W d   n1 slw   Y  | t jkr|rt||tj< |S )z<
    Get output attributes for the given span template.
    r  metadataNrv  rw  )r   rz  r{  ry  r   ru  r2  r   r  r<   r=   r	   GEN_AI_RESPONSE_MODELr   GEN_AI_TOOL_OUTPUT)	rC  rV  rW  rB  usage_candidatesr  metausage_candidaterw  r(   r(   r)   _get_output_attributes  s0   








r  SpanrE  c           	      C   s   i }|t jkrtjdtj|i}n$|t jkrtjdi}n|t jkr4tjdtj|i}|j}|dur4||tj	< |
t|||| | |pCi  dS )a  
    Set span input attributes based on the given span template.

    :param span: The span to set attributes on.
    :param template: The template to use to set attributes on the span.
    :param send_pii: Whether to send PII data.
    :param f: The wrapped function.
    :param args: The arguments to the wrapped function.
    :param kwargs: The keyword arguments to the wrapped function.
    invoke_agentrx  execute_toolN)r   rz  r	   GEN_AI_OPERATION_NAMEr  ry  r{  GEN_AI_TOOL_NAMEr  GEN_AI_TOOL_DESCRIPTIONr   r  rN  )	rn   rC  rV  rd   rE  rF  rG  rB  	docstringr(   r(   r)   rO    s"   



rO  c                 C   s   |  t|||p	i  dS )a%  
    Set span output attributes based on the given span template.

    :param span: The span to set attributes on.
    :param template: The template to use to set attributes on the span.
    :param send_pii: Whether to send PII data.
    :param result: The result of the wrapped function.
    N)rN  r  )rn   rC  rV  rW  r(   r(   r)   rP    s   rP  r   r   c                 C   s   t  }|j}|r|jnd}| r| jdnd}|dur2|dur2||kr2td| d| d dS |jdd}|rY|durC|du sK|du rY|durYtd| d| d dS d	S )
z
    Check if we should continue the incoming trace according to the strict_trace_continuation spec.
    https://develop.sentry.dev/sdk/telemetry/traces/#stricttracecontinuation
    Nr#  zKStarting a new trace because org IDs don't match (incoming baggage org_id: z, SDK org_id: )Fstrict_trace_continuationzvStarting a new trace because strict trace continuation is enabled and one org ID is missing (incoming baggage org_id: T)	rf   rg   r$  r#  r  rL   r   r  rF   )r   r   r$  client_org_idbaggage_org_idr  r(   r(   r)   r     s,   r   headerszMutableMapping[str, str]sentry_baggagec                 C   s>   |  td}t|}t|dkrdnd}|| | | t< dS )zAdd the Sentry baggage to the headers.

    This function directly mutates the provided headers. The provided sentry_baggage
    is appended to the existing baggage. If the baggage already contains Sentry items,
    they are stripped out first.
    r   r   r  N)rL   r   r   r4  r?   )r  r  existing_baggagestripped_existing_baggage	separatorr(   r(   r)   add_sentry_baggage_to_headers  s
   	


r  )r   r,  r   )r  )FrT   )rq   rr   rn   rs   r%   N)r   r    r%   rY   )
rn   rs   r   rY   r   r   r   r   r%   N)rn   rs   r%   N)r   rY   r%   r   )r   r   r%   r   )
rc   rA  rd   rY   rB  rO   rC  r   r%   r   r&   )rq   re  r%   rf  )rn   rf  r%   N)r   r   r   r5  r%   rm  )r  r   r%   r  )[
contextlibr[  r]  r   r9  r   collections.abcr   r   datetimer   randomr   urllib.parser   r   r   rf   sentry_sdk.constsr   r	   r
   r   sentry_sdk.utilsr   r   r   r   r   r   r   r   r   r   r   r   typingr   r   r   r   r   r   r   r   typesr    r:  r   base64_strippedr!   rK   rN   rS   contextmanagerr=   rp   r   r   r   r   r   r   r   rh   r   r   r?  r   DEFAULTrd  rJ  rk  r  r  r  ru  rL  rK  r  r  r  rO  rP  r   r  sentry_sdk.tracingr   r,  r   r  r(   r(   r(   r)   <module>   s   8
-

!


I

! D P

o	




<
(
,
$
