Skip to main content

systemprompt_models/wire/canonical/
usage.rs

1//! The canonical token-usage types and their conventions.
2//!
3//! # Reasoning tokens
4//!
5//! `CanonicalUsage::reasoning_tokens` is a **breakdown of** `output_tokens`,
6//! never an addition to it. Providers disagree on the wire, so every adapter
7//! normalises to that one rule before the count reaches billing:
8//!
9//! * `OpenAI` (chat and responses) already folds
10//!   `*_tokens_details.reasoning_tokens` into `completion_tokens` /
11//!   `output_tokens`, so the adapter copies it across untouched.
12//! * Gemini reports `thoughtsTokenCount` *beside* `candidatesTokenCount` (and
13//!   inside `totalTokenCount`), so its adapter adds it into `output_tokens` on
14//!   the way in.
15//! * Anthropic bills thinking as ordinary output tokens and, for adaptive
16//!   thinking on Claude 5 models, reports the share as
17//!   `usage.output_tokens_details.thinking_tokens`; the adapter copies it
18//!   across untouched. Models that report no details yield 0.
19//!
20//! Holding that invariant here is what makes reasoning billable: cost is
21//! computed from `output_tokens`, so a reasoning-only turn is charged at the
22//! output rate with no per-provider arithmetic downstream, and no count is
23//! charged twice. It is also why `reasoning_tokens` is absent from the
24//! `total_tokens` sum in [`CanonicalUsageUpdate::apply_to`].
25//!
26//! Third-party `OpenAI`-compatible upstreams (Cerebras, Moonshot, Qwen) are not
27//! probed, so `CanonicalUsage::normalise_reasoning` enforces the rule at
28//! runtime rather than trusting it: a breakdown cannot exceed its parent, and a
29//! wire `total_tokens` that overshoots `input + output` by exactly the
30//! reasoning count is the same signal: because `input_tokens` excludes cache
31//! reads, an additive provider's wire total is exactly `billable_total() +
32//! reasoning_tokens`, while a conforming one states `billable_total()` alone.
33//! Either signal means the provider reported reasoning *additionally*, so the
34//! count is folded into `output_tokens` and warned about. The total-based half
35//! fires on both paths: [`CanonicalUsageUpdate`] carries the wire's own
36//! `total_tokens` when a frame states one, and
37//! [`CanonicalUsageUpdate::apply_to`] recomputes only when it does not — and a
38//! recomputed total is `billable_total()`, which is never the additive shape.
39//!
40//! # Cache tokens
41//!
42//! `input_tokens` is **exclusive** of `cache_read_tokens` on every wire.
43//! Anthropic reports the two disjointly; `OpenAI`, Gemini and the
44//! `OpenAI`-compatible upstreams report the cached count as a *subset* of the
45//! prompt count, so their adapters subtract it before it reaches this type.
46//! Billing therefore charges each token exactly once, at exactly one rate, and
47//! `CanonicalUsage::billable_total` is the only definition of `tokens_used`.
48//!
49//! Copyright (c) systemprompt.io — Business Source License 1.1.
50//! See <https://systemprompt.io> for licensing details.
51
52#[derive(Debug, Clone, Copy, Default)]
53#[expect(
54    clippy::struct_field_names,
55    reason = "every field is a token count; the `_tokens` suffix is the domain vocabulary shared \
56              with the provider usage wire formats"
57)]
58pub struct CanonicalUsage {
59    // Why: exclusive of cache_read_tokens on every wire -- see the module head.
60    pub input_tokens: u32,
61
62    pub output_tokens: u32,
63    pub cache_read_tokens: u32,
64    pub cache_creation_tokens: u32,
65
66    // Why: a breakdown of output_tokens, not an addition -- see the module
67    // head for the per-provider normalisation and why billing depends on it.
68    pub reasoning_tokens: u32,
69
70    // Why: the wire's own figure when the provider states one; otherwise the
71    // cache-inclusive sum. `normalise_reasoning` reads it as a signal, so it
72    // must not be recomputed when the wire reported it.
73    pub total_tokens: u32,
74}
75
76impl CanonicalUsage {
77    // Why: the single definition of `tokens_used`. Every count is disjoint --
78    // input excludes cache reads, reasoning is inside output -- so this sum
79    // charges each token once and matches what cost_microdollars prices.
80    #[must_use]
81    pub const fn billable_total(&self) -> u32 {
82        self.input_tokens
83            .saturating_add(self.output_tokens)
84            .saturating_add(self.cache_read_tokens)
85            .saturating_add(self.cache_creation_tokens)
86    }
87
88    // Why: enforces the module head's one rule for providers we have never
89    // probed. Returns whether the count had to be folded in, so callers can
90    // assert on it; the warning is emitted here so no call site can forget it.
91    pub fn normalise_reasoning(&mut self, provider: &str) -> bool {
92        // Why: `input_tokens` is exclusive of cache reads, so a provider that
93        // counts reasoning on top of its completion states a wire total of
94        // exactly `billable_total() + reasoning_tokens`. A conforming provider
95        // states `billable_total()` alone, and so does a total the streaming
96        // accumulator recomputed, so both fall outside this shape without
97        // needing a separate exclusion.
98        let additive = self.reasoning_tokens > self.output_tokens
99            || (self.reasoning_tokens > 0
100                && self.total_tokens
101                    == self.billable_total().saturating_add(self.reasoning_tokens));
102        if !additive {
103            return false;
104        }
105        let folded = self.output_tokens.saturating_add(self.reasoning_tokens);
106        tracing::warn!(
107            provider,
108            reasoning_tokens = self.reasoning_tokens,
109            reported_output_tokens = self.output_tokens,
110            folded_output_tokens = folded,
111            "provider reports reasoning tokens in addition to output tokens; folding them in so \
112             the thinking share is billed"
113        );
114        self.output_tokens = folded;
115        self.total_tokens = self.billable_total();
116        true
117    }
118}
119
120/// A streaming usage report, carrying only the counts its frame actually
121/// stated.
122///
123/// [`CanonicalUsage`] cannot express this: an unreported count and a reported
124/// zero are both `0`. Providers differ in what a mid-stream usage frame
125/// includes — an Anthropic `message_delta` may carry `output_tokens` alone —
126/// so folding one in as though it were complete zeroes the input and cache
127/// counts an earlier frame established, and billing loses them.
128#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
129#[expect(
130    clippy::struct_field_names,
131    reason = "every field is a token count; the `_tokens` suffix is the domain vocabulary shared \
132              with the provider usage wire formats"
133)]
134pub struct CanonicalUsageUpdate {
135    pub input_tokens: Option<u32>,
136    pub output_tokens: Option<u32>,
137    pub cache_read_tokens: Option<u32>,
138    pub cache_creation_tokens: Option<u32>,
139    pub reasoning_tokens: Option<u32>,
140
141    // Why: the wire's own total when the frame stated one. Without it every
142    // stream is billed against a recomputed sum, and `normalise_reasoning`
143    // loses its total-based signal on the streaming path entirely.
144    pub total_tokens: Option<u32>,
145}
146
147impl CanonicalUsageUpdate {
148    #[must_use]
149    pub const fn is_empty(&self) -> bool {
150        self.input_tokens.is_none()
151            && self.output_tokens.is_none()
152            && self.cache_read_tokens.is_none()
153            && self.cache_creation_tokens.is_none()
154            && self.reasoning_tokens.is_none()
155            && self.total_tokens.is_none()
156    }
157
158    pub const fn apply_to(&self, usage: &mut CanonicalUsage) {
159        if let Some(v) = self.input_tokens {
160            usage.input_tokens = v;
161        }
162        if let Some(v) = self.output_tokens {
163            usage.output_tokens = v;
164        }
165        if let Some(v) = self.cache_read_tokens {
166            usage.cache_read_tokens = v;
167        }
168        if let Some(v) = self.cache_creation_tokens {
169            usage.cache_creation_tokens = v;
170        }
171        if let Some(v) = self.reasoning_tokens {
172            usage.reasoning_tokens = v;
173        }
174        // Why: reasoning_tokens is a subset of output_tokens, so it is
175        // deliberately absent from the fallback sum -- adding it would
176        // double-count every thinking turn in `total_tokens` and in the cost
177        // derived from it.
178        usage.total_tokens = match self.total_tokens {
179            Some(v) => v,
180            None => usage.billable_total(),
181        };
182    }
183}