o
    i'`                     @   s  d dl mZ d dlZ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 ee Z!dZ"G dd de#Z$G dd de#Z%									dLdefddZ&dd Z'dd  Z(d!d" Z)d#d$ Z*d%d& Z+d'e,e-ef d(e	d)ee,e-ef  d*e-de.ee e/f f
d+d,Z0d'e,e-ef d(e	d)ee d*e-de.ee e/f f
d-d.Z1d'e,e-ef d(e	d)ee,e-ef  d*e-de.ee e/f f
d/d0Z2d'e,e-ef d(e	d)ee,e-ef  d*e-de.ee e/f f
d1d2Z3d'e,e-ef d(e	d)ee d*e-de.ee e/f f
d3d4Z4d'e,e-ef d(e	d)ee d*e-de.ee e/f f
d5d6Z5d'e,e-ef d(e	d)ee d*e-de.ee e/f f
d7d8Z6d9e,e-ef d*e-d:e7d(e	dee f
d;d<Z8d=e,e-ef d)ee d(e	dee fd>d?Z9d@e,e-ef d*e-d:e7d(e	dee f
dAdBZ:dCe,e-ef d*e-d:e7d(e	dee f
dDdEZ;dFe,e-ef d(e	d)ee dee fdGdHZ<e0e2e3e1e4e5e6dIZ=dJdK Z>dS )M    )timezoneN)Any)Literal)Optional)Span)
get_logger)generate_128bit_trace_id)format_trace_id)LLMOBS_TRACE_ID)parse_model_id)_get_ml_app)_get_session_id)	safe_json)LLMObsSpanEvent)Message)_ErrorField)_Meta)_MetaIO)
_SpanField    .Ac                   @      e Zd ZdZdS )"BedrockGuardrailTriggeredExceptionzMCustom exception to represent Bedrock Agent Guardrail Triggered trace events.N__name__
__module____qualname____doc__ r   r   _/home/ubuntu/.local/lib/python3.10/site-packages/ddtrace/llmobs/_integrations/bedrock_agents.pyr          r   c                   @   r   )BedrockFailureExceptionzACustom exception to represent Bedrock Agent Failure trace events.Nr   r   r   r   r   r    %   r   r    returnc                 C   s  |	d u rt  }	t|j}|t}|d u r|j}t|}t|}d| d| dg}| t|	t|t|p7|j|t	|p>|j
t	|pCt|rHdndtt|di t t t di t|	t||dd	}|
d urn|
|d
 d< |dkrtdnd}|d urd|d
 v r||d
 d |< |d urd|d
 v r||d
 d |< |d urd|d
 v r||d
 d d< |d urd|d
 v r||d
 d d< |S )Nzml_app:zsession_id:zintegration:bedrock_agentserrorok)kind)spanmetadatainputoutputr"   )span_idtrace_idapm_trace_id)namer)   r*   	parent_idtagsstart_nsdurationstatusmetametrics_ddr2   r&   llmmessagesvaluer'   r(   messagetype)r   r	   r*   _get_ctx_itemr
   r   r   strr)   intr/   DEFAULT_SPAN_DURATIONr   r   r   r   )	span_name	root_spanr-   	span_kindr/   duration_nsr"   	error_msg
error_typer)   r&   	input_val
output_valr+   llmobs_trace_id
session_idml_appr.   
span_eventio_keyr   r   r   _build_span_event+   sT   



rK   c                 C   s   |  di }|rt|trt|dkrdS tt| \}}|r&t|ts(dS d|v r5|dv r5| dS t|dkr=dS tt| \}}| dS )a"  Extracts the trace step ID from a Bedrock trace object.
    Due to the union structure of bedrock traces (only one key-value pair representing the actual trace object),
    some trace types have the trace step ID in the underlying trace object, while others have it in a nested object.
    trace   NtraceIdcustomOrchestrationTracefailureTraceguardrailTraceget
