
    `i-              
       b   d dl Z 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
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mZ d dlmZ 	 d dlZd dlmZmZmZ n# e$ r  ed          w xY wd dZ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 )$    N)TYPE_CHECKING)consts)record_token_usage)get_start_span_functionset_data_normalizedtruncate_and_annotate_messagestransform_openai_content_part&truncate_and_annotate_embedding_inputs)SPANDATA)DidNotEnableIntegration)should_send_default_pii)event_from_exception)AnyDictList)datetime)input_callbacksuccess_callbackfailure_callbackz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      s/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/sentry_sdk/integrations/litellm.py_get_metadata_dictr       sG    &&'7<<N !!*--H%-z"O    messagesList[Dict[str, Any]]c                    t          j        |           } | D ]}t          |t                    s|                    d          }t          |t
          t          f          r_g }|D ]U}t          |t                    r)t          |          }|                    ||n|           @|                    |           V||d<   | S )z
    Convert the message parts from OpenAI format to the `gen_ai.request.messages` format
    using the OpenAI-specific transformer (LiteLLM uses OpenAI's message format).

    Deep copies messages to avoid mutating original kwargs.
    content)	copydeepcopy
isinstancedictr   listtupler	   append)r"   messager%   transformeditemresults         r   _convert_message_partsr1   *   s     }X&&H - -'4(( 	++i((ge}-- 		-K - -dD)) -:4@@F&&1CvvNNNN&&t,,,,!,GIOr!   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           nj|                     dg           }|rRt          j                    }
t7          |          }t9          |||
          }|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)unpackr"   )r3   stream
max_tokenspresence_penaltyfrequency_penaltytemperaturetop_papi_baseapi_versioncustom_llm_provider)rG   rH   rI   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(   r*   r
   GEN_AI_EMBEDDINGS_INPUTr1   r   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_modelr3   provider_r6   	operationspanembedding_inputscope
input_listmessages_datar"   paramskey	attributevaluer   s                      r   _input_callbackrq   E   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)* 
 !Ge! ! !,' 8%$	    zz*b11H 
"4661(;; >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>   Nr3   choicesr-   
model_dumpr)   roler%   
tool_callsusageprompt_tokenscompletion_tokenstotal_tokens)input_tokensoutput_tokensr}   )r    r   rJ   rK   rL   rM   hasattrr   r   GEN_AI_RESPONSE_MODELr3   r   rW   rv   r-   r,   rw   r)   rx   r%   ry   GEN_AI_RESPONSE_TEXTrz   r   getattr__exit__)
r   rr   rs   rt   rh   rc   response_messageschoicemsgrz   s
             r   _success_callbackr      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>   NrN   F)typehandled)client_options	mechanism)hint)	r    r   r   rJ   rK   optionscapture_eventr   r   )r   r   rs   rt   rh   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 )rM   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.
    rN   zauto.ai.TselfrW   r   Nc                     || _         d S )N)rW   )r   rW   s     r   __init__zLiteLLMIntegration.__init__5  s    .r!   c                     t           pg t          _         t          t          j         vr$t          j                             t                     t          pg t          _        t
          t          j        vr$t          j                            t
                     t          pg t          _        t          t          j        vr&t          j                            t                     dS dS )z(Set up LiteLLM callbacks for monitoring.N)r   rN   rq   r,   r   r   r   r    r!   r   
setup_oncezLiteLLMIntegration.setup_once8  s     "0!52'"888"))/:::#3#9r G$<<<$++,=>>>#3#9r G$<<<$++,=>>>>> =<r!   )T)r   N)
__name__
__module____qualname____doc__
identifierr=   boolr   staticmethodr   r   r!   r   rM   rM     s        * *X J$
$$F/ /+ /d /d / / / / ? ? ? \? ? ?r!   rM   )r   r   r   r   )r"   r#   r   r#   )r   r   r   N)
r   r   rr   r   rs   r   rt   r   r   N)&r&   typingr   rJ   r   sentry_sdk.ai.monitoringr   sentry_sdk.ai.utilsr   r   r   r	   r
   sentry_sdk.constsr   sentry_sdk.integrationsr   r   sentry_sdk.scoper   sentry_sdk.utilsr   r   r   r   r   rN   r   r   r   ImportErrorr    r1   rq   r   rP   r   rM   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NNNJJJJJJJJJJJ 0 0 0
,.
/
//0	 	 	 	   6eF eF eF eFP=(=(=( =( 	=(
 
=( =( =( =(@888 8 	8
 
8 8 8 80@? @? @? @? @? @? @? @? @? @?s   A% %A6