Skip to main content

llm_trait/
types.rs

1//! Usage info types.
2
3/// Token usage information for an LLM call.
4#[derive(Clone, Debug, Default)]
5pub struct UsageInfo {
6    pub prompt_tokens: Option<u32>,
7    pub completion_tokens: Option<u32>,
8    pub total_tokens: Option<u32>,
9    /// Tokens used for reasoning / thinking (DeepSeek, OpenAI o-series, etc.).
10    /// Always `None` on the Anthropic protocol: its usage object has no
11    /// thinking breakdown — thinking tokens are folded into
12    /// `completion_tokens`.
13    pub reasoning_tokens: Option<u32>,
14
15    /// Prompt tokens served from the provider's prefix cache, billed at the
16    /// cache-read rate rather than the input rate. Anthropic reports
17    /// `cache_read_input_tokens`; OpenAI reports
18    /// `prompt_tokens_details.cached_tokens`; a protocol whose provider does
19    /// not cache reports `None`. `None` means "unknown", never "zero": a cache
20    /// miss and a counter that does not exist look the same from here.
21    pub cache_read_tokens: Option<u32>,
22}
23
24impl UsageInfo {
25    /// Merge a partial usage event into `self`; the incoming `Some` field
26    /// wins over the existing value, a `None` leaves it untouched.
27    ///
28    /// Streaming protocols may split usage across several events (Anthropic
29    /// sends `prompt_tokens` in `message_start` and the final
30    /// `completion_tokens` in `message_delta`). Replacing the whole struct
31    /// on each event would silently zero out fields the last event omits,
32    /// so consumers must fold events with this method instead.
33    pub fn merge(&mut self, other: &UsageInfo) {
34        if other.prompt_tokens.is_some() {
35            self.prompt_tokens = other.prompt_tokens;
36        }
37        if other.completion_tokens.is_some() {
38            self.completion_tokens = other.completion_tokens;
39        }
40        if other.total_tokens.is_some() {
41            self.total_tokens = other.total_tokens;
42        }
43        if other.reasoning_tokens.is_some() {
44            self.reasoning_tokens = other.reasoning_tokens;
45        }
46        if other.cache_read_tokens.is_some() {
47            self.cache_read_tokens = other.cache_read_tokens;
48        }
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    /// Value: protects=cache hits survive streaming usage folds; fails_when=
57    /// `merge` drops `cache_read_tokens` and the app cannot see what it saved.
58    /// why_new=no test folds cache usage today — the field is new.
59    /// seam=none; no_claim=that a given provider reports it (per protocol).
60    #[test]
61    fn merge_keeps_the_cache_hit_count() {
62        let mut acc = UsageInfo {
63            prompt_tokens: Some(40_000),
64            cache_read_tokens: Some(38_000),
65            ..Default::default()
66        };
67        // Anthropic `message_delta` carries only the output count — a `None`
68        // must not erase the hit count that `message_start` reported.
69        acc.merge(&UsageInfo {
70            completion_tokens: Some(700),
71            ..Default::default()
72        });
73        assert_eq!(acc.cache_read_tokens, Some(38_000));
74        assert_eq!(acc.completion_tokens, Some(700));
75    }
76
77    #[test]
78    fn merge_keeps_existing_when_incoming_none() {
79        let mut acc = UsageInfo {
80            prompt_tokens: Some(5),
81            completion_tokens: Some(2),
82            total_tokens: Some(7),
83            reasoning_tokens: None,
84            cache_read_tokens: None,
85        };
86        // Anthropic `message_delta`: only the final output count arrives.
87        acc.merge(&UsageInfo {
88            prompt_tokens: None,
89            completion_tokens: Some(26),
90            total_tokens: None,
91            reasoning_tokens: None,
92            cache_read_tokens: None,
93        });
94        assert_eq!(
95            acc.prompt_tokens,
96            Some(5),
97            "prompt survives the partial event"
98        );
99        assert_eq!(acc.completion_tokens, Some(26), "later Some wins");
100        assert_eq!(acc.total_tokens, Some(7));
101    }
102
103    #[test]
104    fn merge_lets_later_some_override() {
105        // DashScope's anthropic endpoint reports the full `input_tokens` in
106        // `message_delta` (context so far), superseding the `message_start`
107        // value (latest message only) — the newer number is more useful.
108        let mut acc = UsageInfo {
109            prompt_tokens: Some(2),
110            ..Default::default()
111        };
112        acc.merge(&UsageInfo {
113            prompt_tokens: Some(63),
114            ..Default::default()
115        });
116        assert_eq!(acc.prompt_tokens, Some(63));
117    }
118}