Skip to content

The platform for continuously improving AI agents.

3.5 KB
Raw Blame
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::semconv::{
    self, GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_MODEL, GEN_AI_USAGE_CACHE_READ_TOKENS,
    GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS,
    OVERMIND_COST,
};

/// Canonical attribute keys kept in the per-span usage slice.
pub const USAGE_ATTR_KEYS: &[&str] = &[
    GEN_AI_USAGE_TOTAL_TOKENS,
    GEN_AI_USAGE_INPUT_TOKENS,
    GEN_AI_USAGE_OUTPUT_TOKENS,
    GEN_AI_USAGE_CACHE_READ_TOKENS,
    OVERMIND_COST,
    GEN_AI_RESPONSE_MODEL,
    GEN_AI_REQUEST_MODEL,
];

/// Per-span usage derived at ingest. `None` means the span did not report it.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct SpanUsage {
    pub slice: Option<Value>,
    pub total_tokens: Option<i64>,
    pub cost: Option<f64>,
    pub cache_read_tokens: Option<i64>,
    pub model: Option<String>,
}

impl SpanUsage {
    /// Extract usage from already-normalized attributes.
    pub fn from_normalized(attrs: &Map<String, Value>) -> Self {
        let slice: Map<String, Value> = USAGE_ATTR_KEYS
            .iter()
            .filter_map(|key| match attrs.get(*key) {
                None | Some(Value::Null) => None,
                Some(value) => Some(((*key).to_string(), value.clone())),
            })
            .collect();
        if slice.is_empty() {
            return Self::default();
        }
        let model = [GEN_AI_RESPONSE_MODEL, GEN_AI_REQUEST_MODEL]
            .iter()
            .find_map(|key| match slice.get(*key) {
                Some(Value::String(s)) if !s.trim().is_empty() => Some(s.trim().to_string()),
                _ => None,
            });
        Self {
            total_tokens: slice.get(GEN_AI_USAGE_TOTAL_TOKENS).and_then(Value::as_i64),
            cost: slice.get(OVERMIND_COST).and_then(Value::as_f64),
            cache_read_tokens: slice
                .get(GEN_AI_USAGE_CACHE_READ_TOKENS)
                .and_then(Value::as_i64),
            model,
            slice: Some(Value::Object(slice)),
        }
    }

    /// Normalize raw attributes and extract usage.
    pub fn from_attributes(attrs: &Map<String, Value>) -> Self {
        Self::from_normalized(&semconv::normalize_attributes(attrs))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn usage(value: Value) -> SpanUsage {
        SpanUsage::from_attributes(value.as_object().unwrap())
    }

    #[test]
    fn reported_total_wins_over_prompt_plus_completion() {
        let u = usage(json!({"genai.total_tokens": 9, "gen_ai.usage.input_tokens": 100}));
        assert_eq!(u.total_tokens, Some(9));
    }

    #[test]
    fn prompt_plus_completion_when_no_total() {
        let u = usage(json!({"gen_ai.usage.input_tokens": 10, "gen_ai.usage.output_tokens": "5"}));
        assert_eq!(u.total_tokens, Some(15));
    }

    #[test]
    fn unreported_usage_stays_unknown() {
        let u = usage(json!({"http.method": "GET"}));
        assert_eq!(u, SpanUsage::default());
    }

    #[test]
    fn cache_read_is_not_folded_into_total() {
        let u = usage(json!({"genai.cache_read_tokens": 4, "genai.prompt_tokens": 6}));
        assert_eq!((u.total_tokens, u.cache_read_tokens), (Some(6), Some(4)));
    }

    #[test]
    fn response_model_wins_over_request_model() {
        let u = usage(json!({
            "gen_ai.request.model": "openai/gpt-5-mini",
            "gen_ai.response.model": "openai/gpt-5-mini-2026-01"
        }));
        assert_eq!(u.model.as_deref(), Some("openai/gpt-5-mini-2026-01"));
    }
}