Count cache tokens in telemetry, budget and report (#16)
This commit was merged in pull request #16.
This commit is contained in:
1 parent
67a5bdedb9
commit
374cf28aed
7 files changed
+90
-13
No files matched your search
+22
-4
@@ -65,6 +65,8 @@ pub fn new_run(task: &Task, repo: &Path, profile: &str) -> Result<Run> {
|
||||
gate_exit: None,
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cache_read_tokens: 0,
|
||||
cache_write_tokens: 0,
|
||||
session: None,
|
||||
attempts: 0,
|
||||
turns: 0,
|
||||
@@ -96,6 +98,20 @@ pub fn hx_env(vars: impl Iterator<Item = (String, String)>, p: &Profile) -> Vec<
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// All tokens of one hx usage object. hx reports `input_tokens` as the uncached part only, so cached input
|
||||
/// (`cache_read_tokens`, `cache_write_tokens`) has to be added or the count is off by orders of magnitude.
|
||||
fn usage_total(u: &Value) -> u64 {
|
||||
[
|
||||
"input_tokens",
|
||||
"output_tokens",
|
||||
"cache_read_tokens",
|
||||
"cache_write_tokens",
|
||||
]
|
||||
.iter()
|
||||
.map(|k| u[*k].as_u64().unwrap_or(0))
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// hx surfaces provider rejections as `api 429: ...`; also match the usual wording.
|
||||
fn is_rate_limit(reason: &str) -> bool {
|
||||
let r = reason.to_lowercase();
|
||||
@@ -343,8 +359,7 @@ fn run_hx(
|
||||
}
|
||||
Some("stream") if ev["event"]["type"] == "done" => {
|
||||
let u = &ev["event"]["usage"];
|
||||
r.spent_tokens += u["input_tokens"].as_u64().unwrap_or(0)
|
||||
+ u["output_tokens"].as_u64().unwrap_or(0);
|
||||
r.spent_tokens += usage_total(u);
|
||||
if p.budget.max_tokens.is_some_and(|m| r.spent_tokens > m) {
|
||||
killed = Some("budget:tokens".to_string());
|
||||
}
|
||||
@@ -372,8 +387,11 @@ fn run_hx(
|
||||
r.hx_pid = None;
|
||||
if let Some(d) = &done {
|
||||
let u = &d["usage"];
|
||||
r.input_tokens = u["input_tokens"].as_u64().unwrap_or(0);
|
||||
r.output_tokens = u["output_tokens"].as_u64().unwrap_or(0);
|
||||
let f = |k: &str| u[k].as_u64().unwrap_or(0);
|
||||
r.input_tokens = f("input_tokens");
|
||||
r.output_tokens = f("output_tokens");
|
||||
r.cache_read_tokens = f("cache_read_tokens");
|
||||
r.cache_write_tokens = f("cache_write_tokens");
|
||||
r.session = d["session"].as_str().map(String::from);
|
||||
}
|
||||
if let Some(k) = killed {
|
||||
|
||||
Reference in new issue
Block a user