11package datadog .trace .llmobs .domain ;
22
3+ import datadog .context .ContextScope ;
34import datadog .trace .api .DDSpanTypes ;
45import datadog .trace .api .llmobs .LLMObs ;
56import datadog .trace .api .llmobs .LLMObsSpan ;
67import datadog .trace .api .llmobs .LLMObsTags ;
78import datadog .trace .bootstrap .instrumentation .api .AgentSpan ;
9+ import datadog .trace .bootstrap .instrumentation .api .AgentSpanContext ;
810import datadog .trace .bootstrap .instrumentation .api .AgentTracer ;
911import datadog .trace .bootstrap .instrumentation .api .Tags ;
1012import java .util .Collections ;
@@ -29,13 +31,15 @@ public class DDLLMObsSpan implements LLMObsSpan {
2931 private static final String OUTPUT = LLMOBS_TAG_PREFIX + "output" ;
3032 private static final String SPAN_KIND = LLMOBS_TAG_PREFIX + Tags .SPAN_KIND ;
3133 private static final String METADATA = LLMOBS_TAG_PREFIX + LLMObsTags .METADATA ;
34+ private static final String PARENT_ID_TAG_INTERNAL = "parent_id" ;
3235
3336 private static final String LLM_OBS_INSTRUMENTATION_NAME = "llmobs" ;
3437
3538 private static final Logger LOGGER = LoggerFactory .getLogger (DDLLMObsSpan .class );
3639
3740 private final AgentSpan span ;
3841 private final String spanKind ;
42+ private final ContextScope scope ;
3943
4044 private boolean finished = false ;
4145
@@ -63,6 +67,20 @@ public DDLLMObsSpan(
6367 if (sessionId != null && !sessionId .isEmpty ()) {
6468 this .span .setTag (LLMOBS_TAG_PREFIX + LLMObsTags .SESSION_ID , sessionId );
6569 }
70+
71+ AgentSpanContext parent = LLMObsState .getLLMObsParentContext ();
72+ String parentSpanID = LLMObsState .ROOT_SPAN_ID ;
73+ if (null != parent ) {
74+ if (parent .getTraceId () != this .span .getTraceId ()) {
75+ LOGGER .error ("trace ID mismatch, retrieved parent from context trace_id={}, span_id={}, started span trace_id={}, span_id={}" , parent .getTraceId (), parent .getSpanId (), this .span .getTraceId (), this .span .getSpanId ());
76+ } else {
77+ parentSpanID = String .valueOf (parent .getSpanId ());
78+ }
79+ }
80+ this .span .setTag (
81+ LLMOBS_TAG_PREFIX + PARENT_ID_TAG_INTERNAL , parentSpanID );
82+ this .scope = LLMObsState .attach ();
83+ LLMObsState .setLLMObsParentContext (this .span .context ());
6684 }
6785
6886 @ Override
@@ -271,6 +289,7 @@ public void finish() {
271289 return ;
272290 }
273291 this .span .finish ();
292+ this .scope .close ();
274293 this .finished = true ;
275294 }
276295}
0 commit comments