o
    0 i#                     @   s   d dl mZ d dl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 d dlmZ d d	lmZ erJd d
l mZmZ d dlmZ zd dlZW n ey[   edw dd Zdd Zdd Zdd ZG dd deZdS )    )TYPE_CHECKINGN)consts)record_token_usage)get_start_span_functionset_data_normalizedtruncate_and_annotate_messages)SPANDATA)DidNotEnableIntegration)should_send_default_pii)event_from_exception)AnyDict)datetimezLiteLLM not installedc                 C   s.   |  di }|d}|du ri }||d< |S )z,Get the metadata dictionary from the kwargs.litellm_paramsmetadataN)
setdefaultget)kwargsr   r    r   k/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/sentry_sdk/integrations/litellm.py_get_metadata_dict   s   
r   c                 C   s  t  t}|du rdS | dd}zt|\}}}}W n ty+   |}d}Y nw | dd}|dkr9d}nd}t |dkrEt	j
jnt	j
j| d	| tjd
}|  |t| d< t|tj| t|tj| | dg }	|	rt r|jrt  }
t|	||
}|durt|tj|dd tjtjtjtjtjtjtjd}|  D ]\}}| |}|durt||| q| d| d| dd}|  D ]\}}|durt|d| | qdS )zHandle the start of a request.Nmodel unknown	call_typeZ	embeddingZ
embeddingsZchat )opnameorigin_sentry_spanmessagesF)unpack)r   streamZ
max_tokensZpresence_penaltyZfrequency_penaltyZtemperatureZtop_papi_baseapi_versioncustom_llm_provider)r$   r%   r&   zgen_ai.litellm.)!
sentry_sdk
get_clientget_integrationLiteLLMIntegrationr   litellmZget_llm_provider	Exceptionr   r   OPZGEN_AI_CHATZGEN_AI_EMBEDDINGSr   	__enter__r   r   r   ZGEN_AI_SYSTEMZGEN_AI_OPERATION_NAMEr   include_promptsZget_current_scoper   ZGEN_AI_REQUEST_MESSAGESZGEN_AI_REQUEST_MODELZGEN_AI_RESPONSE_STREAMINGZGEN_AI_REQUEST_MAX_TOKENSZGEN_AI_REQUEST_PRESENCE_PENALTYZ GEN_AI_REQUEST_FREQUENCY_PENALTYZGEN_AI_REQUEST_TEMPERATUREZGEN_AI_REQUEST_TOP_Pitems)r   integrationZ
full_modelr   provider_r   Z	operationspanr!   scopeZmessages_dataparamskey	attributevaluer   r   r   r   _input_callback'   sn   	
	
r:   c           
      C   s  t | d}|du rdS t t}|du rdS zt|dr(t|tj	|j
 t r|jrt|drg }|jD ]P}t|drt|jdrN||j  q8t|jdr]||j  q8i }t|jdrk|jj|d< t|jd	rw|jj|d	< t|jd
r|jj|d
< || q8|rt|tj| t|dr|j}	t|t|	ddt|	ddt|	ddd W |ddd dS W |ddd dS |ddd w )zHandle successful completion.r    Nr   choicesmessage
model_dumpdictrolecontent
tool_callsusageZprompt_tokensZcompletion_tokenstotal_tokens)Zinput_tokensZoutput_tokensrC   )r   r   r'   r(   r)   r*   hasattrr   r   ZGEN_AI_RESPONSE_MODELr   r   r/   r;   r<   appendr=   r>   r?   r@   rA   ZGEN_AI_RESPONSE_TEXTrB   r   getattr__exit__)
r   Zcompletion_response
start_timeend_timer4   r1   Zresponse_messageschoicemsgrB   r   r   r   _success_callbackt   sX   









	"rL   c                 C   st   t | d}|du rdS z"t|t jdddd\}}tj||d W |t||d dS |t||d w )zHandle request failure.r    Nr+   F)typeZhandled)Zclient_optionsZ	mechanism)hint)	r   r   r   r'   r(   optionsZcapture_eventrG   rM   )r   	exceptionrH   rI   r4   eventrN   r   r   r   _failure_callback   s   
*rR   c                   @   s4   e Zd ZdZdZde Zd
ddZedd Zd	S )r*   a"  
    LiteLLM integration for Sentry.

    This integration automatically captures LiteLLM API calls and sends them to Sentry
    for monitoring and error tracking. It supports all 100+ LLM providers that LiteLLM
    supports, including OpenAI, Anthropic, Google, Cohere, and many others.

    Features:
    - Automatic exception capture for all LiteLLM calls
    - Token usage tracking across all providers
    - Provider detection and attribution
    - Input/output message capture (configurable)
    - Streaming response support
    - Cost tracking integration

    Usage:

    ```python
    import litellm
    import sentry_sdk

    # Initialize Sentry with the LiteLLM integration
    sentry_sdk.init(
        dsn="your-dsn",
        send_default_pii=True
        integrations=[
            sentry_sdk.integrations.LiteLLMIntegration(
                include_prompts=True  # Set to False to exclude message content
            )
        ]
    )

    # All LiteLLM calls will now be monitored
    response = litellm.completion(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": "Hello!"}]
    )
    ```

    Configuration:
    - include_prompts (bool): Whether to include prompts and responses in spans.
      Defaults to True. Set to False to exclude potentially sensitive data.
    r+   zauto.ai.Tc                 C   s
   || _ d S )N)r/   )selfr/   r   r   r   __init__   s   
zLiteLLMIntegration.__init__c                   C   sn   t jpg t _tt jvrt jt t jpg t _tt jvr"t jt t jp&g t _tt jvr5t jt dS dS )z(Set up LiteLLM callbacks for monitoring.N)r+   Zinput_callbackr:   rE   Zsuccess_callbackrL   Zfailure_callbackrR   r   r   r   r   
setup_once   s   


zLiteLLMIntegration.setup_onceN)T)	__name__
__module____qualname____doc__
identifierr   rT   staticmethodrU   r   r   r   r   r*      s    ,

r*   )typingr   r'   r   Zsentry_sdk.ai.monitoringr   Zsentry_sdk.ai.utilsr   r   r   Zsentry_sdk.constsr   Zsentry_sdk.integrationsr	   r
   Zsentry_sdk.scoper   Zsentry_sdk.utilsr   r   r   r   r+   ImportErrorr   r:   rL   rR   r*   r   r   r   r   <module>   s,    M<