Skip to main content

ag_ui/
token_usage.rs

1//! Per-model token accounting carried by `RUN_FINISHED` and `RUN_ERROR`.
2
3use serde::{Deserialize, Serialize};
4
5/// A numeric-only token usage summary for one `(provider, model)` pair.
6///
7/// Deliberately carries nothing identifying or content-bearing — no prompts,
8/// completions, message text, or thread/run/user ids. Only provider and model
9/// labels plus counts, so usage can be logged and aggregated in places where
10/// conversation content must not go.
11///
12/// Every count is optional and every count is a non-negative integer: `None`
13/// means *the provider did not report it*, which is distinct from zero.
14#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
17#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
18pub struct TokenUsage {
19    /// The inference provider, for example `"anthropic"`.
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub provider: Option<String>,
22    /// The model id, for example `"claude-opus-5"`.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub model: Option<String>,
25    /// Tokens consumed by the prompt.
26    #[serde(
27        default,
28        skip_serializing_if = "Option::is_none",
29        serialize_with = "crate::serde_util::serialize_safe_integer"
30    )]
31    pub input_tokens: Option<u64>,
32    /// Tokens produced by the model.
33    #[serde(
34        default,
35        skip_serializing_if = "Option::is_none",
36        serialize_with = "crate::serde_util::serialize_safe_integer"
37    )]
38    pub output_tokens: Option<u64>,
39    /// Input plus output tokens under the protocol's accounting. Cache and
40    /// reasoning counts are already included in those totals.
41    #[serde(
42        default,
43        skip_serializing_if = "Option::is_none",
44        serialize_with = "crate::serde_util::serialize_safe_integer"
45    )]
46    pub total_tokens: Option<u64>,
47    /// Output tokens spent on reasoning.
48    #[serde(
49        default,
50        skip_serializing_if = "Option::is_none",
51        serialize_with = "crate::serde_util::serialize_safe_integer"
52    )]
53    pub reasoning_tokens: Option<u64>,
54    /// Input tokens served from the provider's prompt cache.
55    #[serde(
56        default,
57        skip_serializing_if = "Option::is_none",
58        serialize_with = "crate::serde_util::serialize_safe_integer"
59    )]
60    pub cached_input_tokens: Option<u64>,
61    /// Input tokens written to the provider's prompt cache. Part of
62    /// `input_tokens`, disjoint from `cached_input_tokens`.
63    #[serde(
64        default,
65        skip_serializing_if = "Option::is_none",
66        serialize_with = "crate::serde_util::serialize_safe_integer"
67    )]
68    pub cache_write_input_tokens: Option<u64>,
69}
70
71impl TokenUsage {
72    /// An empty usage entry.
73    pub fn new() -> Self {
74        Self::default()
75    }
76
77    /// Whether any count is present. A labels-only entry reports nothing and
78    /// should be omitted rather than emitted.
79    pub const fn has_counts(&self) -> bool {
80        self.input_tokens.is_some()
81            || self.output_tokens.is_some()
82            || self.total_tokens.is_some()
83            || self.reasoning_tokens.is_some()
84            || self.cached_input_tokens.is_some()
85            || self.cache_write_input_tokens.is_some()
86    }
87}
88
89/// Sums per-call [`TokenUsage`] entries into one entry per `(provider, model)`
90/// pair, in order of first appearance.
91///
92/// A count stays `None` when no member of a group reported it, keeping "not
93/// reported" distinct from zero.
94///
95/// ```
96/// # use ag_ui::{TokenUsage, aggregate_token_usage};
97/// let calls = vec![
98///     TokenUsage { model: Some("m".into()), input_tokens: Some(10), ..Default::default() },
99///     TokenUsage { model: Some("m".into()), input_tokens: Some(5), ..Default::default() },
100/// ];
101/// let total = aggregate_token_usage(&calls);
102/// assert_eq!(total.len(), 1);
103/// assert_eq!(total[0].input_tokens, Some(15));
104/// assert_eq!(total[0].output_tokens, None);
105/// ```
106pub fn aggregate_token_usage(entries: &[TokenUsage]) -> Vec<TokenUsage> {
107    let mut grouped: Vec<TokenUsage> = Vec::new();
108
109    for entry in entries {
110        let index = match grouped
111            .iter()
112            .position(|g| g.provider == entry.provider && g.model == entry.model)
113        {
114            Some(index) => index,
115            None => {
116                grouped.push(TokenUsage {
117                    provider: entry.provider.clone(),
118                    model: entry.model.clone(),
119                    ..Default::default()
120                });
121                grouped.len() - 1
122            }
123        };
124
125        let target = &mut grouped[index];
126        add_into(&mut target.input_tokens, entry.input_tokens);
127        add_into(&mut target.output_tokens, entry.output_tokens);
128        add_into(&mut target.total_tokens, entry.total_tokens);
129        add_into(&mut target.reasoning_tokens, entry.reasoning_tokens);
130        add_into(&mut target.cached_input_tokens, entry.cached_input_tokens);
131        add_into(
132            &mut target.cache_write_input_tokens,
133            entry.cache_write_input_tokens,
134        );
135    }
136
137    grouped
138}
139
140/// Adds `value` into `target`, leaving `target` untouched when nothing was
141/// reported. Saturating, so a hostile producer cannot panic the aggregation.
142fn add_into(target: &mut Option<u64>, value: Option<u64>) {
143    if let Some(value) = value {
144        *target = Some(target.unwrap_or(0).saturating_add(value));
145    }
146}