Skip to content

Commit 4497d22

Browse files
committed
feat(pricing): add runtime pricing overrides
Add per-model pricing overrides via ccusage.json. Useful when a model is missing from the embedded LiteLLM snapshot (private deployments, internal wrappers like Pi's `[pi] gpt-5.4`, custom proxies) or when the snapshot price differs from your contract. Config under defaults.pricingOverrides, keyed by raw model name (with adapter prefix where applicable): { "defaults": { "pricingOverrides": { "[pi] gpt-5.4": { "inputCostPerToken": 0.0000025, "outputCostPerToken": 0.000015, "cacheReadInputTokenCost": 0.00000025 } } } } Supported fields: input/output cost, cache create/read cost, tiered above-200k variants, maxInputTokens (statusline context limit), and fastMultiplier. Unspecified fields fall back to the existing LiteLLM entry or 0.0 for new models. Overrides apply in both online and --offline modes; the two flags are orthogonal (--offline controls the data source, pricingOverrides patches specific entries). Behavior fix: the Pi adapter parser previously took usage.cost.total verbatim and ignored CostMode. It now goes through calculate_cost_for_usage, so Auto/Calculate modes recompute from tokens and pricingOverrides apply to Pi entries. Implementation: - PricingMap::load_with_overrides plumbs overrides through every adapter (claude, codex, opencode, qwen, pi, all/loader, statusline hook). - apply_override merges over existing entries, preserving fields the user did not specify; sets cache_read_explicit when cache_read is explicitly provided; writes maxInputTokens to context_limits. - Cache scaling: apply_override scales implicit cache values proportionally when input cost is overridden and cache_read_explicit is false. - Config merge: merge_pricing_overrides now does field-level merge (child config only overwrites fields it explicitly sets, preserving parent fields for the same model). - Pi missing_pricing_model: Pi adapter now calls missing_pricing_model_for_usage so users get a warning when a model has no pricing data in Calculate/Auto modes. - Schema: ConfigPricingOverride exposed via JSON schema with snapshot test covering all fields. - Docs: docs/guide/config-files.md gains a Pricing Overrides section (raw model name convention, supported fields, offline-vs-overrides); cost-modes.md cross-links it. Tests: ~13 unit tests covering apply_override (full / partial / cache_read explicit semantics / max_input_tokens write / preserves existing limit / cache proportional scaling / zero-cache no-scale / explicit cache precedence), config field-level merge (parent preserved / child override), Pi missing_pricing_model (Calculate warns / Display silent / Auto+cost silent); statusline context_window_size test now uses a pricingOverrides fixture for a deterministic assert_eq instead of >= 200_000.
1 parent 1f2bcd5 commit 4497d22

30 files changed

Lines changed: 1174 additions & 83 deletions

File tree

‎apps/ccusage/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ bunx ccusage monthly --compact # Compact monthly report
139139
- 💰 **Cost Tracking**: Shows costs in USD for each day/month/session
140140
- 🔄 **Cache Token Support**: Tracks and displays cache creation and cache read tokens separately
141141
- 🌐 **Offline Mode**: Use pre-cached pricing data without network connectivity with `--offline`
142+
- 🧩 **Custom Pricing Overrides**: Override token pricing per raw model name in `ccusage.json` without rebuilding
142143
- 🏗️ **Claude Instance Support**: Group Claude Code usage by project with `--instances` and filter by specific projects
143144
- 🌍 **Timezone Support**: Configure timezone for date grouping with `--timezone` option
144145
- ⚙️ **Configuration Files**: Set defaults with JSON configuration files, complete with IDE autocomplete and validation

‎ccusage.example.json‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,14 @@
55
"mode": "auto",
66
"timezone": "Asia/Tokyo",
77
"offline": false,
8-
"breakdown": false
8+
"breakdown": false,
9+
"pricingOverrides": {
10+
"[pi] gpt-5.4": {
11+
"inputCostPerToken": 0.0000025,
12+
"outputCostPerToken": 0.000015,
13+
"cacheReadInputTokenCost": 0.00000025
14+
}
15+
}
916
},
1017
"commands": {
1118
"daily": {

‎docs/guide/config-files.md‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,60 @@ ccusage daily --config ./my-config.json
382382
ccusage blocks --config /path/to/team-config.json
383383
```
384384

385+
## Pricing Overrides
386+
387+
ccusage looks up token costs from a LiteLLM pricing snapshot embedded in the binary, optionally refreshed at runtime (or skipped with `--offline`). When a model is missing from LiteLLM (private deployments, internal wrappers like Pi's `[pi] gpt-5.4`, custom proxies), or when the snapshot price differs from your contract, set `pricingOverrides` under `defaults` to supply per-model values.
388+
389+
```json
390+
{
391+
"$schema": "https://ccusage.com/config-schema.json",
392+
"defaults": {
393+
"pricingOverrides": {
394+
"[pi] gpt-5.4": {
395+
"inputCostPerToken": 0.0000025,
396+
"outputCostPerToken": 0.000015,
397+
"cacheReadInputTokenCost": 0.00000025
398+
},
399+
"my-private-claude": {
400+
"inputCostPerToken": 0.000003,
401+
"outputCostPerToken": 0.000015,
402+
"maxInputTokens": 1000000
403+
}
404+
}
405+
}
406+
}
407+
```
408+
409+
### Raw Model Names
410+
411+
Keys in `pricingOverrides` must match the **raw model name** as recorded in the source logs, including any adapter prefix:
412+
413+
| Adapter | Prefix | Example key |
414+
|---------|--------|-------------|
415+
| Pi | `[pi] ` | `[pi] gpt-5.4` |
416+
| Others (Claude, Codex, OpenCode, etc.) | none | `claude-sonnet-4-5`, `gpt-5.5` |
417+
418+
To find the exact name, run `ccusage <agent> daily --json` and look at the `model` field in the per-row breakdown.
419+
420+
### Supported Fields
421+
422+
All fields are optional. Unspecified fields fall back to the LiteLLM entry (when one exists) or `0.0`:
423+
424+
- `inputCostPerToken`, `outputCostPerToken` — base per-token rates
425+
- `cacheCreationInputTokenCost`, `cacheReadInputTokenCost` — cache pricing
426+
- `inputCostPerTokenAbove200kTokens`, `outputCostPerTokenAbove200kTokens`, `cacheCreationInputTokenCostAbove200kTokens`, `cacheReadInputTokenCostAbove200kTokens` — tiered pricing past 200k tokens
427+
- `maxInputTokens` — context window limit (used by the Claude statusline hook)
428+
- `fastMultiplier` — multiplier applied when the message is recorded as fast-mode
429+
430+
### Overrides vs Offline Mode
431+
432+
`--offline` and `pricingOverrides` are independent:
433+
434+
- `--offline` controls the **data source** — skip the network refresh and use the embedded LiteLLM snapshot only.
435+
- `pricingOverrides` controls **specific entries** — patch in or replace prices for individual models.
436+
437+
Overrides apply in both online and offline modes.
438+
385439
This is useful for:
386440

387441
- **Team configurations** - Share configuration files across team members

‎docs/guide/cost-modes.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,3 +345,4 @@ After understanding cost modes:
345345

346346
- Explore [Configuration](/guide/configuration) for environment setup
347347
- Learn about [Claude Code](/guide/claude/) data paths for custom Claude Code directories
348+
- Set per-model prices via [Pricing Overrides](/guide/config-files#pricing-overrides) for private or proxied models

‎rust/crates/ccusage-cli/src/lib.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ mod types;
55

66
pub use types::{
77
normalize_date_bound, AgentCommandArgs, AgentReportKind, BlocksArgs, Cli, CliConfig,
8-
CodexSpeed, Command, CostMode, CostSource, DailyArgs, NoConfig, SessionArgs, SharedArgs,
9-
SortOrder, StatuslineArgs, VisualBurnRate, WeekDay, WeeklyArgs,
8+
CodexSpeed, Command, CostMode, CostSource, DailyArgs, NoConfig, PricingOverride,
9+
SessionArgs, SharedArgs, SortOrder, StatuslineArgs, VisualBurnRate, WeekDay, WeeklyArgs,
1010
};
1111

1212
#[cfg(test)]

‎rust/crates/ccusage-cli/src/types.rs‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::path::PathBuf;
1+
use std::{collections::BTreeMap, path::PathBuf};
22

33
pub struct Cli {
44
pub command: Option<Command>,
@@ -29,7 +29,7 @@ pub enum Command {
2929
OpenClaw(AgentCommandArgs),
3030
}
3131

32-
#[derive(Clone, Default)]
32+
#[derive(Clone, Debug, Default)]
3333
pub struct SharedArgs {
3434
pub since: Option<String>,
3535
pub until: Option<String>,
@@ -48,6 +48,7 @@ pub struct SharedArgs {
4848
pub config: Option<PathBuf>,
4949
pub compact: bool,
5050
pub single_thread: bool,
51+
pub pricing_overrides: BTreeMap<String, PricingOverride>,
5152
}
5253

5354
impl SharedArgs {
@@ -209,6 +210,20 @@ pub enum CostSource {
209210
Both,
210211
}
211212

213+
#[derive(Clone, Debug, Default, PartialEq)]
214+
pub struct PricingOverride {
215+
pub input_cost_per_token: Option<f64>,
216+
pub output_cost_per_token: Option<f64>,
217+
pub cache_creation_input_token_cost: Option<f64>,
218+
pub cache_read_input_token_cost: Option<f64>,
219+
pub input_cost_per_token_above_200k_tokens: Option<f64>,
220+
pub output_cost_per_token_above_200k_tokens: Option<f64>,
221+
pub cache_creation_input_token_cost_above_200k_tokens: Option<f64>,
222+
pub cache_read_input_token_cost_above_200k_tokens: Option<f64>,
223+
pub max_input_tokens: Option<u64>,
224+
pub fast_multiplier: Option<f64>,
225+
}
226+
212227
pub trait CliConfig {
213228
fn apply_shared(&self, _shared: &mut SharedArgs) {}
214229

‎rust/crates/ccusage/src/adapter/all/loader.rs‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@ pub(super) fn load_rows(kind: AgentReportKind, shared: &SharedArgs) -> Result<Al
2626
crate::progress::usage_load_output_is_tty(),
2727
),
2828
);
29-
let pricing = PricingMap::load(shared.offline, crate::log_level() != Some(0));
29+
let pricing = PricingMap::load_with_overrides(
30+
shared.offline,
31+
crate::log_level() != Some(0),
32+
shared.pricing_overrides.iter(),
33+
);
3034
let load_kind = match kind {
3135
AgentReportKind::Session => AgentReportKind::Session,
3236
AgentReportKind::Daily | AgentReportKind::Weekly | AgentReportKind::Monthly => {
@@ -134,6 +138,7 @@ pub(super) fn load_rows(kind: AgentReportKind, shared: &SharedArgs) -> Result<Al
134138
"pi",
135139
load_kind,
136140
&loader_shared,
141+
&pricing,
137142
pi::load_entries,
138143
pi::summarize_entries,
139144
)
@@ -359,10 +364,15 @@ fn load_session_capable_summary_agent_rows(
359364
agent: &'static str,
360365
kind: AgentReportKind,
361366
shared: &SharedArgs,
362-
load_entries: impl FnOnce(&SharedArgs, Option<&str>) -> Result<Vec<LoadedEntry>>,
367+
pricing: &PricingMap,
368+
load_entries: impl FnOnce(
369+
&SharedArgs,
370+
Option<&str>,
371+
Option<&PricingMap>,
372+
) -> Result<Vec<LoadedEntry>>,
363373
summarize_entries: impl FnOnce(&[LoadedEntry], AgentReportKind) -> Result<Vec<UsageSummary>>,
364374
) -> Result<AgentRows> {
365-
let mut entries = load_entries(shared, None)?;
375+
let mut entries = load_entries(shared, None, Some(pricing))?;
366376
let detected = !entries.is_empty();
367377
let summaries = if kind == AgentReportKind::Session {
368378
let mut summaries = summarize_entry_sessions(&entries, shared.timezone.as_deref())?;
@@ -380,13 +390,14 @@ fn load_session_capable_summary_agent_rows(
380390

381391
fn load_claude_rows(kind: AgentReportKind, shared: &SharedArgs) -> Result<AgentRows> {
382392
if kind == AgentReportKind::Session {
383-
return load_session_capable_summary_agent_rows(
384-
"claude",
385-
kind,
386-
shared,
387-
claude::load_entries,
388-
summarize_entries,
389-
);
393+
let entries = claude::load_entries(shared, None)?;
394+
let detected = !entries.is_empty();
395+
let mut summaries = summarize_entry_sessions(&entries, shared.timezone.as_deref())?;
396+
filter_session_summaries(&mut summaries, shared);
397+
return Ok(AgentRows {
398+
rows: summary_rows("claude", summaries),
399+
detected,
400+
});
390401
}
391402

392403
let mut summaries = claude::load_daily_summaries(shared, None, false)?;

‎rust/crates/ccusage/src/adapter/amp/mod.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,11 @@ pub(crate) use report::{print_table_for_agent, report_from_rows, summarize_entri
1515

1616
pub(crate) fn run(args: AgentCommandArgs) -> Result<()> {
1717
let shared = args.shared;
18-
let pricing = PricingMap::load(shared.offline, crate::log_level() != Some(0));
18+
let pricing = PricingMap::load_with_overrides(
19+
shared.offline,
20+
crate::log_level() != Some(0),
21+
shared.pricing_overrides.iter(),
22+
);
1923
let mut entries = load_entries(&shared, &pricing)?;
2024
filter_loaded_entries_by_date(&mut entries, &shared);
2125
let mut rows = summarize_entries(&entries, args.kind)?;

‎rust/crates/ccusage/src/adapter/claude/daily.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,11 @@ pub(super) fn load_daily_summaries_inner(
3939
let pricing = if shared.mode == CostMode::Display {
4040
None
4141
} else {
42-
Some(PricingMap::load(shared.offline, log_level() != Some(0)))
42+
Some(PricingMap::load_with_overrides(
43+
shared.offline,
44+
log_level() != Some(0),
45+
shared.pricing_overrides.iter(),
46+
))
4347
};
4448
let tz = parse_tz(shared.timezone.as_deref());
4549
let mode = shared.mode;

‎rust/crates/ccusage/src/adapter/claude/mod.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,11 @@ fn load_entries_inner(
7474
let pricing = if shared.mode == CostMode::Display {
7575
None
7676
} else {
77-
Some(PricingMap::load(shared.offline, log_level() != Some(0)))
77+
Some(PricingMap::load_with_overrides(
78+
shared.offline,
79+
log_level() != Some(0),
80+
shared.pricing_overrides.iter(),
81+
))
7882
};
7983
let tz = parse_tz(shared.timezone.as_deref());
8084
let mode = shared.mode;

0 commit comments

Comments
 (0)