stats: log per-request usage in session, add 'hx stats <session>' token report
This commit is contained in:
1 parent
34dea8f9fd
commit
1c69c8ed34
5 files changed
+188
-2
No files matched your search
@@ -0,0 +1,153 @@
|
||||
//! Token report for a session file: API usage per request, cache hit rate, and which tool
|
||||
//! results are the most expensive to carry (bytes x requests they were resent in).
|
||||
|
||||
use crate::session::Session;
|
||||
use hx_ai::{ContentBlock, Role};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
|
||||
pub fn report(s: &Session) -> String {
|
||||
let msgs = s.messages();
|
||||
let mut o = String::new();
|
||||
|
||||
// per-request usage (all entries, so compaction roots are included)
|
||||
let (mut n, mut inp, mut cr, mut cw, mut out) = (0u64, 0u64, 0u64, 0u64, 0u64);
|
||||
let mut last_in = 0;
|
||||
for (_, u) in s.usages() {
|
||||
n += 1;
|
||||
inp += u.input_tokens;
|
||||
cr += u.cache_read_tokens;
|
||||
cw += u.cache_write_tokens;
|
||||
out += u.output_tokens;
|
||||
last_in = u.input_tokens + u.cache_read_tokens + u.cache_write_tokens;
|
||||
}
|
||||
if n == 0 {
|
||||
return "no usage recorded (session predates usage logging)\n".into();
|
||||
}
|
||||
let total_in = inp + cr + cw;
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"requests {n} input {total_in} (fresh {inp}, cache read {cr}, cache write {cw}) output {out}"
|
||||
);
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"cache hit {:.0}% of input avg input/request {} last request {last_in}",
|
||||
100.0 * cr as f64 / total_in.max(1) as f64,
|
||||
total_in / n
|
||||
);
|
||||
|
||||
// carried cost of tool results on the current path
|
||||
let mut names: HashMap<&str, &str> = HashMap::new();
|
||||
for m in &msgs {
|
||||
for b in &m.content {
|
||||
if let ContentBlock::ToolUse { id, name, .. } = b {
|
||||
names.insert(id, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
let asst_after: Vec<usize> = {
|
||||
let mut c = 0;
|
||||
let mut v: Vec<usize> = msgs
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|m| {
|
||||
let r = c;
|
||||
c += (m.role == Role::Assistant) as usize;
|
||||
r
|
||||
})
|
||||
.collect();
|
||||
v.reverse();
|
||||
v
|
||||
};
|
||||
// name -> (calls, bytes, carried bytes)
|
||||
let mut by: HashMap<String, (usize, usize, usize)> = HashMap::new();
|
||||
let mut big: Vec<(usize, usize, String)> = vec![];
|
||||
for (i, m) in msgs.iter().enumerate() {
|
||||
for b in &m.content {
|
||||
let (name, len) = match b {
|
||||
ContentBlock::ToolResult {
|
||||
tool_use_id,
|
||||
content,
|
||||
..
|
||||
} => (
|
||||
names.get(tool_use_id.as_str()).copied().unwrap_or("?"),
|
||||
content.len(),
|
||||
),
|
||||
ContentBlock::Text { text } if m.role == Role::User && i > 0 => {
|
||||
("(injected text)", text.len())
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let e = by.entry(name.to_string()).or_default();
|
||||
e.0 += 1;
|
||||
e.1 += len;
|
||||
e.2 += len * asst_after[i];
|
||||
big.push((len * asst_after[i], len, format!("msg {i} {name}")));
|
||||
}
|
||||
}
|
||||
let mut rows: Vec<_> = by.into_iter().collect();
|
||||
rows.sort_by_key(|(_, v)| std::cmp::Reverse(v.2));
|
||||
let _ = writeln!(o, "\ncarried cost on current branch (tokens ~ bytes/4):");
|
||||
let _ = writeln!(
|
||||
o,
|
||||
"{:<18}{:>6}{:>12}{:>14}",
|
||||
"tool", "calls", "tok once", "tok resent"
|
||||
);
|
||||
for (k, (c, b, carried)) in rows {
|
||||
let _ = writeln!(o, "{k:<18}{c:>6}{:>12}{:>14}", b / 4, carried / 4);
|
||||
}
|
||||
big.sort_by_key(|b| std::cmp::Reverse(b.0));
|
||||
let _ = writeln!(o, "\ntop 5 single items by resent tokens:");
|
||||
for (carried, len, what) in big.into_iter().take(5) {
|
||||
let _ = writeln!(o, " {what}: {} tok once, {} resent", len / 4, carried / 4);
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use hx_ai::{Message, Usage};
|
||||
|
||||
#[test]
|
||||
fn report_counts() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
let mut s = Session::open(d.path().join("s.jsonl")).unwrap();
|
||||
s.append(Message::user("go")).unwrap();
|
||||
let u = Usage {
|
||||
input_tokens: 10,
|
||||
output_tokens: 5,
|
||||
cache_read_tokens: 90,
|
||||
cache_write_tokens: 0,
|
||||
};
|
||||
s.append_full(
|
||||
Message {
|
||||
role: Role::Assistant,
|
||||
content: vec![ContentBlock::ToolUse {
|
||||
id: "t".into(),
|
||||
name: "read".into(),
|
||||
input: serde_json::json!({}),
|
||||
}],
|
||||
},
|
||||
None,
|
||||
Some(u.clone()),
|
||||
)
|
||||
.unwrap();
|
||||
s.append(Message {
|
||||
role: Role::User,
|
||||
content: vec![ContentBlock::ToolResult {
|
||||
tool_use_id: "t".into(),
|
||||
content: "x".repeat(4000),
|
||||
is_error: false,
|
||||
}],
|
||||
})
|
||||
.unwrap();
|
||||
s.append_full(Message::user("done"), None, Some(u)).unwrap();
|
||||
let r = report(&s);
|
||||
assert!(
|
||||
r.contains("requests 2") && r.contains("cache hit 90%"),
|
||||
"{r}"
|
||||
);
|
||||
assert!(r.contains("read") && r.contains("1000"), "{r}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user