isinstancedictlennextiteritemsbedrock_trace_obj
trace_part
trace_type_r   r   r   _extract_trace_step_idh   s   

r`   c                 C   sB   |  di }|rt|trt|dkrdS tt| \}}|S )z_Extracts the first key from a Bedrock trace object, which represents the underlying trace type.rL   rM   NrS   r[   r   r   r   _extract_trace_type{   s
   ra   c                 C   s:   |  d}|r|jtjd d }t|S |j}t|S )N	eventTimetzinfo    eArT   replacer   utc	timestampr/   r<   )r\   r?   r/   r   r   r   _extract_start_ns   s   
rj   c                 C   sL   |  d}|r|jtjd d }n|j}|  ddd }t|t|fS )zeExtracts the start time and duration from the Bedrock trace metadata (non-orchestration trace types).	startTimerc   re   totalTimeMsrM   r   rf   )bedrock_metadatar?   r/   rA   r   r   r   )_extract_start_and_duration_from_metadata   s   
rn   c           	   	   C   s  t | pd}||}|s.|s|jn|d|j}td|||jd||d|id}|||< |di di }|sR|rR|di drR|di d|d d< |rj|di d	rj|di d	|d d	< |rv|drv|d
sx|S t|d
 |d  |d  |d
< |S )zCreates/updates a Bedrock trace step span based on the provided trace and inner span event.
    Sets the trace step span's input from the first inner span event, and the output from the last inner span event.
    zBedrock Agentr/   z{} Stepworkflowbedrock_trace_id)r>   r?   r-   r@   r/   r)   r&   r2   r'   r(   r0   )ra   rT   r/   rK   formatr)   r<   )	rL   trace_step_idinner_span_eventr?   	span_dictr^   rI   r/   trace_step_inputr   r   r   )_create_or_update_bedrock_trace_step_span   s.   
	 rv   rL   r?   current_active_spanrr   c              
   C   s`   |  di  di }t| |}| di }|rt|tsdS td||d|| ddd	}|d
fS )zTranslates a custom orchestration bedrock trace into a LLMObs span event.
    Returns the translated span event and a boolean indicating if the trace is finished.
    rL   rP   eventNFcustomOrchestrationtasktext )r>   r?   r-   r@   r/   rE   F)rT   rj   rU   rV   rK   )rL   r?   rw   rr   custom_orchestration_tracer/   custom_orchestration_eventrI   r   r   r   %_translate_custom_orchestration_trace   s   

r   c                 C   s   |  di  di }t| |}| di }|r t||||dfS | di }|r0t|||dfS | di }|rAt||||dfS | di }	|	rRt|	|||dfS | d	i }
|
rgt|
trgt|
||dfS d
S )zTranslates an orchestration bedrock trace into a LLMObs span event.
    Returns the translated span event and a boolean indicating if the trace is finished.
    rL   orchestrationTracemodelInvocationInputFmodelInvocationOutputT	rationaleinvocationInputobservationry   )	rT   rj   _model_invocation_input_span_model_invocation_output_span_rationale_span_invocation_input_spanrU   rV   _observation_span)rL   r?   rw   rr   orchestration_tracer/   model_invocation_inputmodel_invocation_outputr   invocation_inputr   r   r   r   _translate_orchestration_trace   s$   
r   c                 C   s   |  di  di }| di }t||\}}zt| dd ty/   |jt   Y nw | dd}| dd}	td||d||d	||	d
	}
|
d	fS )zTranslates a failure bedrock trace into a LLMObs span event.
    Returns the translated span event and a boolean indicating that the span is finished.
    rL   rQ   r&   failureReasonr}   failureTypefailureEventr{   T)	r>   r?   r-   r@   r/   rA   r"   rB   rC   )rT   rn   r    set_exc_infosysexc_inforK   )rL   r?   rw   rr   failure_tracefailure_metadatar/   rA   rB   rC   rI   r   r   r   _translate_failure_trace   s,   r   c                 C   s   |  di  di }| di }t||\}}| dd}|| dg | dg d}	t|d	k}
