Skip to main content

rig_core/telemetry/
mod.rs

1//! GenAI tracing spans, completion-parent adoption, and opt-in content recording.
2//!
3//! ```
4//! use rig_core::telemetry::{GenAiOperation, SpanBuilder};
5//!
6//! let span = SpanBuilder::new("provider", "model", GenAiOperation::Chat).build();
7//! ```
8use crate::completion::{AssistantContent, CompletionRequest, Message, Usage};
9use crate::message::{
10    DocumentData, DocumentSourceKind, Image, MimeType, Opaque, ToolResult, ToolResultContent,
11    UserContent,
12};
13use base64::Engine;
14use serde::Serialize;
15use std::borrow::Borrow;
16use std::collections::HashSet;
17use std::sync::{LazyLock, Mutex};
18use tracing::callsite::Identifier;
19
20/// Macro implementation dependency; public because exported macro expansions
21/// must be able to resolve it from downstream crates.
22#[doc(hidden)]
23pub use tracing as __tracing;
24
25/// Declares a span field without a value, including in [`completion_parent_span!`].
26pub use tracing::field::Empty;
27
28/// Declares caller-supplied header fields and canonical completion fields.
29/// The header must end with a comma; nonempty extras must begin with one.
30#[doc(hidden)]
31#[macro_export]
32macro_rules! __rig_canonical_completion_span {
33    (
34        target: $target:literal,
35        $(parent: $parent:expr,)?
36        name: $name:literal,
37        // Both blocks are spliced verbatim into `info_span!`: the header block
38        // must end with a trailing comma, the extras block must begin with one.
39        // Violating either surfaces as an `info_span!` parse error at the call
40        // site, not here.
41        { $($header:tt)* }
42        { $($extra:tt)* }
43    ) => {
44        $crate::telemetry::__tracing::info_span!(
45            target: $target,
46            $(parent: $parent,)?
47            $name,
48            $($header)*
49            gen_ai.request.stream = $crate::telemetry::__tracing::field::Empty,
50            gen_ai.response.id = $crate::telemetry::__tracing::field::Empty,
51            gen_ai.response.model = $crate::telemetry::__tracing::field::Empty,
52            rig.provider_request_id = $crate::telemetry::__tracing::field::Empty,
53            gen_ai.usage.input_tokens = $crate::telemetry::__tracing::field::Empty,
54            gen_ai.usage.output_tokens = $crate::telemetry::__tracing::field::Empty,
55            gen_ai.usage.cache_read.input_tokens = $crate::telemetry::__tracing::field::Empty,
56            gen_ai.usage.cache_creation.input_tokens = $crate::telemetry::__tracing::field::Empty,
57            gen_ai.usage.tool_use_prompt_tokens = $crate::telemetry::__tracing::field::Empty,
58            gen_ai.usage.reasoning_tokens = $crate::telemetry::__tracing::field::Empty,
59            gen_ai.input.messages = $crate::telemetry::__tracing::field::Empty,
60            gen_ai.output.messages = $crate::telemetry::__tracing::field::Empty
61            $($extra)*
62        )
63    };
64}
65
66macro_rules! new_completion_span {
67    ($name:literal, $provider:expr, $request_model:expr, $operation:expr, $system:expr) => {
68        $crate::__rig_canonical_completion_span!(
69            target: "rig::completions",
70            name: $name,
71            {
72                gen_ai.operation.name = $operation,
73                gen_ai.provider.name = $provider,
74                gen_ai.request.model = $request_model,
75                gen_ai.system_instructions = $system,
76            }
77            {}
78        )
79    };
80}
81
82/// A GenAI operation and its canonical span name. Completion operations carry
83/// message content and may adopt a completion-parent span; the others record
84/// only usage and identity on a fresh span.
85///
86/// Completion operations report the well-known `gen_ai.operation.name` values
87/// of the OpenTelemetry GenAI semantic conventions. Streaming is a delivery
88/// mode, not an operation: it is recorded as `gen_ai.request.stream` (see
89/// [`SpanBuilder::streaming`]).
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum GenAiOperation {
92    /// A chat completion (`chat`), unary or streamed.
93    Chat,
94    /// A Gemini generate-content request (`generate_content`), unary or streamed.
95    GenerateContent,
96    /// A text (or image) embedding request.
97    Embeddings,
98    /// A reranking request.
99    Rerank,
100    /// An audio transcription request.
101    Transcription,
102    /// An image generation request.
103    ImageGeneration,
104    /// An audio generation (text-to-speech) request.
105    AudioGeneration,
106}
107
108impl GenAiOperation {
109    fn as_str(self) -> &'static str {
110        match self {
111            Self::Chat => "chat",
112            Self::GenerateContent => "generate_content",
113            Self::Embeddings => "embeddings",
114            Self::Rerank => "rerank",
115            Self::Transcription => "transcription",
116            Self::ImageGeneration => "image_generation",
117            Self::AudioGeneration => "audio_generation",
118        }
119    }
120
121    pub(crate) fn is_completion(self) -> bool {
122        matches!(self, Self::Chat | Self::GenerateContent)
123    }
124}
125
126/// Span field holding the provider's transport request id (the request-id
127/// response header), recorded on success and on provider errors. GenAI
128/// semantic conventions define no attribute for it. Rig's own completion
129/// spans declare it; it is not required of an adopted parent, which simply
130/// does not record it when undeclared.
131pub const PROVIDER_REQUEST_ID_FIELD: &str = "rig.provider_request_id";
132
133/// Marker field for completion-parent adoption, independent of tracing target.
134/// Its value is ignored. Adoption requires every field in
135/// [`COMPLETION_PARENT_REQUIRED_FIELDS`]; otherwise the builder creates a child
136/// span and warns once per incomplete callsite.
137pub const COMPLETION_PARENT_MARKER_FIELD: &str = "rig.completion_parent";
138
139/// Fields required alongside [`COMPLETION_PARENT_MARKER_FIELD`] for adoption.
140/// Each must be statically declared with [`Empty`] or a value.
141/// [`completion_parent_span!`] declares the complete set.
142pub const COMPLETION_PARENT_REQUIRED_FIELDS: &[&str] = &[
143    "gen_ai.operation.name",
144    "gen_ai.provider.name",
145    "gen_ai.request.model",
146    "gen_ai.system_instructions",
147    "gen_ai.response.id",
148    "gen_ai.response.model",
149    "gen_ai.usage.input_tokens",
150    "gen_ai.usage.output_tokens",
151    "gen_ai.usage.cache_read.input_tokens",
152    "gen_ai.usage.cache_creation.input_tokens",
153    "gen_ai.usage.tool_use_prompt_tokens",
154    "gen_ai.usage.reasoning_tokens",
155    "gen_ai.input.messages",
156    "gen_ai.output.messages",
157];
158
159/// Declares a completion-parent span with the marker and all required fields.
160/// Defaults to the current span as parent. An optional `parent: <expr>` between
161/// `target` and `name` accepts any parent supported by [`tracing::info_span!`],
162/// including `None`.
163///
164/// Records the supplied operation and system instructions. Provider and model
165/// fields are populated on adoption. Extra fields must not duplicate the marker
166/// or required fields: recording a duplicate name updates only its first field.
167/// Use [`Empty`] or `Option::<&str>::None` for unset values without a direct
168/// `tracing` dependency.
169///
170/// ```
171/// use rig_core::telemetry::completion_parent_span;
172///
173/// let span = completion_parent_span!(
174///     target: "my_runtime",
175///     name: "chat",
176///     operation: "chat",
177///     system_instructions: Option::<&str>::None,
178///     gen_ai.agent.name = "assistant",
179/// );
180/// ```
181#[macro_export]
182macro_rules! completion_parent_span {
183    (
184        target: $target:literal,
185        parent: $parent:expr,
186        name: $name:literal,
187        operation: $operation:expr,
188        system_instructions: $system:expr
189        $(, $($extra:tt)*)?
190    ) => {
191        $crate::__rig_canonical_completion_span!(
192            target: $target,
193            parent: $parent,
194            name: $name,
195            {
196                rig.completion_parent = true,
197                gen_ai.operation.name = $operation,
198                gen_ai.system_instructions = $system,
199                gen_ai.provider.name = $crate::telemetry::__tracing::field::Empty,
200                gen_ai.request.model = $crate::telemetry::__tracing::field::Empty,
201            }
202            { $(, $($extra)*)? }
203        )
204    };
205    // Default arm: delegates to the explicit-parent arm so the two cannot
206    // drift in the fields they declare.
207    (
208        target: $target:literal,
209        name: $name:literal,
210        operation: $operation:expr,
211        system_instructions: $system:expr
212        $(, $($extra:tt)*)?
213    ) => {
214        $crate::completion_parent_span!(
215            target: $target,
216            parent: $crate::telemetry::__tracing::Span::current(),
217            name: $name,
218            operation: $operation,
219            system_instructions: $system
220            $(, $($extra)*)?
221        )
222    };
223}
224
225// `#[macro_export]` places the macro at the crate root; re-export it here so
226// it is also reachable at its documented home alongside the contract
227// constants it implements.
228pub use crate::completion_parent_span;
229
230/// Returns undeclared required fields for the warning diagnostic.
231fn missing_required_fields(metadata: &tracing::Metadata<'_>) -> Vec<&'static str> {
232    let fields = metadata.fields();
233    COMPLETION_PARENT_REQUIRED_FIELDS
234        .iter()
235        .copied()
236        .filter(|name| fields.field(name).is_none())
237        .collect()
238}
239
240/// Incomplete parent callsites already reported, bounded by the program's
241/// static callsites. Each callsite receives its own missing-field diagnostic.
242static NEAR_MISS_WARNED: LazyLock<Mutex<HashSet<Identifier>>> =
243    LazyLock::new(|| Mutex::new(HashSet::new()));
244
245/// Clear the per-callsite warn budget.
246///
247/// The budget is process-global, so without this the warning tests are coupled:
248/// whichever runs first consumes the budget for any callsite they share, and the
249/// other sees silence. `cargo nextest` hides that (one process per test) while
250/// `cargo test` exposes it, so the coupling would be green in CI and red
251/// locally — the worst orientation for a latent test bug. Resetting makes each
252/// test independent of callsite identity, ordering, and runner.
253#[cfg(test)]
254fn reset_near_miss_warnings() {
255    crate::lock(&NEAR_MISS_WARNED).clear();
256}
257
258/// Warns once per incomplete parent callsite, recovering a poisoned dedup lock.
259/// A subscriber panic must not prevent subsequent completions.
260fn warn_once_on_missing_fields(metadata: &tracing::Metadata<'_>, missing: &[&'static str]) {
261    // Release the lock before invoking subscribers, which may re-enter
262    // the builder and deadlock if the guard is still held.
263    if !crate::lock(&NEAR_MISS_WARNED).insert(metadata.callsite()) {
264        return;
265    }
266    tracing::warn!(
267        marker = COMPLETION_PARENT_MARKER_FIELD,
268        missing_fields = ?missing,
269        "completion-parent span declares the marker but not every required field \
270         and is not adopted; provider telemetry lands on a fresh child span \
271         instead — declare the span with \
272         `rig_core::telemetry::completion_parent_span!`"
273    );
274}
275
276macro_rules! new_modality_span {
277    ($name:literal, $provider:expr, $request_model:expr, $operation:expr) => {
278        $crate::telemetry::__tracing::info_span!(
279            target: "rig::modalities",
280            $name,
281            gen_ai.operation.name = $operation,
282            gen_ai.provider.name = $provider,
283            gen_ai.request.model = $request_model,
284            gen_ai.response.id = $crate::telemetry::__tracing::field::Empty,
285            gen_ai.response.model = $crate::telemetry::__tracing::field::Empty,
286            rig.provider_request_id = $crate::telemetry::__tracing::field::Empty,
287            gen_ai.usage.input_tokens = $crate::telemetry::__tracing::field::Empty,
288            gen_ai.usage.output_tokens = $crate::telemetry::__tracing::field::Empty,
289            gen_ai.usage.cache_read.input_tokens = $crate::telemetry::__tracing::field::Empty,
290            gen_ai.usage.cache_creation.input_tokens = $crate::telemetry::__tracing::field::Empty,
291            gen_ai.usage.tool_use_prompt_tokens = $crate::telemetry::__tracing::field::Empty,
292            gen_ai.usage.reasoning_tokens = $crate::telemetry::__tracing::field::Empty,
293        )
294    };
295}
296
297/// Builder for a canonical GenAI span.
298///
299/// A completion operation reuses the current span when it declares
300/// [`COMPLETION_PARENT_MARKER_FIELD`] and every field in
301/// [`COMPLETION_PARENT_REQUIRED_FIELDS`], and otherwise opens a
302/// `rig::completions` child of the current span. Every other operation opens a
303/// fresh `rig::modalities` span.
304pub struct SpanBuilder<'a> {
305    provider: &'a str,
306    request_model: &'a str,
307    operation: GenAiOperation,
308    system_instructions: Option<String>,
309    streaming: Option<bool>,
310}
311
312impl<'a> SpanBuilder<'a> {
313    /// Create a span builder for a provider request.
314    pub fn new(provider: &'a str, request_model: &'a str, operation: GenAiOperation) -> Self {
315        Self {
316            provider,
317            request_model,
318            operation,
319            system_instructions: None,
320            streaming: None,
321        }
322    }
323
324    /// Record whether the request streams its response, as
325    /// `gen_ai.request.stream`. Only completion spans record it.
326    pub fn streaming(mut self, streaming: bool) -> Self {
327        self.streaming = Some(streaming);
328        self
329    }
330
331    /// Set the system instructions sent with the request when sensitive content
332    /// telemetry has been explicitly enabled. Only completion spans record them.
333    pub fn system_instructions(
334        mut self,
335        system_instructions: Option<&'a str>,
336        record_content: bool,
337    ) -> Self {
338        self.system_instructions = system_instructions_json(system_instructions, record_content);
339        self
340    }
341
342    /// Build the operation's canonical span, or enrich Rig's current
343    /// completion-parent span for a completion operation.
344    pub fn build(self) -> tracing::Span {
345        if self.operation.is_completion()
346            && let Some(parent) = self.adopt_completion_parent()
347        {
348            return parent;
349        }
350
351        let (provider, model) = (self.provider, self.request_model);
352        let op = self.operation.as_str();
353        let sys = self.system_instructions.as_deref();
354        let span = match self.operation {
355            GenAiOperation::Chat => new_completion_span!("chat", provider, model, op, sys),
356            GenAiOperation::GenerateContent => {
357                new_completion_span!("generate_content", provider, model, op, sys)
358            }
359            GenAiOperation::Embeddings => new_modality_span!("embeddings", provider, model, op),
360            GenAiOperation::Rerank => new_modality_span!("rerank", provider, model, op),
361            GenAiOperation::Transcription => {
362                new_modality_span!("transcription", provider, model, op)
363            }
364            GenAiOperation::ImageGeneration => {
365                new_modality_span!("image_generation", provider, model, op)
366            }
367            GenAiOperation::AudioGeneration => {
368                new_modality_span!("audio_generation", provider, model, op)
369            }
370        };
371        if self.operation.is_completion() {
372            self.record_streaming(&span);
373        }
374        span
375    }
376
377    fn record_streaming(&self, span: &tracing::Span) {
378        if let Some(streaming) = self.streaming {
379            span.record("gen_ai.request.stream", streaming);
380        }
381    }
382
383    /// The current span, enriched with this request, when it is a conforming
384    /// completion parent. Warns once per near-miss callsite.
385    fn adopt_completion_parent(&self) -> Option<tracing::Span> {
386        let current = tracing::Span::current();
387        let metadata = current.metadata()?;
388        // Exact match, never a prefix: a runtime field that merely starts with the
389        // marker name (`rig.completion_parent.id`, say) is not the marker and must
390        // not make its span a rejected parent.
391        metadata.fields().field(COMPLETION_PARENT_MARKER_FIELD)?;
392        let missing = missing_required_fields(metadata);
393        if !missing.is_empty() {
394            warn_once_on_missing_fields(metadata, &missing);
395            return None;
396        }
397        current.record("gen_ai.operation.name", self.operation.as_str());
398        current.record("gen_ai.provider.name", self.provider);
399        current.record("gen_ai.request.model", self.request_model);
400        self.record_streaming(&current);
401        if let Some(system_instructions) = self.system_instructions.as_deref() {
402            current.record("gen_ai.system_instructions", system_instructions);
403        }
404        Some(current)
405    }
406}
407
408#[derive(Serialize)]
409struct TelemetryChatMessage {
410    role: &'static str,
411    parts: Vec<TelemetryPart>,
412}
413
414#[derive(Serialize)]
415struct TelemetryOutputMessage {
416    role: &'static str,
417    parts: Vec<TelemetryPart>,
418    finish_reason: &'static str,
419}
420
421#[derive(Serialize)]
422#[serde(tag = "type", rename_all = "snake_case")]
423enum TelemetryPart {
424    Text {
425        content: String,
426    },
427    ToolCall {
428        #[serde(skip_serializing_if = "Option::is_none")]
429        id: Option<String>,
430        name: String,
431        arguments: serde_json::Value,
432    },
433    ToolCallResponse {
434        #[serde(skip_serializing_if = "Option::is_none")]
435        id: Option<String>,
436        response: serde_json::Value,
437    },
438    Reasoning {
439        content: String,
440    },
441    Opaque {
442        kind: String,
443    },
444    Uri {
445        #[serde(skip_serializing_if = "Option::is_none")]
446        mime_type: Option<String>,
447        modality: &'static str,
448        uri: String,
449    },
450    File {
451        #[serde(skip_serializing_if = "Option::is_none")]
452        mime_type: Option<String>,
453        modality: &'static str,
454        file_id: String,
455    },
456    Blob {
457        #[serde(skip_serializing_if = "Option::is_none")]
458        mime_type: Option<String>,
459        modality: &'static str,
460        content: String,
461    },
462}
463
464fn media_part<T>(
465    data: &DocumentSourceKind,
466    media_type: Option<&T>,
467    modality: &'static str,
468) -> Option<TelemetryPart>
469where
470    T: MimeType,
471{
472    let mime_type = media_type.map(|media_type| media_type.to_mime_type().to_string());
473    match data {
474        DocumentSourceKind::Url(uri) => Some(TelemetryPart::Uri {
475            mime_type,
476            modality,
477            uri: uri.clone(),
478        }),
479        DocumentSourceKind::FileId(file_id) => Some(TelemetryPart::File {
480            mime_type,
481            modality,
482            file_id: file_id.clone(),
483        }),
484        DocumentSourceKind::Base64(content) => Some(TelemetryPart::Blob {
485            mime_type,
486            modality,
487            content: content.clone(),
488        }),
489        DocumentSourceKind::Raw(content) => Some(TelemetryPart::Blob {
490            mime_type,
491            modality,
492            content: base64::engine::general_purpose::STANDARD.encode(content),
493        }),
494        DocumentSourceKind::Unknown => None,
495    }
496}
497
498fn image_part(image: &Image) -> Option<TelemetryPart> {
499    media_part(&image.data, image.media_type.as_ref(), "image")
500}
501
502/// A provider-only item, named by its `type` and nothing else: its payload
503/// is the provider's, not content.
504fn opaque_part(opaque: &Opaque) -> TelemetryPart {
505    TelemetryPart::Opaque {
506        kind: opaque.kind().unwrap_or("unknown").to_owned(),
507    }
508}
509
510fn tool_result_response(result: &ToolResult) -> serde_json::Value {
511    let mut content = result
512        .content
513        .iter()
514        .filter_map(|content| match content {
515            ToolResultContent::Text(text) => Some(serde_json::Value::String(text.text.clone())),
516            ToolResultContent::Json { value } => Some(value.clone()),
517            ToolResultContent::Image(image) => {
518                image_part(image).and_then(|part| serde_json::to_value(part).ok())
519            }
520        })
521        .collect::<Vec<_>>();
522
523    if content.len() == 1 {
524        content.pop().unwrap_or(serde_json::Value::Null)
525    } else {
526        serde_json::Value::Array(content)
527    }
528}
529
530fn user_parts(content: &[UserContent]) -> Vec<TelemetryPart> {
531    content
532        .iter()
533        .filter_map(|content| match content {
534            UserContent::Text(text) => Some(TelemetryPart::Text {
535                content: text.text.clone(),
536            }),
537            UserContent::ToolResult(result) => Some(TelemetryPart::ToolCallResponse {
538                id: Some(result.call.to_string()),
539                response: tool_result_response(result),
540            }),
541            UserContent::Image(image) => image_part(image),
542            UserContent::Audio(audio) => {
543                media_part(&audio.data, audio.media_type.as_ref(), "audio")
544            }
545            UserContent::Video(video) => {
546                media_part(&video.data, video.media_type.as_ref(), "video")
547            }
548            UserContent::Document(document) => match &document.data {
549                DocumentData::Text(content) => Some(TelemetryPart::Text {
550                    content: content.clone(),
551                }),
552                DocumentData::File(data) => {
553                    media_part(data, document.media_type.as_ref(), "document")
554                }
555            },
556        })
557        .collect()
558}
559
560fn assistant_parts(content: &[AssistantContent]) -> Vec<TelemetryPart> {
561    content
562        .iter()
563        .flat_map(|content| match content {
564            AssistantContent::Text(text) => vec![TelemetryPart::Text {
565                content: text.text.clone(),
566            }],
567            AssistantContent::ToolCall(tool_call) => vec![TelemetryPart::ToolCall {
568                id: Some(tool_call.id.to_string()),
569                name: tool_call.function.name.clone().into(),
570                arguments: tool_call.function.arguments_value(),
571            }],
572            AssistantContent::Reasoning(reasoning) => vec![TelemetryPart::Reasoning {
573                content: reasoning.text.clone(),
574            }],
575            AssistantContent::Image(image) => image_part(image).into_iter().collect(),
576            AssistantContent::Opaque(opaque) => vec![opaque_part(opaque)],
577        })
578        .collect()
579}
580
581fn input_messages(messages: &[impl Borrow<Message>]) -> Vec<TelemetryChatMessage> {
582    messages
583        .iter()
584        .map(|message| match message.borrow() {
585            Message::System { content } => TelemetryChatMessage {
586                role: "system",
587                parts: vec![TelemetryPart::Text {
588                    content: content.clone(),
589                }],
590            },
591            Message::User { content } => TelemetryChatMessage {
592                role: "user",
593                parts: user_parts(content),
594            },
595            Message::Assistant(turn) => TelemetryChatMessage {
596                role: "assistant",
597                parts: assistant_parts(&turn.content),
598            },
599        })
600        .collect()
601}
602
603fn output_messages(content: &[AssistantContent]) -> Vec<TelemetryOutputMessage> {
604    let finish_reason = if content
605        .iter()
606        .any(|content| matches!(content, AssistantContent::ToolCall(_)))
607    {
608        "tool_call"
609    } else {
610        // Rig's normalized assistant content does not retain provider finish
611        // reasons such as length or content filtering. Avoid claiming a clean
612        // stop when the actual reason is unavailable.
613        "unknown"
614    };
615    vec![TelemetryOutputMessage {
616        role: "assistant",
617        parts: assistant_parts(content),
618        finish_reason,
619    }]
620}
621
622/// Serializes system instructions using the normalized GenAI telemetry shape.
623pub fn system_instructions_json(instructions: Option<&str>, enabled: bool) -> Option<String> {
624    if !enabled {
625        return None;
626    }
627
628    instructions.and_then(|instructions| {
629        serde_json::to_string(&vec![TelemetryPart::Text {
630            content: instructions.to_string(),
631        }])
632        .ok()
633    })
634}
635
636/// Records serialized model input messages on `gen_ai.input.messages` when
637/// content telemetry is explicitly enabled.
638///
639/// Message content can contain prompts, retrieved context, tool results, and
640/// other sensitive or high-cardinality data. Keep this disabled unless the
641/// caller has explicitly opted in for debugging/observability.
642pub fn record_model_input(span: &tracing::Span, messages: &[impl Borrow<Message>], enabled: bool) {
643    if !enabled || span.is_disabled() {
644        return;
645    }
646
647    if let Ok(messages) = serde_json::to_string(&input_messages(messages)) {
648        span.record("gen_ai.input.messages", messages);
649    }
650}
651
652/// Records serialized model output messages on `gen_ai.output.messages` when
653/// content telemetry is explicitly enabled.
654///
655/// Message content can contain model responses, tool calls, and other sensitive
656/// or high-cardinality data. Keep this disabled unless the caller has explicitly
657/// opted in for debugging/observability.
658pub fn record_model_output(span: &tracing::Span, content: &[AssistantContent], enabled: bool) {
659    if !enabled || span.is_disabled() {
660        return;
661    }
662
663    let messages = output_messages(content);
664    if let Ok(messages) = serde_json::to_string(&messages) {
665        span.record("gen_ai.output.messages", messages);
666    }
667}
668
669/// Records the request's tool definitions on `gen_ai.tool.definitions` when
670/// content telemetry is explicitly enabled.
671///
672/// Function tools carry their name, description and parameter schema.
673/// Provider-hosted tools in `additional_params.tools` carry only their type and
674/// name, since their configuration can hold credentials. An entry without a
675/// `type` field is a function when it has a `name`, and otherwise one tool per
676/// key, as in `{"googleSearch": {}}`. The name is the `name` field, or the one
677/// nested under the type (`{"type": "custom", "custom": {"name": ...}}`), or
678/// else the type.
679///
680/// This is the request as dispatched; a provider may still add or drop tools
681/// when it encodes the request. Records nothing when the request has no tools.
682pub fn record_tool_definitions(span: &tracing::Span, request: &CompletionRequest, enabled: bool) {
683    if !enabled || span.is_disabled() {
684        return;
685    }
686
687    let functions = request.tools.iter().map(|tool| {
688        serde_json::json!({
689            "type": "function",
690            "name": tool.name.as_str(),
691            "description": tool.description,
692            "parameters": tool.parameters,
693        })
694    });
695    let hosted = crate::completion::history::raw_tools(request)
696        .iter()
697        .filter_map(serde_json::Value::as_object)
698        .flat_map(|tool| {
699            let kinds: Vec<&str> = match (tool.get("type"), tool.get("name")) {
700                (Some(kind), _) => kind.as_str().into_iter().collect(),
701                (None, Some(_)) => vec!["function"],
702                (None, None) => tool.keys().map(String::as_str).collect(),
703            };
704            kinds.into_iter().map(move |kind| {
705                let name = [
706                    tool.get("name"),
707                    tool.get(kind).and_then(|body| body.get("name")),
708                ]
709                .into_iter()
710                .find_map(|name| name?.as_str());
711                serde_json::json!({ "type": kind, "name": name.unwrap_or(kind) })
712            })
713        });
714    let definitions: Vec<_> = functions.chain(hosted).collect();
715    if definitions.is_empty() {
716        return;
717    }
718    if let Ok(definitions) = serde_json::to_string(&definitions) {
719        span.record("gen_ai.tool.definitions", definitions);
720    }
721}
722
723/// Records GenAI usage and response metadata on tracing spans.
724pub trait SpanCombinator {
725    /// Record Rig-normalized token usage fields on the span.
726    fn record_token_usage(&self, usage: &Usage);
727
728    /// Record a response's ID, model, and token usage on the span.
729    fn record_response(&self, response_id: Option<&str>, model: Option<&str>, usage: &Usage);
730}
731
732impl SpanCombinator for tracing::Span {
733    fn record_token_usage(&self, usage: &Usage) {
734        if self.is_disabled() {
735            return;
736        }
737
738        // A counter the provider did not report leaves its span field unset;
739        // a reported zero is recorded as zero.
740        let fields = [
741            ("gen_ai.usage.input_tokens", usage.input_tokens),
742            ("gen_ai.usage.output_tokens", usage.output_tokens),
743            (
744                "gen_ai.usage.cache_read.input_tokens",
745                usage.cached_input_tokens,
746            ),
747            (
748                "gen_ai.usage.cache_creation.input_tokens",
749                usage.cache_creation_input_tokens,
750            ),
751            (
752                "gen_ai.usage.tool_use_prompt_tokens",
753                usage.tool_use_prompt_tokens,
754            ),
755            ("gen_ai.usage.reasoning_tokens", usage.reasoning_tokens),
756        ];
757        for (field, value) in fields {
758            if let Some(value) = value {
759                self.record(field, value);
760            }
761        }
762    }
763
764    fn record_response(&self, response_id: Option<&str>, model: Option<&str>, usage: &Usage) {
765        if self.is_disabled() {
766            return;
767        }
768        if let Some(id) = response_id {
769            self.record("gen_ai.response.id", id);
770        }
771        if let Some(model) = model {
772            self.record("gen_ai.response.model", model);
773        }
774        self.record_token_usage(usage);
775    }
776}
777
778#[cfg(test)]
779mod tests;