Skip to main content

rbnx/cmd/
llm_usage.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2//! `rbnx llm-usage` — sum the per-request model usage records that
3//! `robonix_api.llm.metrics` and `robonix-llm-metrics` append.
4
5use anyhow::{Context, Result};
6use serde::Serialize;
7use serde_json::Value;
8use std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10
11/// Requests and reported tokens of one consumer/operation/host/model group.
12#[derive(Debug, Default, PartialEq, Eq, Serialize)]
13struct Total {
14    /// Component that made the requests.
15    consumer: String,
16    /// What the component used the model for.
17    operation: String,
18    /// Endpoint host and port; joined with `model` against a price list.
19    host: String,
20    /// Model named in the requests.
21    model: String,
22    /// Records in the group, one per call.
23    calls: u64,
24    /// Requests sent, retries included.
25    attempts: u64,
26    /// Calls per outcome (`ok`, `http_error`, ...).
27    status: BTreeMap<String, u64>,
28    /// Sum of reported prompt tokens.
29    input_tokens: u64,
30    /// Sum of reported generated tokens.
31    output_tokens: u64,
32    /// Sum of reported cached prompt tokens.
33    cached_input_tokens: u64,
34    /// Sum of reported reasoning tokens.
35    reasoning_tokens: u64,
36    /// Calls whose input or output count was not reported; their tokens are
37    /// missing from the sums.
38    unreported: u64,
39    /// Reported latencies, kept only to compute the summary below.
40    #[serde(skip)]
41    latencies: Vec<u64>,
42    /// Calls that reported a latency.
43    latency_samples: u64,
44    /// Median reported latency in milliseconds.
45    latency_p50_ms: Option<u64>,
46    /// 95th percentile reported latency in milliseconds.
47    latency_p95_ms: Option<u64>,
48    /// Maximum reported latency in milliseconds.
49    latency_max_ms: Option<u64>,
50}
51
52impl Total {
53    /// Sort once, then fill the latency summary fields.
54    fn summarize_latency(&mut self) {
55        self.latency_samples = self.latencies.len() as u64;
56        if self.latencies.is_empty() {
57            return;
58        }
59        self.latencies.sort_unstable();
60        self.latency_p50_ms = Some(percentile(&self.latencies, 0.50));
61        self.latency_p95_ms = Some(percentile(&self.latencies, 0.95));
62        self.latency_max_ms = self.latencies.last().copied();
63    }
64}
65
66/// Nearest-rank percentile of a sorted slice; `fraction` is in `0..=1`.
67fn percentile(sorted: &[u64], fraction: f64) -> u64 {
68    let rank = (fraction * sorted.len() as f64).ceil() as usize;
69    sorted[rank.saturating_sub(1).min(sorted.len() - 1)]
70}
71
72pub fn execute(dir: Option<PathBuf>, boot: Option<&str>, json: bool) -> Result<()> {
73    let dir = dir.unwrap_or_else(|| {
74        std::env::var_os("ROBONIX_LLM_METRICS_DIR")
75            .filter(|d| !d.is_empty())
76            .map_or_else(|| PathBuf::from("./rbnx-boot/llm-metrics"), PathBuf::from)
77    });
78    let (totals, skipped) = sum(&dir, boot)?;
79    if json {
80        for total in &totals {
81            println!("{}", serde_json::to_string(total)?);
82        }
83    } else {
84        print_table(&totals);
85    }
86    if skipped > 0 {
87        eprintln!("rbnx llm-usage: skipped {skipped} unreadable line(s) or file(s)");
88    }
89    Ok(())
90}
91
92/// Totals of every `*.jsonl` record under `dir`, and the count of lines
93/// that were not a record: a line still being written, or an unreadable file
94/// (counted as one).
95fn sum(dir: &Path, boot: Option<&str>) -> Result<(Vec<Total>, u64)> {
96    let entries = std::fs::read_dir(dir).with_context(|| {
97        format!(
98            "{} is not readable; pass -d or set ROBONIX_LLM_METRICS_DIR",
99            dir.display()
100        )
101    })?;
102    let mut groups: BTreeMap<[String; 4], Total> = BTreeMap::new();
103    let mut skipped = 0;
104    for entry in entries.flatten() {
105        let path = entry.path();
106        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
107            continue;
108        }
109        let Ok(text) = std::fs::read_to_string(&path) else {
110            skipped += 1;
111            continue;
112        };
113        for line in text.lines().filter(|line| !line.trim().is_empty()) {
114            let Ok(record) = serde_json::from_str::<Value>(line) else {
115                skipped += 1;
116                continue;
117            };
118            if boot.is_some_and(|boot| record["boot_id"].as_str() != Some(boot)) {
119                continue;
120            }
121            let field = |name: &str| record[name].as_str().unwrap_or_default().to_owned();
122            let key = [
123                field("consumer"),
124                field("operation"),
125                field("host"),
126                field("model"),
127            ];
128            let total = groups.entry(key.clone()).or_insert_with(|| {
129                let [consumer, operation, host, model] = key;
130                Total {
131                    consumer,
132                    operation,
133                    host,
134                    model,
135                    ..Total::default()
136                }
137            });
138            let count = |name: &str| record[name].as_u64();
139            total.calls += 1;
140            total.attempts += count("attempts").unwrap_or(1);
141            *total.status.entry(field("status")).or_default() += 1;
142            total.input_tokens += count("input_tokens").unwrap_or(0);
143            total.output_tokens += count("output_tokens").unwrap_or(0);
144            total.cached_input_tokens += count("cached_input_tokens").unwrap_or(0);
145            total.reasoning_tokens += count("reasoning_tokens").unwrap_or(0);
146            if let Some(latency) = count("latency_ms") {
147                total.latencies.push(latency);
148            }
149            if count("input_tokens").is_none() || count("output_tokens").is_none() {
150                total.unreported += 1;
151            }
152        }
153    }
154    let mut totals: Vec<Total> = groups.into_values().collect();
155    for total in &mut totals {
156        total.summarize_latency();
157    }
158    Ok((totals, skipped))
159}
160
161fn print_table(totals: &[Total]) {
162    println!(
163        "{:<14} {:<16} {:<24} {:<24} {:>6} {:>8} {:>10} {:>10} {:>10} {:>10} {:>10} {:>7} {:>8} {:>8} {:>8}  status",
164        "consumer",
165        "operation",
166        "host",
167        "model",
168        "calls",
169        "attempts",
170        "input",
171        "output",
172        "cached",
173        "reasoning",
174        "unreported",
175        "lat_n",
176        "p50_ms",
177        "p95_ms",
178        "max_ms"
179    );
180    for t in totals {
181        let status = t
182            .status
183            .iter()
184            .map(|(name, count)| format!("{name}={count}"))
185            .collect::<Vec<_>>()
186            .join(" ");
187        println!(
188            "{:<14} {:<16} {:<24} {:<24} {:>6} {:>8} {:>10} {:>10} {:>10} {:>10} {:>10} {:>7} {:>8} {:>8} {:>8}  {status}",
189            t.consumer,
190            t.operation,
191            t.host,
192            t.model,
193            t.calls,
194            t.attempts,
195            t.input_tokens,
196            t.output_tokens,
197            t.cached_input_tokens,
198            t.reasoning_tokens,
199            t.unreported,
200            t.latency_samples,
201            fmt_ms(t.latency_p50_ms),
202            fmt_ms(t.latency_p95_ms),
203            fmt_ms(t.latency_max_ms)
204        );
205    }
206}
207
208/// A latency cell, or `-` when no record reported one.
209fn fmt_ms(value: Option<u64>) -> String {
210    value.map_or_else(|| "-".to_owned(), |value| value.to_string())
211}
212
213#[cfg(test)]
214mod tests {
215    use super::sum;
216
217    #[test]
218    fn sums_by_group_and_boot_and_skips_partial_lines() {
219        let directory = tempfile::tempdir().unwrap();
220        let records = [
221            r#"{"consumer":"pilot","operation":"plan","host":"h","model":"m","status":"ok","attempts":2,"input_tokens":10,"output_tokens":3,"cached_input_tokens":4,"latency_ms":100,"boot_id":"a"}"#,
222            r#"{"consumer":"pilot","operation":"plan","host":"h","model":"m","status":"timeout","attempts":1,"input_tokens":null,"output_tokens":null,"latency_ms":300,"boot_id":"a"}"#,
223            r#"{"consumer":"scene","operation":"caption","host":"h","model":"m","status":"ok","input_tokens":5,"output_tokens":1,"latency_ms":200,"boot_id":"b"}"#,
224            r#"{"consumer":"pilot","operation":"pl"#,
225        ];
226        std::fs::write(directory.path().join("pilot-1.jsonl"), records.join("\n")).unwrap();
227        std::fs::write(directory.path().join("notes.txt"), "not a record").unwrap();
228        std::fs::write(directory.path().join("scene-2.jsonl"), [0xff, 0xfe]).unwrap();
229
230        let (totals, skipped) = sum(directory.path(), None).unwrap();
231        assert_eq!(skipped, 2);
232        assert_eq!(totals.len(), 2);
233        let plan = &totals[0];
234        assert_eq!((plan.calls, plan.attempts), (2, 3));
235        assert_eq!(
236            (
237                plan.input_tokens,
238                plan.output_tokens,
239                plan.cached_input_tokens
240            ),
241            (10, 3, 4)
242        );
243        assert_eq!(plan.unreported, 1);
244        assert_eq!(plan.status.get("timeout"), Some(&1));
245        assert_eq!(
246            (
247                plan.latency_samples,
248                plan.latency_p50_ms,
249                plan.latency_p95_ms,
250                plan.latency_max_ms
251            ),
252            (2, Some(100), Some(300), Some(300))
253        );
254        // A record without `attempts` (an older writer) is one request.
255        assert_eq!(totals[1].attempts, 1);
256        assert_eq!(totals[1].latency_p50_ms, Some(200));
257
258        let (totals, _) = sum(directory.path(), Some("b")).unwrap();
259        assert_eq!(totals.len(), 1);
260        assert_eq!(totals[0].consumer, "scene");
261    }
262}
浙ICP备2023005800号-2 浙公网安备33010902005384号