Skip to content

Commit 07939bb

Browse files
unhappychoiceclaude
andcommitted
refactor(fetcher/claude_code_usage): use shared llm_pricing helper
Drops the per-family hardcoded `PRICE_TABLE` / `cost_usd` / `Price` from `claude/common.rs` and threads the shared `llm_pricing::PriceMap` through the same call sites as the codex refactor in the previous commit. This is a behaviour change for **Opus 4.7 sessions specifically**: the hardcoded table still had Opus at the 4.1-tier $15 / $75 / MTok line, but Anthropic dropped Opus 4.5+ to $5 / $25 / MTok (verified against docs.claude.com pricing on 2026-05-23). Migrating to LiteLLM-derived data unwinds the ~3x over-charge. Sonnet and Haiku figures are unchanged. Module doc updated to reflect the host-fixed HTTP GET that now backs the pricing lookup; safety class stays `Safe`. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent c55aa0c commit 07939bb

2 files changed

Lines changed: 38 additions & 137 deletions

File tree

‎src/fetcher/claude/code_usage.rs‎

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
//! since the configured window, deduplicates by `(message.id, request_id)` keeping the row with
66
//! the higher token total, then groups by project / model / day depending on `group_by`.
77
//!
8-
//! `Safety::Safe` — every read is rooted at a `$HOME`-relative directory the user owns. No
9-
//! network, no token, no exec. Pricing is hardcoded in [`super::common`] so a stale price feed
10-
//! can't disrupt the fetch.
8+
//! `Safety::Safe` — every session read is rooted at a `$HOME`-relative directory the user
9+
//! owns. The fetcher *does* make a single HTTP GET for the LLM pricing snapshot (see
10+
//! [`crate::fetcher::llm_pricing`]) — the URL is hardcoded to splashboard's own GitHub repo,
11+
//! which keeps it under the host-fixed-URL Safe rule. On HTTP failure we fall back to the
12+
//! embedded floor so cost columns stay populated for the headline models.
1113
1214
use std::collections::HashMap;
1315
use std::fs;
@@ -19,9 +21,10 @@ use chrono::{DateTime, Duration, NaiveDate, Utc};
1921
use serde::Deserialize;
2022

2123
use crate::fetcher::claude::common::{
22-
cost_usd, discover_jsonl_dirs, format_cost, format_tokens, project_name_from_cwd,
24+
discover_jsonl_dirs, format_cost, format_tokens, project_name_from_cwd,
2325
};
2426
use crate::fetcher::github::common::{cache_key, parse_options, payload};
27+
use crate::fetcher::llm_pricing::{self, PriceMap};
2528
use crate::fetcher::{FetchContext, FetchError, Fetcher, Safety};
2629
use crate::options::OptionSchema;
2730
use crate::payload::{
@@ -117,11 +120,22 @@ impl Fetcher for ClaudeCodeUsage {
117120
let group_by = parse_group_by(opts.group_by.as_deref())?;
118121
let shape = ctx.shape.unwrap_or(Shape::Text);
119122

120-
let snapshot = build_snapshot(&since, group_by, limit);
123+
let prices = llm_pricing::fetch_pricing(http()).await;
124+
let snapshot = build_snapshot(&since, group_by, limit, &prices);
121125
Ok(payload(render_body(&snapshot, shape)))
122126
}
123127
}
124128

