o
    i4+                     @   sl  d dl 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
 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 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 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e$Z%dZ&G dd deZ'dS )     N)Any)Iterable)Optional)Union)
get_logger)"CACHE_READ_INPUT_TOKENS_METRIC_KEY)#CACHE_WRITE_INPUT_TOKENS_METRIC_KEY)INPUT_MESSAGES)INPUT_TOKENS_METRIC_KEY)METADATA)METRICS)
MODEL_NAME)MODEL_PROVIDER)OUTPUT_MESSAGES)OUTPUT_TOKENS_METRIC_KEY)PROXY_REQUEST)	SPAN_KIND)TOOL_DEFINITIONS)TOTAL_TOKENS_METRIC_KEY)BaseLLMIntegration)(update_proxy_workflow_input_output_value)	_get_attr)Message)ToolCall)ToolDefinition)
ToolResult)Spananthropic.request.modelc                   @   s0  e Zd ZdZ		d dedee dee deeef ddf
dd	Z			
d!dede
e deeef dee deddfddZ	d"de
eeef  deeee
eeef  f  de
e fddZdefddZde
e fddZdedeeef fddZdeeef dee fddZdee de
e fddZdS )#AnthropicIntegration	anthropicNspanmodelapi_keykwargsreturnc                 K   s   |dur| t| dS dS )zYSet base level tags that should be present on all Anthropic spans (if they are not None).N)_set_tag_strMODEL)selfr    r!   r"   r#    r(   Z/home/ubuntu/.local/lib/python3.10/site-packages/ddtrace/llmobs/_integrations/anthropic.py_set_base_span_tags)   s   z(AnthropicIntegration._set_base_span_tags argsresponse	operationc                 C   s  i }| dr| d|d< | dr| d|d< | dr-| | d}|t| | d}| d}	| |r?t|ng |	}
tddg}|jsU|durU| |}|	t
r\d	nd
}t|di }|d	krn| ||ni }|t|t|dp{dtdt|
t|t|t|i t|| dS )zZExtract prompt/response tags from a completion and set them as temporary "_ml_obs.*" tags.temperature
max_tokenstoolsmessagessystemr+   )contentNworkflowllmusager   r   )get_extract_tools_set_ctx_itemr   _extract_input_messagelistr   error_extract_output_message_get_ctx_itemr   r   _extract_usage_set_ctx_itemsr   r   get_tagr   r	   r   r   r   r   )r'   r    r,   r#   r-   r.   
parametersr1   r2   system_promptinput_messagesoutput_messages	span_kindr7   metricsr(   r(   r)   _llmobs_set_tags4   s8   	





z%AnthropicIntegration._llmobs_set_tagsr2   rD   c                 C   s.  t |ts
td g }|dur|ddg| }|D ]}t |ts'td qt|dd}t|dd}|du s;|du r@td t |trQ|t|t|d qt |t	r|D ]}t|d	dd
kru|ttt|d
dt|d qYt|d	ddkr|tdt|d qYt|d	ddkrt|d
d}t|dd}	t |	trt
|	}	ttt|dd|	tt|ddtt|d	dd}
|du rd}|tt|t||
gd qYt|d	ddkrt|dd}| |}t|tt|dddd}|tdt||gd qY|tt|t|d qYq|S )zExtract input messages from the stored prompt.
        Anthropic allows for messages and multiple texts in a message, which requires some special casing.
        z+Anthropic input must be a list of messages.Nr3   r4   rolez>Anthropic message input must be a list of message param dicts.r4   rK   z3Anthropic input message must have content and role.typetextr+   image([IMAGE DETECTED])tool_useinputnameidrR   	argumentstool_idrL   r4   rK   
tool_callstool_resulttool_use_id)resultrV   rL   )r4   rK   tool_results)
isinstancer   logwarningdictr   strappendr   r<   jsonloadsr   _format_tool_result_contentr   )r'   r2   rD   rE   messager4   rK   blockrM   
input_datatool_call_infoformatted_contenttool_result_infor(   r(   r)   r;   ^   s^   





$

 
z+AnthropicIntegration._extract_input_messagec                 C   sv   t |tr|S t |tr7g }|D ]!}t|dddkr$|t|dd qt|dd dkr1|d qd|S t|S )NrM   r+   rL   rN   rO   ,)r]   ra   r   r   rb   join)r'   r4   rj   tool_result_blockr(   r(   r)   re      s   



z0AnthropicIntegration._format_tool_result_contentc           	   
   C   s  g }t |dd}t |dd}t|trt|t|dgS t|tr|D ]`}t |dd}t|tr<|t|t|d q#t |dddkrt |d	d}t|trTt|}ttt |d
d|tt |ddtt |ddd}|du rtd}|tt|t||gd q#|S )z1Extract output messages from the stored response.r4   r+   rK   rJ   rM   NrL   rP   rQ   rR   rS   rT   rW   )	r   r]   ra   r   r<   rb   rc   rd   r   )	r'   r-   rF   r4   rK   
completionrM   rh   ri   r(   r(   r)   r>      s2   




z,AnthropicIntegration._extract_output_messager7   c                 C   s   |sd S t |dd }t |dd }t |dd }t |dd }i }|p!d|p$d |p(d |t< |d ur4||t< t|v rD|d urD|t | |t< |d urL||t< |d urT||t< |S )Ninput_tokensoutput_tokenscache_creation_input_tokenscache_read_input_tokensr   )r   r
   r   r   r   r   )r'   r    r7   rp   rq   cache_write_tokenscache_read_tokensrH   r(   r(   r)   r@      s"   z#AnthropicIntegration._extract_usagec                 K   s:   | d}t|dd }|rt|dd nd }|rt|S d S )Ninstance_client	_base_url)r8   getattrra   )r'   r#   rv   clientbase_urlr(   r(   r)   _get_base_url   s   
z"AnthropicIntegration._get_base_urlr1   c                 C   sJ   |sg S g }|D ]}t |dd|dd|di d}|| q|S )NrR   r+   descriptioninput_schema)rR   r}   schema)r   r8   rb   )r'   r1   tool_definitionstooltool_defr(   r(   r)   r9      s   z#AnthropicIntegration._extract_tools)NN)Nr+   )N)__name__
__module____qualname___integration_namer   r   ra   r`   r   r*   r<   rI   r   r   r;   re   r>   r@   r|   r   r9   r(   r(   r(   r)   r   &   sV    



+
Ar   )(rc   typingr   r   r   r   ddtrace.internal.loggerr   ddtrace.llmobs._constantsr   r   r	   r
   r   r   r   r   r   r   r   r   r   r   !ddtrace.llmobs._integrations.baser   "ddtrace.llmobs._integrations.utilsr   ddtrace.llmobs._utilsr   ddtrace.llmobs.typesr   r   r   r   ddtrace.tracer   r   r^   r&   r   r(   r(   r(   r)   <module>   s>    