Skip to main content

agentmux_srv_core/backend/model_gateway/
usage.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a response used, read from the bytes as they pass: the usage block of a Messages response, or of
5//! the `message_start` and `message_delta` events of a stream. Nothing else in the body is kept.
6
7use crate::agents::types::TokenCounts;
8use serde_json::Value;
9
10/// A body larger than this is not buffered to read its usage (a stream is read line by line instead).
11const MAX_JSON_BODY: usize = 8 * 1024 * 1024;
12/// A single stream line longer than this is dropped rather than held.
13const MAX_LINE: usize = 1024 * 1024;
14
15pub struct UsageTap {
16    stream: bool,
17    pending: Vec<u8>,
18    body: Vec<u8>,
19    counts: TokenCounts,
20    model: Option<String>,
21    /// The provider's own charge for the response, when it reports one
22    /// (OpenRouter's `usage.cost`): the real figure, not a price-table
23    /// estimate (#30143).
24    cost_usd: Option<f64>,
25    /// The five-minute and one-hour cache writes, when the usage block separates them.
26    cache_split: Option<(u64, u64)>,
27}
28
29impl UsageTap {
30    /// `stream`: the response is `text/event-stream`.
31    pub fn new(stream: bool) -> Self {
32        Self { stream, pending: Vec::new(), body: Vec::new(), counts: TokenCounts::default(), model: None, cost_usd: None, cache_split: None }
33    }
34
35    pub fn push(&mut self, chunk: &[u8]) {
36        if !self.stream {
37            if self.body.len() + chunk.len() <= MAX_JSON_BODY {
38                self.body.extend_from_slice(chunk);
39            }
40            return;
41        }
42        self.pending.extend_from_slice(chunk);
43        while let Some(end) = self.pending.iter().position(|b| *b == b'\n') {
44            let line: Vec<u8> = self.pending.drain(..=end).collect();
45            self.line(&line);
46        }
47        if self.pending.len() > MAX_LINE {
48            self.pending.clear();
49        }
50    }
51
52    fn line(&mut self, line: &[u8]) {
53        let Ok(text) = std::str::from_utf8(line) else { return };
54        let Some(data) = text.trim().strip_prefix("data:") else { return };
55        if let Ok(event) = serde_json::from_str::<Value>(data.trim()) {
56            self.event(&event);
57        }
58    }
59
60    fn event(&mut self, event: &Value) {
61        match event.get("type").and_then(Value::as_str) {
62            Some("message_start") => {
63                let message = event.get("message").unwrap_or(&Value::Null);
64                self.model = message.get("model").and_then(Value::as_str).map(str::to_string);
65                self.usage(message.get("usage"));
66            }
67            Some("message_delta") => self.usage(event.get("usage")),
68            // An answer the gateway ended in an error was still generated and charged: its error carries what it used.
69            Some("error") => self.usage(event.get("usage")),
70            _ => {}
71        }
72    }
73
74    /// Later counts replace earlier ones: a stream reports running totals, and a field it leaves out keeps its value.
75    fn usage(&mut self, usage: Option<&Value>) {
76        let Some(usage) = usage else { return };
77        let read = |key: &str| usage.get(key).and_then(Value::as_u64);
78        if let Some(n) = read("input_tokens") {
79            self.counts.input = n;
80        }
81        if let Some(n) = read("output_tokens") {
82            self.counts.output = n;
83        }
84        if let Some(n) = read("cache_creation_input_tokens") {
85            self.counts.cache_creation = n;
86        }
87        if let Some(n) = read("cache_read_input_tokens") {
88            self.counts.cache_read = n;
89        }
90        if let Some(split) = usage.get("cache_creation").filter(|v| v.is_object()) {
91            let part = |key: &str| split.get(key).and_then(Value::as_u64).unwrap_or(0);
92            self.cache_split = Some((part("ephemeral_5m_input_tokens"), part("ephemeral_1h_input_tokens")));
93        }
94        if let Some(cost) = usage.get("cost").and_then(Value::as_f64).filter(|c| c.is_finite() && *c >= 0.0) {
95            self.cost_usd = Some(cost);
96        }
97    }
98
99    /// The counts, the model the upstream says answered, and its own charge
100    /// for the response when it reported one.
101    pub fn finish(self) -> (TokenCounts, Option<String>, Option<f64>) {
102        let (counts, model, cost, _) = self.finish_with_split();
103        (counts, model, cost)
104    }
105
106    /// [`finish`](Self::finish), and the five-minute and one-hour cache writes when the response separated them.
107    pub fn finish_with_split(mut self) -> (TokenCounts, Option<String>, Option<f64>, Option<(u64, u64)>) {
108        if !self.stream {
109            if let Ok(body) = serde_json::from_slice::<Value>(&self.body) {
110                self.model = body.get("model").and_then(Value::as_str).map(str::to_string);
111                self.usage(body.get("usage"));
112            }
113        }
114        (self.counts, self.model, self.cost_usd, self.cache_split)
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    const STREAM: &str = concat!(
123        "event: message_start\n",
124        "data: {\"type\":\"message_start\",\"message\":{\"model\":\"deepseek/deepseek-v4.1-flash-1017\",\"usage\":{\"input_tokens\":120,\"cache_read_input_tokens\":40,\"output_tokens\":1}}}\n\n",
125        "event: content_block_delta\n",
126        "data: {\"type\":\"content_block_delta\",\"delta\":{\"text\":\"hi\"}}\n\n",
127        "event: message_delta\n",
128        "data: {\"type\":\"message_delta\",\"usage\":{\"output_tokens\":57,\"cost\":0.00123}}\n\n",
129    );
130
131    #[test]
132    fn a_stream_is_read_whatever_the_chunking() {
133        for size in [1, 7, 64, STREAM.len()] {
134            let mut tap = UsageTap::new(true);
135            for chunk in STREAM.as_bytes().chunks(size) {
136                tap.push(chunk);
137            }
138            let (counts, model, cost) = tap.finish();
139            assert_eq!((counts.input, counts.output, counts.cache_read), (120, 57, 40), "chunks of {size}");
140            assert_eq!(model.as_deref(), Some("deepseek/deepseek-v4.1-flash-1017"));
141            assert_eq!(cost, Some(0.00123), "the provider's own charge rides the stream");
142        }
143    }
144
145    #[test]
146    fn the_five_minute_and_one_hour_cache_writes_are_read_when_the_usage_separates_them() {
147        let mut tap = UsageTap::new(false);
148        tap.push(br#"{"model":"m","usage":{"input_tokens":9,"output_tokens":3,"cache_creation_input_tokens":300,"cache_creation":{"ephemeral_5m_input_tokens":100,"ephemeral_1h_input_tokens":200}}}"#);
149        let (counts, _, _, split) = tap.finish_with_split();
150        assert_eq!((counts.cache_creation, split), (300, Some((100, 200))));
151        let mut plain = UsageTap::new(false);
152        plain.push(br#"{"usage":{"cache_creation_input_tokens":300}}"#);
153        assert_eq!(plain.finish_with_split().3, None, "not separated: the dearest rate counts");
154    }
155
156    #[test]
157    fn a_plain_response_is_read_at_the_end() {
158        let mut tap = UsageTap::new(false);
159        tap.push(br#"{"model":"m","usage":{"input_tokens":9,"output_tokens":3}"#);
160        tap.push(b"}");
161        let (counts, model, cost) = tap.finish();
162        assert_eq!((counts.input, counts.output, model.as_deref()), (9, 3, Some("m")));
163        assert_eq!(cost, None, "no charge reported: the price table estimates it");
164    }
165
166    #[test]
167    fn text_that_is_not_an_event_is_ignored() {
168        let mut tap = UsageTap::new(true);
169        tap.push(b": keep-alive\n\ndata: not json\n\ndata: [DONE]\n");
170        assert_eq!(tap.finish().0, TokenCounts::default());
171    }
172}