129+
fn http() -> &'static reqwest::Client {
130+
static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
131+
CLIENT.get_or_init(|| {
132+
reqwest::Client::builder()
133+
.user_agent(concat!("splashboard/", env!("CARGO_PKG_VERSION")))
134+
.build()
135+
.expect("reqwest client should build with default config")
136+
})
137+
}
138+
125139
#[derive(Debug, Clone, Copy)]
126140
enum Since {
127141
Today,
@@ -224,23 +238,24 @@ impl UsageEvent {
224238
+ self.cache_write_1h
225239
+ self.cache_read
226240
}
227-
fn cost(&self) -> f64 {
228-
cost_usd(
241+
fn cost(&self, prices: &PriceMap) -> f64 {
242+
llm_pricing::cost_usd(
243+
prices,
229244
&self.model,
230245
self.input_tokens,
231246
self.output_tokens,
247+
self.cache_read,
232248
self.cache_write_5m,
233249
self.cache_write_1h,
234-
self.cache_read,
235250
)
236251
}
237252
}
238253

239-
fn build_snapshot(since: &Since, group_by: GroupBy, limit: usize) -> Snapshot {
254+
fn build_snapshot(since: &Since, group_by: GroupBy, limit: usize, prices: &PriceMap) -> Snapshot {
240255
let events = dedup(collect_events(&discover_jsonl_dirs(), since));
241256
let total_tokens = events.iter().map(UsageEvent::token_total).sum();
242-
let total_cost = events.iter().map(UsageEvent::cost).sum();
243-
let rows = group_rows(&events, group_by, limit);
257+
let total_cost: f64 = events.iter().map(|e| e.cost(prices)).sum();
258+
let rows = group_rows(&events, group_by, limit, prices);
244259
let daily_tokens = daily_series(&events, since);
245260
Snapshot {
246261
rows,
@@ -395,7 +410,12 @@ fn dedup(events: Vec<UsageEvent>) -> Vec<UsageEvent> {
395410
out
396411
}
397412

398-
fn group_rows(events: &[UsageEvent], group_by: GroupBy, limit: usize) -> Vec<UsageRow> {
413+
fn group_rows(
414+
events: &[UsageEvent],
415+
group_by: GroupBy,
416+
limit: usize,
417+
prices: &PriceMap,
418+
) -> Vec<UsageRow> {
399419
let mut by_key: HashMap<String, (u64, f64)> = HashMap::new();
400420
for e in events {
401421
let key = match group_by {
@@ -405,7 +425,7 @@ fn group_rows(events: &[UsageEvent], group_by: GroupBy, limit: usize) -> Vec<Usa
405425
};
406426
let entry = by_key.entry(key).or_insert((0, 0.0));
407427
entry.0 += e.token_total();
408-
entry.1 += e.cost();
428+
entry.1 += e.cost(prices);
409429
}
410430
let mut rows: Vec<UsageRow> = by_key
411431
.into_iter()
@@ -746,7 +766,7 @@ mod tests {
746766
cache_read: 0,
747767
};
748768
let events = vec![make("a", 1_000), make("b", 5_000), make("c", 100)];
749-
let rows = group_rows(&events, GroupBy::Project, 2);
769+
let rows = group_rows(&events, GroupBy::Project, 2, &llm_pricing::embedded_floor());
750770
assert_eq!(rows.len(), 2);
751771
assert_eq!(rows[0].label, "b");
752772
assert_eq!(rows[1].label, "a");
@@ -957,7 +977,7 @@ mod tests {
957977
mk(day1, "b", 2_000),
958978
mk(day2, "c", 500),
959979
];
960-
let rows = group_rows(&events, GroupBy::Day, 10);
980+
let rows = group_rows(&events, GroupBy::Day, 10, &llm_pricing::embedded_floor());
961981
assert_eq!(rows.len(), 2);
962982
// Day 1 contributed 3_000 tokens vs day 2's 500, so it ranks first.
963983
assert!(rows[0].label.ends_with("05-05"));

‎src/fetcher/claude/common.rs‎

Lines changed: 3 additions & 122 deletions
Original file line numberDiff line numberDiff line change
@@ -1,92 +1,11 @@
1-
//! Shared helpers for the `claude_*` family — model pricing, cost math, and the JSONL discovery
1+
//! Shared helpers for the `claude_*` family — formatting helpers and the JSONL discovery
22
//! roots used by `claude_code_usage`.
33
//!
4-
//! Pricing lives in source rather than a vendored JSON file because the set of Claude models is
5-
//! small and changes rarely; bumping a constant is less error-prone than parsing an external table
6-
//! on every fetch. When a new family ships, add a [`PRICE_TABLE`] row matching the model-id prefix.
4+
//! Pricing has moved to the shared [`crate::fetcher::llm_pricing`] module so claude and codex
5+
//! consume the same snapshot. See its module doc for the fetch / fallback story.
76
87
use std::path::PathBuf;
98

10-
/// USD per million tokens for a single Claude model family. Cache write tiers map to Anthropic's
11-
/// `ephemeral_5m` / `ephemeral_1h` breakouts in the usage payload; `cache_read` covers the
12-
/// flat-rate cache-read line.
13-
#[derive(Debug, Clone, Copy)]
14-
pub struct Price {
15-
pub input: f64,
16-
pub output: f64,
17-
pub cache_write_5m: f64,
18-
pub cache_write_1h: f64,
19-
pub cache_read: f64,
20-
}
21-
22-
const OPUS: Price = Price {
23-
input: 15.0,
24-
output: 75.0,
25-
cache_write_5m: 18.75,
26-
cache_write_1h: 30.0,
27-
cache_read: 1.50,
28-
};
29-
30-
const SONNET: Price = Price {
31-
input: 3.0,
32-
output: 15.0,
33-
cache_write_5m: 3.75,
34-
cache_write_1h: 6.0,
35-
cache_read: 0.30,
36-
};
37-
38-
const HAIKU: Price = Price {
39-
input: 1.0,
40-
output: 5.0,
41-
cache_write_5m: 1.25,
42-
cache_write_1h: 2.0,
43-
cache_read: 0.10,
44-
};
45-
46-
/// Prefix table — first match wins, longest-prefix entries appear first so `opus` doesn't shadow
47-
/// a hypothetical `opus-mini`. Match is on the full lowercased model id.
48-
const PRICE_TABLE: &[(&str, Price)] = &[
49-
("claude-opus", OPUS),
50-
("claude-sonnet", SONNET),
51-
("claude-haiku", HAIKU),
52-
// Legacy date-stamped names still seen in older JSONL sessions.
53-
("claude-3-5-sonnet", SONNET),
54-
("claude-3-5-haiku", HAIKU),
55-
("claude-3-opus", OPUS),
56-
("claude-3-sonnet", SONNET),
57-
("claude-3-haiku", HAIKU),
58-
];
59-
60-
pub fn price_for(model: &str) -> Option<Price> {
61-
let lower = model.to_lowercase();
62-
PRICE_TABLE
63-
.iter()
64-
.find(|(prefix, _)| lower.starts_with(prefix))
65-
.map(|(_, p)| *p)
66-
}
67-
68-
/// USD cost of a usage row given a model. Unknown models contribute 0 — surfacing them as
69-
/// "free" is friendlier than hiding the underlying token activity behind an error.
70-
#[allow(clippy::too_many_arguments)]
71-
pub fn cost_usd(
72-
model: &str,
73-
input_tokens: u64,
74-
output_tokens: u64,
75-
cache_write_5m: u64,
76-
cache_write_1h: u64,
77-
cache_read: u64,
78-
) -> f64 {
79-
let Some(p) = price_for(model) else {
80-
return 0.0;
81-
};
82-
let per_token = |rate_per_mt: f64, count: u64| (count as f64) * rate_per_mt / 1_000_000.0;
83-
per_token(p.input, input_tokens)
84-
+ per_token(p.output, output_tokens)
85-
+ per_token(p.cache_write_5m, cache_write_5m)
86-
+ per_token(p.cache_write_1h, cache_write_1h)
87-
+ per_token(p.cache_read, cache_read)
88-
}
89-
909
/// "$12.34" / "$0.05" / "$1.2k" — compact enough to fit a Badge or a Text headline.
9110
pub fn format_cost(usd: f64) -> String {
9211
if usd >= 1_000.0 {
@@ -148,44 +67,6 @@ pub fn project_name_from_cwd(cwd: &str) -> String {
14867
mod tests {
14968
use super::*;
15069

151-
#[test]
152-
fn price_for_matches_opus_sonnet_haiku_by_prefix() {
153-
assert!(price_for("claude-opus-4-7").is_some());
154-
assert!(price_for("claude-sonnet-4-6").is_some());
155-
assert!(price_for("claude-haiku-4-5-20251001").is_some());
156-
assert!(price_for("claude-3-5-sonnet-20241022").is_some());
157-
}
158-
159-
#[test]
160-
fn price_for_unknown_model_returns_none() {
161-
assert!(price_for("gpt-4-turbo").is_none());
162-
assert!(price_for("").is_none());
163-
}
164-
165-
#[test]
166-
fn price_for_is_case_insensitive() {
167-
assert!(price_for("CLAUDE-OPUS-4-7").is_some());
168-
}
169-
170-
#[test]
171-
fn cost_usd_zero_for_unknown_model_even_with_tokens() {
172-
assert_eq!(cost_usd("gpt-4", 1_000_000, 1_000_000, 0, 0, 0), 0.0);
173-
}
174-
175-
#[test]
176-
fn cost_usd_sums_per_tier_rates_against_million_tokens() {
177-
// Opus: 1M input @ $15 + 1M output @ $75 = $90 exactly.
178-
let c = cost_usd("claude-opus-4-7", 1_000_000, 1_000_000, 0, 0, 0);
179-
assert!((c - 90.0).abs() < 1e-6, "expected ~$90, got {c}");
180-
}
181-
182-
#[test]
183-
fn cost_usd_charges_cache_tiers() {
184-
// Sonnet cache_write_1h: 1M @ $6 = $6.
185-
let c = cost_usd("claude-sonnet-4-6", 0, 0, 0, 1_000_000, 0);
186-
assert!((c - 6.0).abs() < 1e-6);
187-
}
188-
18970
#[test]
19071
fn format_cost_picks_unit_by_magnitude() {
19172
assert_eq!(format_cost(0.0), "$0.00");

0 commit comments

Comments
 (0)