Skip to main content

strands/telemetry/
tracer.rs

1//! Spans and local execution traces.
2//!
3//! Spans are `tracing` spans (`invoke_agent <name>` through the `otel.name` field,
4//! `execute_agent_loop_cycle`, `chat`, `execute_tool <tool>`) with fields named after their
5//! attributes, so `tracing-opentelemetry` exports the span names and attributes the other Strands
6//! SDKs export. The [`AgentTrace`] tree is collected whether or not anything records the spans.
7
8mod memory;
9mod parts;
10
11use std::collections::BTreeMap;
12use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
13
14use serde::{Deserialize, Serialize};
15use serde_json::json;
16use tracing::Span;
17use tracing::field::Empty;
18
19pub(crate) use self::memory::{
20    AgentSpanContext, EndMemoryAddSpanOptions, EndMemoryExtractSpanOptions, EndMemoryInjectSpanOptions,
21    EndMemorySearchSpanOptions, StartMemoryAddSpanOptions, StartMemoryExtractSpanOptions, StartMemoryInjectSpanOptions,
22    StartMemorySearchSpanOptions,
23};
24use self::parts::{
25    event_name_for_message, message_text, otel_messages, otel_parts, stable_parts, system_prompt_otel_parts,
26    system_prompt_stable, to_json,
27};
28use super::span::{Attributes, add_event, end_span, exports, record_attributes, start_span};
29use super::types::AttributeValue;
30use super::utils::{TracerSettings, now_ms};
31use crate::models::streaming::{Metrics, Usage};
32use crate::types::{JsonObject, JsonValue, Message, SystemPrompt, ToolResultBlock, ToolResultStatus, ToolUse};
33
34const TARGET: &str = "strands::telemetry";
35const OPERATION_DETAILS: &str = "gen_ai.client.inference.operation.details";
36
37/// A node in the local timing tree of an invocation (`AgentTrace`).
38///
39/// Collected whether or not OpenTelemetry is configured. Serializes with `null` for an absent
40/// parent, end time or message.
41///
42/// ```
43/// use strands::telemetry::AgentTrace;
44///
45/// let mut cycle = AgentTrace::new("Cycle 1", 1_000);
46/// cycle.add_child(AgentTrace::new("stream_messages", 1_001)).end(1_100);
47/// cycle.end(1_200);
48/// assert_eq!(cycle.children[0].parent_id.as_deref(), Some(cycle.id.as_str()));
49/// assert_eq!(cycle.duration, 200);
50/// ```
51#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53#[non_exhaustive]
54pub struct AgentTrace {
55    /// Unique identifier (a UUID).
56    pub id: String,
57    /// Display name, such as `Cycle 1` or `Tool: calc`.
58    pub name: String,
59    /// The parent trace's id; `None` for a root trace.
60    pub parent_id: Option<String>,
61    /// Start time in milliseconds since the Unix epoch.
62    pub start_time: u64,
63    /// End time in milliseconds since the Unix epoch; `None` until the trace ends.
64    pub end_time: Option<u64>,
65    /// Duration in milliseconds.
66    pub duration: u64,
67    /// Nested traces.
68    pub children: Vec<AgentTrace>,
69    /// String metadata such as `cycleId`, `toolUseId` and `toolName`.
70    pub metadata: JsonObject,
71    /// The message associated with the trace, such as the model output.
72    pub message: Option<Message>,
73}
74
75impl AgentTrace {
76    /// Creates a root trace that starts at `start_time` (milliseconds since the epoch).
77    pub fn new(name: impl Into<String>, start_time: u64) -> Self {
78        Self {
79            id: uuid::Uuid::new_v4().to_string(),
80            name: name.into(),
81            parent_id: None,
82            start_time,
83            end_time: None,
84            duration: 0,
85            children: Vec::new(),
86            metadata: JsonObject::new(),
87            message: None,
88        }
89    }
90
91    /// Creates a root trace that starts now.
92    pub fn start(name: impl Into<String>) -> Self {
93        Self::new(name, now_ms())
94    }
95
96    /// Nests `child` under this trace and returns it.
97    pub fn add_child(&mut self, mut child: AgentTrace) -> &mut AgentTrace {
98        child.parent_id = Some(self.id.clone());
99        let index = self.children.len();
100        self.children.push(child);
101        &mut self.children[index]
102    }
103
104    /// Ends the trace at `end_time` and records its duration (`end`).
105    pub fn end(&mut self, end_time: u64) {
106        self.end_time = Some(end_time);
107        self.duration = end_time.saturating_sub(self.start_time);
108    }
109
110    /// Ends the trace now.
111    pub fn end_now(&mut self) {
112        self.end(now_ms());
113    }
114}
115
116/// Where a model or tool trace sits in the tree: a child, by id, of a cycle of one invocation.
117/// The id stays valid when a tool trace is inserted before it.
118#[derive(Debug, Clone)]
119struct TraceRef {
120    generation: u64,
121    cycle: usize,
122    child: String,
123}
124
125/// The local traces of the current invocation and the spans that parent the next ones.
126#[derive(Debug, Default)]
127struct TraceState {
128    /// Counts `invoke_agent` spans, so a trace handle from an earlier invocation finds nothing.
129    generation: u64,
130    traces: Vec<AgentTrace>,
131    current_cycle: Option<usize>,
132    agent_span: Option<Span>,
133    loop_span: Option<Span>,
134    /// The tool use ids of the current tool batch, in call order.
135    tool_order: Vec<String>,
136}
137
138impl TraceState {
139    fn cycle_child(&mut self, trace: Option<TraceRef>) -> Option<&mut AgentTrace> {
140        let trace = trace.filter(|trace| trace.generation == self.generation)?;
141        self.traces
142            .get_mut(trace.cycle)?
143            .children
144            .iter_mut()
145            .find(|child| child.id == trace.child)
146    }
147
148    /// The call index of a tool trace in the current batch.
149    fn tool_rank(&self, trace: &AgentTrace) -> Option<usize> {
150        let tool_use_id = trace.metadata.get("toolUseId")?.as_str()?;
151        self.tool_order.iter().position(|id| id == tool_use_id)
152    }
153}
154
155/// Creates the agent's spans and collects its local traces.
156#[derive(Debug)]
157pub(crate) struct Tracer {
158    settings: TracerSettings,
159    trace_attributes: Vec<(String, AttributeValue)>,
160    baggage_attributes: BTreeMap<String, String>,
161    state: Mutex<TraceState>,
162}
163
164impl Default for Tracer {
165    fn default() -> Self {
166        Self::new(BTreeMap::new(), BTreeMap::new())
167    }
168}
169
170/// Options for [`Tracer::start_agent_span`] (`StartAgentSpanOptions`).
171#[derive(Debug, Default, Clone, Copy)]
172pub(crate) struct StartAgentSpanOptions<'a> {
173    pub(crate) messages: &'a [Message],
174    pub(crate) agent_name: &'a str,
175    pub(crate) agent_id: Option<&'a str>,
176    pub(crate) model_id: Option<&'a str>,
177    pub(crate) tools: &'a [String],
178    pub(crate) trace_attributes: &'a [(String, AttributeValue)],
179    pub(crate) tools_config: Option<&'a JsonObject>,
180    pub(crate) system_prompt: Option<&'a SystemPrompt>,
181}
182
183/// Options for [`AgentSpan::end`] (`EndAgentSpanOptions`).
184#[derive(Debug, Default)]
185pub(crate) struct EndAgentSpanOptions<'a> {
186    pub(crate) response: Option<&'a Message>,
187    pub(crate) error: Option<String>,
188    pub(crate) accumulated_usage: Option<Usage>,
189    pub(crate) stop_reason: Option<&'a str>,
190}
191
192/// Options for [`Tracer::start_model_invoke_span`] (`StartModelInvokeSpanOptions`).
193#[derive(Debug, Default, Clone, Copy)]
194pub(crate) struct StartModelInvokeSpanOptions<'a> {
195    pub(crate) messages: &'a [Message],
196    pub(crate) model_id: Option<&'a str>,
197    pub(crate) system_prompt: Option<&'a SystemPrompt>,
198}
199
200/// Options for [`ModelSpan::end`] (`EndModelSpanOptions`).
201#[derive(Debug, Default, Clone, Copy)]
202pub(crate) struct EndModelSpanOptions<'a> {
203    pub(crate) usage: Option<&'a Usage>,
204    pub(crate) metrics: Option<&'a Metrics>,
205    pub(crate) error: Option<&'a str>,
206    pub(crate) output: Option<&'a Message>,
207    pub(crate) stop_reason: Option<&'a str>,
208}
209
210/// Options for [`ToolSpan::end`] (`EndToolCallSpanOptions`).
211#[derive(Debug, Default, Clone, Copy)]
212pub(crate) struct EndToolCallSpanOptions<'a> {
213    pub(crate) tool_result: Option<&'a ToolResultBlock>,
214    pub(crate) error: Option<&'a str>,
215}
216
217macro_rules! gen_ai_span {
218    ($parent:expr, $name:literal $(, $field:literal)* $(,)?) => {
219        match $parent {
220            Some(parent) => tracing::info_span!(
221                target: TARGET, parent: &parent, $name,
222                "otel.name" = Empty, "otel.status_code" = Empty, "otel.status_description" = Empty,
223                "gen_ai.event.start_time" = Empty, "gen_ai.event.end_time" = Empty,
224                $($field = Empty),*
225            ),
226            None => tracing::info_span!(
227                target: TARGET, $name,
228                "otel.name" = Empty, "otel.status_code" = Empty, "otel.status_description" = Empty,
229                "gen_ai.event.start_time" = Empty, "gen_ai.event.end_time" = Empty,
230                $($field = Empty),*
231            ),
232        }
233    };
234}
235
236macro_rules! usage_fields {
237    ($parent:expr, $name:literal $(, $field:literal)* $(,)?) => {
238        gen_ai_span!(
239            $parent, $name,
240            "gen_ai.usage.prompt_tokens", "gen_ai.usage.input_tokens", "gen_ai.usage.completion_tokens",
241            "gen_ai.usage.output_tokens", "gen_ai.usage.total_tokens", "gen_ai.usage.cache_read.input_tokens",
242            "gen_ai.usage.cache_read_input_tokens", "gen_ai.usage.cache_creation.input_tokens",
243            "gen_ai.usage.cache_write_input_tokens"
244            $(, $field)*
245        )
246    };
247}
248
249/// The `gen_ai.tool.definitions` entries: each tool's name, description and schemas, `null` for
250/// a schema the tool does not declare.
251fn tool_definitions(tools_config: &JsonObject) -> Vec<JsonValue> {
252    tools_config
253        .iter()
254        .map(|(name, spec)| {
255            let field = |key: &str| spec.get(key).cloned().unwrap_or(JsonValue::Null);
256            serde_json::json!({
257                "name": name,
258                "description": field("description"),
259                "inputSchema": field("inputSchema"),
260                "outputSchema": field("outputSchema"),
261            })
262        })
263        .collect()
264}
265
266impl Tracer {
267    /// A tracer with the conventions the environment selects (`OTEL_SEMCONV_STABILITY_OPT_IN`,
268    /// the Langfuse endpoints and `OTEL_SERVICE_NAME`).
269    pub(crate) fn new(
270        trace_attributes: BTreeMap<String, AttributeValue>,
271        baggage_attributes: BTreeMap<String, String>,
272    ) -> Self {
273        Self::with_settings(TracerSettings::from_env(), trace_attributes, baggage_attributes)
274    }
275
276    pub(crate) fn with_settings(
277        settings: TracerSettings,
278        trace_attributes: BTreeMap<String, AttributeValue>,
279        baggage_attributes: BTreeMap<String, String>,
280    ) -> Self {
281        Self {
282            settings,
283            trace_attributes: trace_attributes.into_iter().collect(),
284            baggage_attributes,
285            state: Mutex::new(TraceState::default()),
286        }
287    }
288
289    /// A tracer with the same settings and attributes and its own local traces, for work that
290    /// runs detached from the invocation (background tool calls).
291    pub(crate) fn detached(&self) -> Self {
292        Self {
293            settings: self.settings.clone(),
294            trace_attributes: self.trace_attributes.clone(),
295            baggage_attributes: self.baggage_attributes.clone(),
296            state: Mutex::new(TraceState::default()),
297        }
298    }
299
300    /// The attributes added to every span; subagent children inherit them.
301    pub(crate) fn trace_attributes(&self) -> BTreeMap<String, AttributeValue> {
302        self.trace_attributes.iter().cloned().collect()
303    }
304
305    /// The baggage entries every invocation runs under.
306    pub(crate) fn baggage_attributes(&self) -> &BTreeMap<String, String> {
307        &self.baggage_attributes
308    }
309
310    /// Whether agent spans record tool definitions (`gen_ai_tool_definitions`).
311    pub(crate) fn includes_tool_definitions(&self) -> bool {
312        self.settings.include_tool_definitions
313    }
314
315    /// The local traces of the latest invocation.
316    pub(crate) fn local_traces(&self) -> Vec<AgentTrace> {
317        self.lock().traces.clone()
318    }
319
320    fn lock(&self) -> MutexGuard<'_, TraceState> {
321        self.state.lock().unwrap_or_else(PoisonError::into_inner)
322    }
323
324    /// `gen_ai.operation.name` and the provider key of the convention in use.
325    fn common_attributes(&self, operation_name: &str) -> Attributes {
326        let mut attributes = Attributes::new();
327        attributes.set("gen_ai.operation.name", operation_name);
328        let provider_key = if self.settings.use_latest_conventions {
329            "gen_ai.provider.name"
330        } else {
331            "gen_ai.system"
332        };
333        attributes.set(provider_key, self.settings.service_name.as_str());
334        attributes
335    }
336
337    /// Starts the `invoke_agent <name>` span, parented to the current span, and resets the local
338    /// traces.
339    pub(crate) fn start_agent_span(self: &Arc<Self>, options: StartAgentSpanOptions<'_>) -> AgentSpan {
340        {
341            let mut state = self.lock();
342            state.generation = state.generation.wrapping_add(1);
343            state.traces.clear();
344            state.current_cycle = None;
345        }
346        let span = usage_fields!(
347            None::<Span>,
348            "invoke_agent",
349            "gen_ai.operation.name",
350            "gen_ai.system",
351            "gen_ai.provider.name",
352            "gen_ai.agent.name",
353            "name",
354            "gen_ai.agent.id",
355            "gen_ai.request.model",
356            "langfuse.observation.type",
357        );
358        if !span.is_disabled() {
359            let span_name = format!("invoke_agent {}", options.agent_name);
360            span.record("otel.name", span_name.as_str());
361            let mut attributes = self.common_attributes("invoke_agent");
362            attributes.set("gen_ai.agent.name", options.agent_name);
363            attributes.set("name", span_name);
364            if let Some(agent_id) = options.agent_id.filter(|id| !id.is_empty()) {
365                attributes.set("gen_ai.agent.id", agent_id);
366            }
367            if let Some(model_id) = options.model_id.filter(|id| !id.is_empty()) {
368                attributes.set("gen_ai.request.model", model_id);
369            }
370            if exports(&span) {
371                self.agent_content_attributes(&mut attributes, &options);
372            }
373            attributes.extend(&self.trace_attributes);
374            attributes.extend(options.trace_attributes);
375            start_span(&span, attributes);
376            self.add_event_messages(&span, options.messages);
377        }
378        self.lock().agent_span = Some(span.clone());
379        AgentSpan {
380            tracer: self.clone(),
381            span: Some(span),
382            meter: None,
383        }
384    }
385
386    /// The tool names, tool definitions and system prompt of an agent span.
387    fn agent_content_attributes(&self, attributes: &mut Attributes, options: &StartAgentSpanOptions<'_>) {
388        if !options.tools.is_empty() {
389            attributes.set("gen_ai.agent.tools", to_json(options.tools));
390        }
391        if self.settings.include_tool_definitions
392            && let Some(tools_config) = options.tools_config
393        {
394            attributes.set("gen_ai.tool.definitions", to_json(&tool_definitions(tools_config)));
395        }
396        if let Some(system_prompt) = options.system_prompt {
397            attributes.set("system_prompt", to_json(system_prompt));
398        }
399    }
400
401    /// Starts an `execute_agent_loop_cycle` span under the agent span and opens the cycle's
402    /// local trace.
403    pub(crate) fn start_agent_loop_span(self: &Arc<Self>, cycle_id: &str, messages: &[Message]) -> LoopSpan {
404        let (parent, generation, cycle) = {
405            let mut state = self.lock();
406            let mut trace = AgentTrace::start(format!("Cycle {}", state.traces.len() + 1));
407            trace.metadata.insert("cycleId".to_owned(), json!(cycle_id));
408            state.traces.push(trace);
409            let cycle = state.traces.len() - 1;
410            state.current_cycle = Some(cycle);
411            state.tool_order.clear();
412            (state.agent_span.clone(), state.generation, cycle)
413        };
414        let span = gen_ai_span!(parent, "execute_agent_loop_cycle", "agent_loop.cycle_id");
415        if !span.is_disabled() {
416            let mut attributes = Attributes::new();
417            attributes.set("agent_loop.cycle_id", cycle_id);
418            attributes.extend(&self.trace_attributes);
419            start_span(&span, attributes);
420            self.add_event_messages(&span, messages);
421        }
422        self.lock().loop_span = Some(span.clone());
423        LoopSpan {
424            tracer: self.clone(),
425            span: Some(span),
426            generation,
427            cycle,
428        }
429    }
430
431    /// Starts a `chat` span under the cycle span and a `stream_messages` trace under the cycle.
432    pub(crate) fn start_model_invoke_span(self: &Arc<Self>, options: StartModelInvokeSpanOptions<'_>) -> ModelSpan {
433        let (parent, trace) = self.child_trace(AgentTrace::start("stream_messages"));
434        let span = usage_fields!(
435            parent,
436            "chat",
437            "gen_ai.operation.name",
438            "gen_ai.system",
439            "gen_ai.provider.name",
440            "gen_ai.request.model",
441            "gen_ai.server.request.duration",
442        );
443        if !span.is_disabled() {
444            let mut attributes = self.common_attributes("chat");
445            if let Some(model_id) = options.model_id.filter(|id| !id.is_empty()) {
446                attributes.set("gen_ai.request.model", model_id);
447            }
448            attributes.extend(&self.trace_attributes);
449            start_span(&span, attributes);
450            self.add_system_prompt_event(&span, options.system_prompt);
451            self.add_event_messages(&span, options.messages);
452        }
453        ModelSpan {
454            tracer: self.clone(),
455            span: Some(span),
456            trace,
457        }
458    }
459
460    /// Starts an `execute_tool <tool>` span under the cycle span and a `Tool: <tool>` trace under
461    /// the cycle.
462    pub(crate) fn start_tool_call_span(self: &Arc<Self>, tool: &ToolUse) -> ToolSpan {
463        let mut trace = AgentTrace::start(format!("Tool: {}", tool.name));
464        trace.metadata.insert("toolUseId".to_owned(), json!(tool.tool_use_id));
465        trace.metadata.insert("toolName".to_owned(), json!(tool.name));
466        let (parent, trace) = self.child_trace(trace);
467        let span = gen_ai_span!(
468            parent,
469            "execute_tool",
470            "gen_ai.operation.name",
471            "gen_ai.system",
472            "gen_ai.provider.name",
473            "gen_ai.tool.name",
474            "gen_ai.tool.call.id",
475            "gen_ai.tool.status",
476        );
477        if !span.is_disabled() {
478            span.record("otel.name", format!("execute_tool {}", tool.name).as_str());
479            let mut attributes = self.common_attributes("execute_tool");
480            attributes.set("gen_ai.tool.name", tool.name.as_str());
481            attributes.set("gen_ai.tool.call.id", tool.tool_use_id.as_str());
482            attributes.extend(&self.trace_attributes);
483            start_span(&span, attributes);
484            self.add_tool_input(&span, tool);
485        }
486        ToolSpan {
487            tracer: self.clone(),
488            span: Some(span),
489            trace,
490        }
491    }
492
493    /// Records the call order of a tool batch, so the batch's tool traces sit in that order
494    /// however their calls interleave.
495    pub(crate) fn order_tool_calls<'a>(&self, tool_use_ids: impl IntoIterator<Item = &'a str>) {
496        self.lock().tool_order = tool_use_ids.into_iter().map(str::to_owned).collect();
497    }
498
499    /// Nests a trace under the current cycle (an orphan without one), a tool trace
500    /// before the traces of later calls of its batch, and returns the cycle span to parent the
501    /// matching span.
502    fn child_trace(&self, mut trace: AgentTrace) -> (Option<Span>, Option<TraceRef>) {
503        let mut state = self.lock();
504        let parent = state.loop_span.clone();
505        let generation = state.generation;
506        let Some(cycle) = state.current_cycle else {
507            return (parent, None);
508        };
509        let position = state.tool_rank(&trace).and_then(|rank| {
510            state
511                .traces
512                .get(cycle)?
513                .children
514                .iter()
515                .position(|child| state.tool_rank(child).is_some_and(|other| other > rank))
516        });
517        let Some(cycle_trace) = state.traces.get_mut(cycle) else {
518            return (parent, None);
519        };
520        trace.parent_id = Some(cycle_trace.id.clone());
521        let child = trace.id.clone();
522        match position {
523            Some(index) => cycle_trace.children.insert(index, trace),
524            None => cycle_trace.children.push(trace),
525        }
526        (
527            parent,
528            Some(TraceRef {
529                generation,
530                cycle,
531                child,
532            }),
533        )
534    }
535
536    fn add_tool_input(&self, span: &Span, tool: &ToolUse) {
537        if !exports(span) {
538            return;
539        }
540        if !self.settings.use_latest_conventions {
541            add_event(
542                span,
543                "gen_ai.tool.message",
544                vec![
545                    ("role", "tool".to_owned()),
546                    ("content", to_json(&tool.input)),
547                    ("id", tool.tool_use_id.clone()),
548                ],
549                false,
550            );
551            return;
552        }
553        let mut arguments = Attributes::new();
554        arguments.set("gen_ai.tool.call.arguments", to_json(&tool.input));
555        record_attributes(span, arguments);
556        let input = json!([{
557            "role": "tool",
558            "parts": [{"type": "tool_call", "name": tool.name, "id": tool.tool_use_id, "arguments": tool.input}],
559        }]);
560        add_event(
561            span,
562            OPERATION_DETAILS,
563            vec![("gen_ai.input.messages", to_json(&input))],
564            self.settings.span_attributes_only,
565        );
566    }
567
568    /// Records messages: one operation details event in the latest conventions, one event per
569    /// message otherwise.
570    fn add_event_messages(&self, span: &Span, messages: &[Message]) {
571        if !exports(span) {
572            return;
573        }
574        if self.settings.use_latest_conventions {
575            add_event(
576                span,
577                OPERATION_DETAILS,
578                vec![("gen_ai.input.messages", to_json(&otel_messages(messages)))],
579                self.settings.span_attributes_only,
580            );
581            return;
582        }
583        for message in messages {
584            add_event(
585                span,
586                event_name_for_message(message),
587                vec![("content", to_json(&message.content))],
588                false,
589            );
590        }
591    }
592
593    /// `gen_ai.system.message`, or `gen_ai.system_instructions` in the latest conventions.
594    fn add_system_prompt_event(&self, span: &Span, system_prompt: Option<&SystemPrompt>) {
595        let Some(system_prompt) = system_prompt.filter(|_| exports(span)) else {
596            return;
597        };
598        if !self.settings.use_latest_conventions {
599            add_event(
600                span,
601                "gen_ai.system.message",
602                vec![("content", system_prompt_stable(system_prompt))],
603                false,
604            );
605            return;
606        }
607        add_event(
608            span,
609            OPERATION_DETAILS,
610            vec![(
611                "gen_ai.system_instructions",
612                to_json(&system_prompt_otel_parts(system_prompt)),
613            )],
614            self.settings.span_attributes_only,
615        );
616    }
617
618    /// Prompt, completion and cache token counts, legacy names included.
619    fn usage_attributes(&self, attributes: &mut Attributes, usage: &Usage) {
620        let prompt_tokens = usage.total_prompt_tokens();
621        attributes.set("gen_ai.usage.prompt_tokens", prompt_tokens);
622        attributes.set("gen_ai.usage.input_tokens", prompt_tokens);
623        attributes.set("gen_ai.usage.completion_tokens", usage.output_tokens);
624        attributes.set("gen_ai.usage.output_tokens", usage.output_tokens);
625        attributes.set("gen_ai.usage.total_tokens", usage.total_tokens);
626        let legacy = !self.settings.use_latest_conventions;
627        if let Some(tokens) = usage.cache_read_input_tokens.filter(|tokens| *tokens > 0) {
628            attributes.set("gen_ai.usage.cache_read.input_tokens", tokens);
629            if legacy {
630                attributes.set("gen_ai.usage.cache_read_input_tokens", tokens);
631            }
632        }
633        if let Some(tokens) = usage.cache_write_input_tokens.filter(|tokens| *tokens > 0) {
634            attributes.set("gen_ai.usage.cache_creation.input_tokens", tokens);
635            if legacy {
636                attributes.set("gen_ai.usage.cache_write_input_tokens", tokens);
637            }
638        }
639    }
640
641    fn end_agent_span(&self, span: &Span, options: &EndAgentSpanOptions<'_>) {
642        {
643            let mut state = self.lock();
644            state.agent_span = None;
645            state.loop_span = None;
646            state.current_cycle = None;
647        }
648        if span.is_disabled() {
649            return;
650        }
651        let mut attributes = Attributes::new();
652        if let Some(usage) = &options.accumulated_usage {
653            self.usage_attributes(&mut attributes, usage);
654        }
655        if self.settings.is_langfuse {
656            attributes.set("langfuse.observation.type", "span");
657        }
658        if let Some(response) = options.response {
659            self.add_response_event(span, response, options.stop_reason);
660        }
661        end_span(span, attributes, options.error.as_deref());
662    }
663
664    /// The agent's final answer.
665    fn add_response_event(&self, span: &Span, response: &Message, stop_reason: Option<&str>) {
666        if !exports(span) {
667            return;
668        }
669        let finish_reason = stop_reason.filter(|reason| !reason.is_empty()).unwrap_or("end_turn");
670        let text = message_text(response);
671        if !self.settings.use_latest_conventions {
672            add_event(
673                span,
674                "gen_ai.choice",
675                vec![("message", text), ("finish_reason", finish_reason.to_owned())],
676                false,
677            );
678            return;
679        }
680        let output = json!([{"role": "assistant", "parts": [{"type": "text", "content": text}], "finish_reason": finish_reason}]);
681        add_event(
682            span,
683            OPERATION_DETAILS,
684            vec![("gen_ai.output.messages", to_json(&output))],
685            self.settings.span_attributes_only,
686        );
687    }
688
689    fn end_loop_span(&self, span: &Span, generation: u64, cycle: usize, error: Option<&str>) {
690        {
691            let mut state = self.lock();
692            if state.generation == generation {
693                if let Some(trace) = state.traces.get_mut(cycle) {
694                    trace.end_now();
695                }
696                if state.current_cycle == Some(cycle) {
697                    state.current_cycle = None;
698                }
699            }
700            if state.loop_span.as_ref().map(Span::id) == Some(span.id()) {
701                state.loop_span = None;
702            }
703        }
704        if span.is_disabled() {
705            return;
706        }
707        end_span(span, Attributes::new(), error);
708    }
709
710    fn end_model_span(&self, span: &Span, trace: Option<TraceRef>, options: EndModelSpanOptions<'_>) {
711        if let Some(model_trace) = self.lock().cycle_child(trace) {
712            if let Some(output) = options.output {
713                model_trace.message = Some(output.clone());
714            }
715            model_trace.end_now();
716        }
717        if span.is_disabled() {
718            return;
719        }
720        if let Some(output) = options.output {
721            self.add_output_event(span, output, options.stop_reason);
722        }
723        let mut attributes = Attributes::new();
724        if let Some(usage) = options.usage {
725            self.usage_attributes(&mut attributes, usage);
726            if let Some(metrics) = options.metrics.filter(|metrics| metrics.latency_ms > 0) {
727                attributes.set("gen_ai.server.request.duration", metrics.latency_ms);
728            }
729        }
730        end_span(span, attributes, options.error);
731    }
732
733    /// The model's output message.
734    fn add_output_event(&self, span: &Span, message: &Message, stop_reason: Option<&str>) {
735        if !exports(span) {
736            return;
737        }
738        let finish_reason = stop_reason.filter(|reason| !reason.is_empty()).unwrap_or("unknown");
739        if !self.settings.use_latest_conventions {
740            add_event(
741                span,
742                "gen_ai.choice",
743                vec![
744                    ("finish_reason", finish_reason.to_owned()),
745                    ("message", to_json(&stable_parts(&message.content))),
746                ],
747                false,
748            );
749            return;
750        }
751        let output = json!([{
752            "role": message.role,
753            "parts": otel_parts(&message.content),
754            "finish_reason": finish_reason,
755        }]);
756        add_event(
757            span,
758            OPERATION_DETAILS,
759            vec![("gen_ai.output.messages", to_json(&output))],
760            self.settings.span_attributes_only,
761        );
762    }
763
764    fn end_tool_span(&self, span: &Span, trace: Option<TraceRef>, options: EndToolCallSpanOptions<'_>) {
765        if let Some(tool_trace) = self.lock().cycle_child(trace) {
766            tool_trace.end_now();
767        }
768        if span.is_disabled() {
769            return;
770        }
771        let mut attributes = Attributes::new();
772        if let Some(result) = options.tool_result {
773            self.tool_result_attributes(span, &mut attributes, result);
774        }
775        end_span(span, attributes, options.error);
776    }
777
778    fn tool_result_attributes(&self, span: &Span, attributes: &mut Attributes, result: &ToolResultBlock) {
779        let status = match result.status {
780            ToolResultStatus::Success => "success",
781            ToolResultStatus::Error => "error",
782        };
783        attributes.set("gen_ai.tool.status", status);
784        if !exports(span) {
785            return;
786        }
787        if !self.settings.use_latest_conventions {
788            add_event(
789                span,
790                "gen_ai.choice",
791                vec![
792                    ("message", to_json(&result.content)),
793                    ("id", result.tool_use_id.clone()),
794                ],
795                false,
796            );
797            return;
798        }
799        if result.status != ToolResultStatus::Error {
800            attributes.set("gen_ai.tool.call.result", to_json(&result.content));
801        }
802        let output = json!([{
803            "role": "tool",
804            "parts": [{"type": "tool_call_response", "id": result.tool_use_id, "response": result.content}],
805        }]);
806        add_event(
807            span,
808            OPERATION_DETAILS,
809            vec![("gen_ai.output.messages", to_json(&output))],
810            self.settings.span_attributes_only,
811        );
812    }
813}
814
815/// An open `invoke_agent` span; dropping it, as a consumer that stops early does, ends it with the
816/// accumulated usage only.
817pub(crate) struct AgentSpan {
818    tracer: Arc<Tracer>,
819    span: Option<Span>,
820    meter: Option<Arc<Mutex<super::Meter>>>,
821}
822
823impl AgentSpan {
824    /// Reads the accumulated usage from `meter` when the span ends without one.
825    pub(crate) fn with_meter(mut self, meter: Arc<Mutex<super::Meter>>) -> Self {
826        self.meter = Some(meter);
827        self
828    }
829
830    /// Ends the span.
831    pub(crate) fn end(mut self, options: EndAgentSpanOptions<'_>) {
832        self.finish(options);
833    }
834
835    fn finish(&mut self, mut options: EndAgentSpanOptions<'_>) {
836        let Some(span) = self.span.take() else {
837            return;
838        };
839        if options.accumulated_usage.is_none()
840            && let Some(meter) = &self.meter
841        {
842            let usage = meter
843                .lock()
844                .unwrap_or_else(PoisonError::into_inner)
845                .metrics()
846                .accumulated_usage;
847            options.accumulated_usage = Some(usage);
848        }
849        self.tracer.end_agent_span(&span, &options);
850    }
851}
852
853impl Drop for AgentSpan {
854    fn drop(&mut self) {
855        self.finish(EndAgentSpanOptions::default());
856    }
857}
858
859/// An open `execute_agent_loop_cycle` span; dropping it ends it.
860pub(crate) struct LoopSpan {
861    tracer: Arc<Tracer>,
862    span: Option<Span>,
863    generation: u64,
864    cycle: usize,
865}
866
867impl LoopSpan {
868    /// Ends the span, with an error when the cycle failed.
869    pub(crate) fn end(mut self, error: Option<&str>) {
870        self.finish(error);
871    }
872
873    fn finish(&mut self, error: Option<&str>) {
874        let Some(span) = self.span.take() else {
875            return;
876        };
877        self.tracer.end_loop_span(&span, self.generation, self.cycle, error);
878    }
879}
880
881impl Drop for LoopSpan {
882    fn drop(&mut self) {
883        self.finish(None);
884    }
885}
886
887/// An open `chat` span; dropping it ends it without output (a consumer that stopped early).
888pub(crate) struct ModelSpan {
889    tracer: Arc<Tracer>,
890    span: Option<Span>,
891    trace: Option<TraceRef>,
892}
893
894impl ModelSpan {
895    /// Ends the span.
896    pub(crate) fn end(mut self, options: EndModelSpanOptions<'_>) {
897        self.finish(options);
898    }
899
900    fn finish(&mut self, options: EndModelSpanOptions<'_>) {
901        let Some(span) = self.span.take() else {
902            return;
903        };
904        self.tracer.end_model_span(&span, self.trace.take(), options);
905    }
906}
907
908impl Drop for ModelSpan {
909    fn drop(&mut self) {
910        self.finish(EndModelSpanOptions::default());
911    }
912}
913
914/// An open `execute_tool` span; dropping it ends it without a result.
915pub(crate) struct ToolSpan {
916    tracer: Arc<Tracer>,
917    span: Option<Span>,
918    trace: Option<TraceRef>,
919}
920
921impl ToolSpan {
922    /// The span the tool runs in.
923    pub(crate) fn span(&self) -> Span {
924        self.span.clone().unwrap_or_else(Span::none)
925    }
926
927    /// Ends the span with the raw tool outcome.
928    pub(crate) fn end(mut self, options: EndToolCallSpanOptions<'_>) {
929        self.finish(options);
930    }
931
932    fn finish(&mut self, options: EndToolCallSpanOptions<'_>) {
933        let Some(span) = self.span.take() else {
934            return;
935        };
936        self.tracer.end_tool_span(&span, self.trace.take(), options);
937    }
938}
939
940impl Drop for ToolSpan {
941    fn drop(&mut self) {
942        self.finish(EndToolCallSpanOptions::default());
943    }
944}
945
946#[cfg(test)]
947mod tests;