
    fi#                        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rd d
l mZmZ d dlmZ 	 d dlZn# e$ r  ed          w xY wd Zd Zd Zd Z G 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                 n    |                      di           }|                    d          }|i }||d<   |S )z,Get the metadata dictionary from the kwargs.litellm_paramsmetadata)
setdefaultget)kwargsr   r   s      o/var/www/html/Pagina-Ingenieria-Requisitos/venv/lib/python3.11/site-packages/sentry_sdk/integrations/litellm.py_get_metadata_dictr      sI     &&'7<<N !!*--H%-z"O    c                 h   t          j                                        t                    }|dS |                     dd          }	 t          j        |          \  }}}}n# t          $ r |}d}Y nw xY w|                     dd          }|dk    rd}nd} t                      |dk    rt          j
        j        nt          j
        j        | d	| t          j        
          }|                                 |t          |           d<   t!          |t"          j        |           t!          |t"          j        |           |                     dg           }	|	rXt)                      rJ|j        rCt          j                    }
t/          |	||
          }|t!          |t"          j        |d           t"          j        t"          j        t"          j        t"          j        t"          j        t"          j        t"          j        d}|                                 D ]-\  }}|                     |          }|t!          |||           .|                     d          |                     d          |                     d          d}|                                 D ]\  }}|t!          |d| |           dS )zHandle the start of a request.Nmodel unknown	call_type	embedding
embeddingschat )opnameorigin_sentry_spanmessagesF)unpack)r   stream
max_tokenspresence_penaltyfrequency_penaltytemperaturetop_papi_baseapi_versioncustom_llm_provider)r/   r0   r1   zgen_ai.litellm.)!
sentry_sdk
get_clientget_integrationLiteLLMIntegrationr   litellmget_llm_provider	Exceptionr   r   OPGEN_AI_CHATGEN_AI_EMBEDDINGSr%   	__enter__r   r   r	   GEN_AI_SYSTEMGEN_AI_OPERATION_NAMEr   include_promptsget_current_scoper   GEN_AI_REQUEST_MESSAGESGEN_AI_REQUEST_MODELGEN_AI_RESPONSE_STREAMINGGEN_AI_REQUEST_MAX_TOKENSGEN_AI_REQUEST_PRESENCE_PENALTY GEN_AI_REQUEST_FREQUENCY_PENALTYGEN_AI_REQUEST_TEMPERATUREGEN_AI_REQUEST_TOP_Pitems)r   integration
full_modelr   provider_r   	operationspanr'   scopemessages_dataparamskey	attributevaluer   s                    r   _input_callbackrV   '   s    '))99:LMMK GR((J ' 8 D DxAA    

;--IK 			 %"$$ F"" I!!,##E##!(  D 	NN 26v~. h4h???h<iHHH zz*b))H +-- +2M ,..6xuMM$h6e    .48$D%F:. F !,,.. 8 8Y

3i777 JJz**zz-00%zz*?@@ N
 %**,, F F
U&=&=&=uEEEF Fs   A! !A21A2c           
         t          |                               d          }|dS t          j                                        t
                    }|dS 	 t          |d          r t          |t          j	        |j
                   t                      r\|j        rTt          |d          rCg }|j        D ]}t          |d          rt          |j        d          r-|                    |j                                                   Vt          |j        d          r-|                    |j                                                   i }t          |j        d          r|j        j        |d<   t          |j        d	          r|j        j        |d	<   t          |j        d
          r|j        j        |d
<   |                    |           |rt          |t          j        |           t          |d          rG|j        }	t/          |t1          |	dd          t1          |	dd          t1          |	dd                     |                    ddd           dS # |                    ddd           w xY w)zHandle successful completion.r&   Nr   choicesmessage
model_dumpdictrolecontent
tool_callsusageprompt_tokenscompletion_tokenstotal_tokens)input_tokensoutput_tokensrb   )r   r   r2   r3   r4   r5   hasattrr   r	   GEN_AI_RESPONSE_MODELr   r   r?   rX   rY   appendrZ   r[   r\   r]   r^   GEN_AI_RESPONSE_TEXTr_   r   getattr__exit__)
r   completion_response
start_timeend_timerO   rJ   response_messageschoicemsgr_   s
             r   _success_callbackrq   t   s    f%%)).99D|'))99:LMMK-(&00 	h46I6O  
 #$$ 	)D 	*I66 $&!19 : :Fvy11 :"6><@@ :-44V^5N5N5P5PQQQQ$V^V<< :-44V^5H5H5J5JKKKK #%C&v~v>> B.4n.AF&v~yAA H171GI&v~|DD N4:N4ML 1-44S999$ 'h;=N  
 &00 	'-E$UOTBB%e-@$GG$UNDAA	    	dD$'''''dD$''''s   G2I" "I;c                 v   t          |                               d          }|dS 	 t          |t          j                    j        ddd          \  }}t          j        ||           |                    t          |          |d           dS # |                    t          |          |d           w xY w)zHandle request failure.r&   Nr6   F)typehandled)client_options	mechanism)hint)	r   r   r   r2   r3   optionscapture_eventrj   rs   )r   	exceptionrl   rm   rO   eventrw   s          r   _failure_callbackr|      s     f%%)).99D|
8*%022:(U;;
 
 
t
 	 T2222 	d9ooy$77777d9ooy$7777s   AB &B8c                   >    e Zd ZdZdZde ZddZed             ZdS )	r5   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.
    r6   zauto.ai.Tc                     || _         d S )N)r?   )selfr?   s     r   __init__zLiteLLMIntegration.__init__   s    .r   c                     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r&t           j                            t                     dS dS )z(Set up LiteLLM callbacks for monitoring.N)r6   input_callbackrV   rg   success_callbackrq   failure_callbackr|    r   r   
setup_oncezLiteLLMIntegration.setup_once   s     ")!7!=2'"888"))/:::#*#;#Ar G$<<<$++,=>>>#*#;#Ar G$<<<$++,=>>>>> =<r   N)T)	__name__
__module____qualname____doc__
identifierr%   r   staticmethodr   r   r   r   r5   r5      sb        * *X J$
$$F/ / / / ? ? \? ? ?r   r5   )typingr   r2   r   sentry_sdk.ai.monitoringr   sentry_sdk.ai.utilsr   r   r   sentry_sdk.constsr	   sentry_sdk.integrationsr
   r   sentry_sdk.scoper   sentry_sdk.utilsr   r   r   r   r6   ImportErrorr   rV   rq   r|   r5   r   r   r   <module>r      s                         7 7 7 7 7 7         
 ' & & & & & = = = = = = = = 4 4 4 4 4 4 1 1 1 1 1 1 "        !!!!!!0NNNN 0 0 0
,.
/
//0
 
 
JF JF JFZ9( 9( 9(x8 8 8(B? B? B? B? B? B? B? B? B? B?s   A A"