1
1
package datadog .trace .llmobs .domain ;
2
2
3
+ import datadog .context .ContextScope ;
3
4
import datadog .trace .api .DDSpanTypes ;
4
5
import datadog .trace .api .llmobs .LLMObs ;
5
6
import datadog .trace .api .llmobs .LLMObsSpan ;
6
7
import datadog .trace .api .llmobs .LLMObsTags ;
7
8
import datadog .trace .bootstrap .instrumentation .api .AgentSpan ;
9
+ import datadog .trace .bootstrap .instrumentation .api .AgentSpanContext ;
8
10
import datadog .trace .bootstrap .instrumentation .api .AgentTracer ;
9
11
import datadog .trace .bootstrap .instrumentation .api .Tags ;
10
12
import java .util .Collections ;
@@ -29,13 +31,15 @@ public class DDLLMObsSpan implements LLMObsSpan {
29
31
private static final String OUTPUT = LLMOBS_TAG_PREFIX + "output" ;
30
32
private static final String SPAN_KIND = LLMOBS_TAG_PREFIX + Tags .SPAN_KIND ;
31
33
private static final String METADATA = LLMOBS_TAG_PREFIX + LLMObsTags .METADATA ;
34
+ private static final String PARENT_ID_TAG_INTERNAL = "parent_id" ;
32
35
33
36
private static final String LLM_OBS_INSTRUMENTATION_NAME = "llmobs" ;
34
37
35
38
private static final Logger LOGGER = LoggerFactory .getLogger (DDLLMObsSpan .class );
36
39
37
40
private final AgentSpan span ;
38
41
private final String spanKind ;
42
+ private final ContextScope scope ;
39
43
40
44
private boolean finished = false ;
41
45
@@ -63,6 +67,20 @@ public DDLLMObsSpan(
63
67
if (sessionID != null && !sessionID .isEmpty ()) {
64
68
this .span .setTag (LLMOBS_TAG_PREFIX + LLMObsTags .SESSION_ID , sessionID );
65
69
}
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 ());
66
84
}
67
85
68
86
@ Override
@@ -271,6 +289,7 @@ public void finish() {
271
289
return ;
272
290
}
273
291
this .span .finish ();
292
+ this .scope .close ();
274
293
this .finished = true ;
275
294
}
276
295
}
0 commit comments