td
||d|||
|
r=dnd|
rBdndt|	d
}|
rcztd tyb   |jt   Y |dfS w |dfS )zTranslates a guardrail bedrock trace into a LLMObs span event.
    Returns the translated span event and a boolean indicating that the span is finished.
    rL   rR   r&   actionr}   inputAssessmentsoutputAssessments)r   r   r   
INTERVENED	guardrailr{   zGuardrail intervenedNGuardrailTriggered)
r>   r?   r-   r@   r/   rA   r"   rB   rC   rE   T)	rT   rn   boolrK   r   r   r   r   r   )rL   r?   rw   rr   guardrail_traceguardrail_metadatar/   rA   r   guardrail_outputguardrail_triggeredrI   r   r   r   _translate_guardrail_trace  s:   



r   c                 C   d   |  di  di }t| |}| di }|r t||||dfS | di }|r0t|||dfS dS )zTranslates a postprocessing bedrock trace into a LLMObs span event.
    Returns the translated span event and a boolean indicating if the span is finished.
    rL   postProcessingTracer   Fr   Try   rT   rj   r   r   )rL   r?   rw   rr   postprocessing_tracer/   r   r   r   r   r    _translate_post_processing_trace&     
r   c                 C   r   )zTranslates a preprocessing bedrock trace into a LLMObs span event.
    Returns the translated span event and a boolean indicating if the span is finished.
    rL   preProcessingTracer   Fr   Try   r   )rL   r?   rw   rr   preprocessing_tracer/   r   r   r   r   r   _translate_pre_processing_trace7  r   r   c           
      C   s   |  di  di }t| |}| di }|r t||||dfS | di }|r0t|||dfS | di }|rAt||||dfS | di }	|	rVt|	trVt|	||dfS d	S )
zTranslates a routing classifier bedrock trace into a LLMObs span event.
    Returns the translated span event and a boolean indicating if the span is finished.
    rL   routingClassifierTracer   Fr   Tr   r   ry   )rT   rj   r   r   r   rU   rV   r   )
rL   r?   rw   rr   routing_tracer/   r   r   r   r   r   r   r   #_translate_routing_classifier_traceH  s   
r   model_inputr/   c              	   C   s   |  dd}t|\}}zt|  dd}W n tjtfy*   td i }Y nw t| ddddg}| dg D ]}	|	t|	 d	d|	 d
dd q<t
d||d|||d|d}
|
S )zKTranslates a Bedrock model invocation input trace into a LLMObs span event.foundationModelr}   r|   z{}z"Failed to decode model input text.systemcontentroler6   r   r   modelInvocationr5   )
model_namemodel_provider)r/   r&   rD   )rT   r   jsonloadsJSONDecodeErrorUnicodeDecodeErrorlogwarningr   appendrK   )r   rr   r/   r?   model_idr   r   r|   input_messagesr8   rI   r   r   r   r   _  s*   
$	r   model_outputc                 C   s,  |s	t d dS | di }t||\}}g }| di }|r.|tt|p(ddd n| di d	d}|t|dd | d
i di }	|	rad|d v rat|	dd|d d d< |di dd|di ddd}
t||d< t||d< d|d v r||d d d< |
|d< |S )zLTranslates a Bedrock model invocation output trace into a LLMObs span event.z*Error in processing modelInvocationOutput.Nr&   parsedResponser}   	assistantr   rawResponser   reasoningContentreasoningTextr2   r|   usageinputTokensr   outputTokens)input_tokensoutput_tokensr/   r0   r(   r6   r3   )	r   r   rT   rn   r   r   r   r;   r<   )r   rw   r?   rm   r/   rA   output_messagesparsed_responseraw_responsereasoning_texttoken_metricsr   r   r   r   y  s.   
r   r   c              
   C   s    t d||d|| ddd}|S )z>Translates a Bedrock rationale trace into a LLMObs span event.	reasoningr{   r|   r}   )r/   rE   )rK   rT   )r   rr   r/   r?   rI   r   r   r   r     s   r   r   c              	   C   s:  d}i }i }|  dd}|dkr6|  di }| d}| di }	dd |	D }| d	d| d
