
    tni'              
       2   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dZddZ	 	 	 	 	 	 	 	 	 	 ddZdddeddddddf
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 installedkwargsDict[str, Any]returnc                 n    |                      di           }|                    d          }|i }||d<   |S )z,Get the metadata dictionary from the kwargs.litellm_paramsmetadata)
setdefaultget)r   r   r   s      \/var/www/html/gpu-tools/venv/lib/python3.11/site-packages/sentry_sdk/integrations/litellm.py_get_metadata_dictr      sG    &&'7<<N !!*--H%-z"O    c                 ^   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        |           t)                      r|j        r|dk    ru|                     d          }	|	r]t          j                    }
t/          |	t0                    r|	n|	g}t3          |||
          }|t!          |t"          j        |d           n[|                     dg           }|rCt          j                    }
t3          |||
          }|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inputF)unpackmessages)r   stream
max_tokenspresence_penaltyfrequency_penaltytemperaturetop_papi_baseapi_versioncustom_llm_provider)r2   r3   r4   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_scope
isinstancelistr   GEN_AI_EMBEDDINGS_INPUT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spanembedding_inputscope
input_listmessages_datar+   paramskey	attributevaluer   s                      r   _input_callbackr^   &   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     [%@  $$$jj11O "466 "/488+OO)* 
 !?z4QV W W ,' 8%$	    zz*b11H 	"466 >xu U U ,' 8%$	    .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completion_responser   
start_timer   end_timec           
         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_tokensrm   )r   r   r5   r6   r7   r8   hasattrr   r	   GEN_AI_RESPONSE_MODELr   r   rB   rc   rd   appendre   rf   rg   rh   ri   GEN_AI_RESPONSE_TEXTrj   r   getattr__exit__)
r   r_   r`   ra   rU   rP   response_messageschoicemsgrj   s
             r   _success_callbackry      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;	exceptionc                 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(   Nr9   F)typehandled)client_options	mechanism)hint)	r   r   r   r5   r6   optionscapture_eventru   r|   )r   rz   r`   ra   rU   eventr   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                   N    e Zd ZdZdZde Zddd deddfd	Zedd
            Z	dS )r8   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.
    r9   zauto.ai.TselfrB   r   Nc                     || _         d S )N)rB   )r   rB   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)r9   input_callbackr^   rr   success_callbackry   failure_callbackr    r   r   
setup_oncezLiteLLMIntegration.setup_once  s     ")!7!=2'"888"))/:::#*#;#Ar G$<<<$++,=>>>#*#;#Ar G$<<<$++,=>>>>> =<r   )T)r   N)
__name__
__module____qualname____doc__
identifierr'   boolr   staticmethodr   r   r   r   r8   r8      s        * *X J$
$$F/ /+ /d /d / / / / ? ? ? \? ? ?r   r8   )r   r   r   r   )r   r   r   N)
r   r   r_   r   r`   r   ra   r   r   N)typingr   r5   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   r9   ImportErrorr   r^   ry   r;   r   r8   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	 	 	 	bF bF bF bFJ=(=(=( =( 	=(
 
=( =( =( =(@888 8 	8
 
8 8 8 80@? @? @? @? @? @? @? @? @? @?s   A A"