Skip to main content

eclipse_core/
usage.rs

1//! What one provider call cost, and what the session has cost so far.
2//!
3//! Two dialects report this, and both are worth reading because they say different things:
4//!
5//! - **OpenAI** puts `usage: {prompt_tokens, completion_tokens, total_tokens}`, and, when the
6//!   server caches a prefix, `usage.prompt_tokens_details.cached_tokens`. It says nothing
7//!   about time.
8//! - **llama.cpp** adds `timings: {prompt_n, prompt_ms, predicted_n, predicted_ms, cache_n}`
9//!   — the prefill cost, the decode cost, and how many prompt tokens were reused from the
10//!   KV cache. `prompt_n` counts only the tokens actually processed, so the prompt size is
11//!   `prompt_n + cache_n`; that `cache_n` is the number the status line shows, because a
12//!   warm cache is the difference between a 1 s and a 20 s turn on a local server.
13//!
14//! Everything is optional on purpose. A server that reports nothing is normal, and the UI
15//! then shows `--` rather than inventing a number.
16
17use serde_json::Value;
18
19/// What one provider call cost.
20#[derive(Debug, Clone, Default, PartialEq, Eq)]
21pub struct TurnUsage {
22    pub prompt_tokens: Option<u64>,
23    pub completion_tokens: Option<u64>,
24    pub total_tokens: Option<u64>,
25    /// Prompt tokens served from the server's KV/prefix cache (llama.cpp `cache_n`).
26    pub cached_tokens: Option<u64>,
27    /// Prefill time, when the server distinguishes it.
28    pub prompt_ms: Option<u64>,
29    /// Decode time.
30    pub completion_ms: Option<u64>,
31    /// Wall time of the whole call as this process measured it — always present.
32    pub latency_ms: u64,
33    /// Time to the first streamed character, when the provider streamed at all.
34    pub ttft_ms: Option<u64>,
35}
36
37fn num(v: &Value, pointer: &str) -> Option<u64> {
38    let n = v.pointer(pointer)?;
39    if let Some(i) = n.as_u64() {
40        Some(i)
41    } else {
42        n.as_f64()
43            .filter(|f| f.is_finite() && *f >= 0.0)
44            .map(|f| f.round() as u64)
45    }
46}
47
48impl TurnUsage {
49    /// Read a response body (or a stream's final chunk) plus the wall time we measured.
50    pub fn from_body(body: &Value, latency_ms: u64) -> Self {
51        let prompt = num(body, "/usage/prompt_tokens");
52        let completion = num(body, "/usage/completion_tokens");
53        let cached = num(body, "/usage/prompt_tokens_details/cached_tokens");
54
55        // llama.cpp: prompt_n excludes the cached prefix, so the real prompt is their sum.
56        let llm_prompt = num(body, "/timings/prompt_n");
57        let llm_cached = num(body, "/timings/cache_n");
58        let prompt_tokens = match (prompt, llm_prompt, llm_cached) {
59            (Some(p), _, _) => Some(p),
60            (None, Some(n), Some(c)) => Some(n + c),
61            (None, Some(n), None) => Some(n),
62            _ => None,
63        };
64        let total_tokens = num(body, "/usage/total_tokens").or_else(|| {
65            match (
66                prompt_tokens,
67                num(body, "/timings/predicted_n").or(completion),
68            ) {
69                (Some(p), Some(c)) => Some(p + c),
70                _ => None,
71            }
72        });
73
74        Self {
75            prompt_tokens,
76            completion_tokens: completion.or_else(|| num(body, "/timings/predicted_n")),
77            total_tokens,
78            cached_tokens: cached.or(llm_cached),
79            prompt_ms: num(body, "/timings/prompt_ms"),
80            completion_ms: num(body, "/timings/predicted_ms"),
81            latency_ms,
82            ttft_ms: None,
83        }
84    }
85
86    /// Decode speed. Prefers the server's own decode timing (it excludes prefill), else the
87    /// whole wall time, which is a floor on the real speed rather than a fake precision.
88    pub fn tokens_per_sec(&self) -> Option<f64> {
89        let tokens = self.completion_tokens? as f64;
90        if let Some(done) = self.completion_ms.filter(|m| *m > 0) {
91            return Some(tokens * 1000.0 / done as f64);
92        }
93        (self.latency_ms > 0).then(|| tokens * 1000.0 / self.latency_ms as f64)
94    }
95
96    /// Prefill speed, when the server timed it.
97    pub fn prefill_per_sec(&self) -> Option<f64> {
98        match (self.prompt_tokens, self.prompt_ms) {
99            (Some(tokens), Some(ms)) if ms > 0 => {
100                // prompt_n is the prefill; when we only have prompt_n + cache_n, this is the
101                // honest upper bound rather than a wrong claim.
102                Some(tokens as f64 * 1000.0 / ms as f64)
103            }
104            _ => None,
105        }
106    }
107
108    pub fn is_empty(&self) -> bool {
109        self.prompt_tokens.is_none() && self.completion_tokens.is_none()
110    }
111}
112
113/// Running totals for the whole process, so the status line can show more than the last turn.
114#[derive(Debug, Clone, Default, PartialEq, Eq)]
115pub struct UsageTotals {
116    pub turns: u64,
117    pub prompt_tokens: u64,
118    pub completion_tokens: u64,
119    pub cached_tokens: u64,
120}
121
122impl UsageTotals {
123    pub fn add(&mut self, u: &TurnUsage) {
124        self.turns += 1;
125        self.prompt_tokens += u.prompt_tokens.unwrap_or(0);
126        self.completion_tokens += u.completion_tokens.unwrap_or(0);
127        self.cached_tokens += u.cached_tokens.unwrap_or(0);
128    }
129
130    /// Share of prompt tokens that the server did not have to prefill, 0.0–1.0.
131    pub fn cache_ratio(&self) -> Option<f64> {
132        (self.prompt_tokens > 0).then(|| self.cached_tokens as f64 / self.prompt_tokens as f64)
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139    use serde_json::json;
140
141    #[test]
142    fn reads_the_openai_shape() {
143        let body = json!({"usage": {"prompt_tokens": 1200, "completion_tokens": 55,
144                                    "total_tokens": 1255}});
145        let u = TurnUsage::from_body(&body, 900);
146        assert_eq!(u.prompt_tokens, Some(1200));
147        assert_eq!(u.completion_tokens, Some(55));
148        assert_eq!(u.total_tokens, Some(1255));
149        assert_eq!(u.cached_tokens, None);
150        assert_eq!(u.latency_ms, 900);
151    }
152
153    #[test]
154    fn reads_the_cached_prompt_detail() {
155        let body = json!({"usage": {"prompt_tokens": 2000, "completion_tokens": 10,
156            "prompt_tokens_details": {"cached_tokens": 1920}}});
157        assert_eq!(TurnUsage::from_body(&body, 1).cached_tokens, Some(1920));
158    }
159
160    #[test]
161    fn reads_llamacpp_timings_and_adds_the_cached_prefix() {
162        // prompt_n is what the server actually processed; cache_n was reused on top.
163        let body = json!({"timings": {"prompt_n": 300, "prompt_ms": 250.0,
164                                      "predicted_n": 40, "predicted_ms": 2000.0,
165                                      "cache_n": 1700}});
166        let u = TurnUsage::from_body(&body, 2400);
167        assert_eq!(u.prompt_tokens, Some(2000), "300 processed + 1700 cached");
168        assert_eq!(u.cached_tokens, Some(1700));
169        assert_eq!(u.completion_tokens, Some(40));
170        assert_eq!(u.total_tokens, Some(2040));
171        assert_eq!(u.tokens_per_sec().unwrap().round(), 20.0, "40 tok in 2 s");
172    }
173
174    #[test]
175    fn timings_win_only_where_usage_is_silent() {
176        let body = json!({
177            "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
178            "timings": {"prompt_n": 1, "predicted_n": 999, "cache_n": 0}
179        });
180        let u = TurnUsage::from_body(&body, 100);
181        assert_eq!(u.prompt_tokens, Some(10));
182        assert_eq!(u.completion_tokens, Some(5));
183        assert_eq!(u.total_tokens, Some(15));
184    }
185
186    #[test]
187    fn a_silent_server_reports_nothing_and_says_so() {
188        let u = TurnUsage::from_body(&json!({"choices": []}), 500);
189        assert!(u.is_empty());
190        assert_eq!(u.tokens_per_sec(), None);
191        assert_eq!(u.latency_ms, 500);
192    }
193
194    #[test]
195    fn decode_speed_falls_back_to_wall_time_without_timings() {
196        let u = TurnUsage::from_body(&json!({"usage": {"completion_tokens": 50}}), 1000);
197        assert_eq!(u.tokens_per_sec().unwrap(), 50.0);
198    }
199
200    #[test]
201    fn totals_add_up_and_the_cache_ratio_is_honest() {
202        let mut t = UsageTotals::default();
203        t.add(&TurnUsage::from_body(
204            &json!({"timings": {"prompt_n": 100, "cache_n": 900,
205                                                        "predicted_n": 10}}),
206            1000,
207        ));
208        t.add(&TurnUsage::from_body(
209            &json!({"timings": {"prompt_n": 200, "cache_n": 800,
210                                                        "predicted_n": 10}}),
211            1000,
212        ));
213        assert_eq!(t.turns, 2);
214        assert_eq!(t.prompt_tokens, 2000);
215        assert_eq!(t.cached_tokens, 1700);
216        assert_eq!(t.cache_ratio().unwrap(), 0.85);
217    }
218
219    #[test]
220    fn garbage_fields_do_not_panic_or_go_negative() {
221        let body = json!({"usage": {"prompt_tokens": -5, "completion_tokens": "x"}});
222        let u = TurnUsage::from_body(&body, 0);
223        assert_eq!(u.prompt_tokens, None);
224        assert_eq!(u.completion_tokens, None);
225    }
226}