dd}nX|dkrT|  di }| d}dt| di  ddi}n:|dkru|  di }| d}t| ddt| ddd}n|dkr|  di }| d}dt| ddi}t|||d||t|d}
|
S )zETranslates a Bedrock invocation input trace into a LLMObs span event.r}   invocationTypeACTION_GROUPactionGroupInvocationInputactionGroupName
parametersc                 S   s   i | ]}|d  t |d qS )r,   r7   )r;   ).0argr   r   r   
<dictcomp>  s    z*_invocation_input_span.<locals>.<dictcomp>functionexecutionType)r   execution_typeAGENT_COLLABORATOR agentCollaboratorInvocationInputagentCollaboratorNamer|   r'   ACTION_GROUP_CODE_INTERPRETERcodeInterpreterInvocationInputcodefiles)r   r   KNOWLEDGE_BASEknowledgeBaseLookupInputknowledgeBaseIdtool)r&   rD   )rT   r;   rK   r   )r   rr   r/   r?   r>   tool_metadata	tool_argsinvocation_typebedrock_tool_callparamsrI   r   r   r   r     s8   




$
r   r   c           	      C   s>  |  dd}|dv rdS |std dS d}i }|dkr0|  di }| di }| d	d}nL|d
krK|  di }| di }| di  d	d}n1|dkrf|  di }| di }| di  d	d}n|dkr||  di }| di }| dd}t||\}}t||d< t||d< d|d v r||d d d< |S )z@Translates a Bedrock observation trace into a LLMObs span event.r9   r}   )FINISHREPROMPTNz Error in processing observation.r   actionGroupInvocationOutputr&   r|   r   !agentCollaboratorInvocationOutputr(   r   knowledgeBaseLookupOutputretrievedReferencesr   codeInterpreterInvocationOutputexecutionOutputr/   r0   r2   r7   )rT   r   r   rn   r<   )	r   r?   rw   observation_typeoutput_valuerm   output_chunkr/   rA   r   r   r   r     s<   
r   )rP   rQ   rR   r   r   r   r   c           	      C   s   t | pd}|tvrtd||  dS | di |i }|r$t|ts-td||  dS |dvr@t|dkr@td||  dS t| }|| |||\}}||fS )zTranslates a Bedrock trace into a LLMObs span event.
    Routes the trace to the appropriate translation method based on the trace type.
    Returns the translated span event and a boolean indicating if the span is finished.
    r}   z0Unsupported trace type '%s' in Bedrock trace: %sry   rL   z/Invalid trace structure for trace type '%s': %srO   rM   )ra   'BEDROCK_AGENTS_TRACE_CONVERSION_METHODSr   r   rT   rU   rV   rW   )	rL   r?   current_active_span_eventrr   r^   nested_trace_dicttranslation_methodtranslated_span_eventfinishedr   r   r   translate_bedrock_trace  s   r  )	NNNNNNNNN)?datetimer   r   r   typingr   r   r   ddtrace._trace.spanr   ddtrace.internal.loggerr   ddtrace.internal.nativer   ddtrace.internal.utils.formatsr	   ddtrace.llmobs._constantsr
   *ddtrace.llmobs._integrations.bedrock_utilsr   ddtrace.llmobs._utilsr   r   r   ddtrace.llmobs._writerr   ddtrace.llmobs.typesr   r   r   r   r   r   r   r=   	Exceptionr   r    rK   r`   ra   rj   rn   rv   rV   r;   tupler   r   r   r   r   r   r   r   r<   r   r   r   r   r   r   r  r   r   r   r   <module>   sf   
=		







$









 




#

(