Open History to see the last commit
1/**
2 * Model rate lookup and cost arithmetic.
3 *
4 * Rates come from LiteLLM's `model_prices_and_context_window.json`, the same
5 * table `ccusage` prices against. Everything here is pure: fetching and caching
6 * the table lives in `UsageService`.
7 *
8 * @module usagePricing
9 */
10import type { UsageCostSource, UsageModelPriceOverride } from "@t3tools/contracts";
11
12import type { UsageRecord } from "./usageTranscripts.ts";
13
14/**
15 * The subset of a LiteLLM entry we price against. All values are USD per token.
16 *
17 * LiteLLM also publishes tiered variants (`*_above_272k_tokens`, `*_flex`,
18 * `*_priority`, `*_batches`). We deliberately price at the base tier: the
19 * transcripts don't record which tier served a request, so anything else would
20 * be a guess dressed up as precision.
21 */
22export interface ModelRate {
23 readonly inputCostPerToken: number;
24 readonly outputCostPerToken: number;
25 readonly cacheReadCostPerToken: number;
26 readonly cacheCreationCostPerToken: number;
27 /**
28 * Multiple of the rates above billed for a fast-mode request, from LiteLLM's
29 * `provider_specific_entry.fast`. `1` when the model publishes no fast tier.
30 */
31 readonly fastMultiplier: number;
32}
33
34export type RateTable = ReadonlyMap<string, ModelRate>;
35
36/**
37 * Custom IDs keep their case, provider prefix, and variant suffix. Custom rates
38 * apply as entered, fast-mode requests included.
39 */
40export function createOverrideRateTable(
41 overrides: Readonly<Record<string, UsageModelPriceOverride>>,
42): RateTable {
43 return new Map(
44 Object.entries(overrides).map(([model, prices]) => [
45 model.trim(),
46 {
47 inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000,
48 outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000,
49 cacheReadCostPerToken:
50 (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
51 cacheCreationCostPerToken:
52 (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
53 fastMultiplier: 1,
54 },
55 ]),
56 );
57}
58
59/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */
60interface LiteLlmEntry {
61 readonly input_cost_per_token?: unknown;
62 readonly output_cost_per_token?: unknown;
63 readonly cache_read_input_token_cost?: unknown;
64 readonly cache_creation_input_token_cost?: unknown;
65 readonly provider_specific_entry?: unknown;
66}
67
68function finiteNumber(value: unknown): number | null {
69 return typeof value === "number" && Number.isFinite(value) ? value : null;
70}
71
72/** Reads `provider_specific_entry.fast`, e.g. `2` for Claude Opus 5.5. */
73function fastMultiplier(entry: LiteLlmEntry): number {
74 const specific = entry.provider_specific_entry;
75 if (typeof specific !== "object" || specific === null) return 1;
76 const fast = finiteNumber((specific as Record<string, unknown>)["fast"]);
77 return fast !== null && fast > 0 ? fast : 1;
78}
79
80/**
81 * Projects the LiteLLM document into a rate table.
82 *
83 * Entries without both an input and an output rate are dropped: a half-priced
84 * model would silently under-report cost, which is worse than reporting the
85 * model as unpriced.
86 *
87 * Entries keep their full normalized key; a bare name is aliased only when no
88 * canonical entry exists and every qualified entry has the same rate.
89 */
90export function parseRateTable(document: unknown): RateTable {
91 const table = new Map<string, ModelRate>();
92 if (typeof document !== "object" || document === null) return table;
93
94 for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
95 if (typeof raw !== "object" || raw === null) continue;
96 const entry = raw as LiteLlmEntry;
97 const input = finiteNumber(entry.input_cost_per_token);
98 const output = finiteNumber(entry.output_cost_per_token);
99 if (input === null || output === null) continue;
100
101 const key = normalizeRateKey(name);
102 if (key.length === 0) continue;
103 table.set(key, {
104 inputCostPerToken: input,
105 outputCostPerToken: output,
106 // Anthropic bills cache reads at a discount and cache writes at a
107 // premium. When a model omits them, cached input is priced as plain
108 // input rather than as free.
109 cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input,
110 cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input,
111 fastMultiplier: fastMultiplier(entry),
112 });
113 }
114
115 // `null` marks a bare name claimed at conflicting rates: no alias for it.
116 const aliasCandidates = new Map<string, ModelRate | null>();
117 for (const [key, rate] of table) {
118 const alias = bareModelName(key);
119 if (alias.length === 0 || alias === key || table.has(alias)) continue;
120 const held = aliasCandidates.get(alias);
121 if (held === undefined) {
122 aliasCandidates.set(alias, rate);
123 } else if (held !== null && !sameRate(held, rate)) {
124 aliasCandidates.set(alias, null);
125 }
126 }
127 for (const [alias, rate] of aliasCandidates) {
128 if (rate !== null) table.set(alias, rate);
129 }
130
131 return table;
132}
133
134function sameRate(a: ModelRate, b: ModelRate): boolean {
135 return (
136 a.inputCostPerToken === b.inputCostPerToken &&
137 a.outputCostPerToken === b.outputCostPerToken &&
138 a.cacheReadCostPerToken === b.cacheReadCostPerToken &&
139 a.cacheCreationCostPerToken === b.cacheCreationCostPerToken &&
140 a.fastMultiplier === b.fastMultiplier
141 );
142}
143
144function normalizeRateKey(model: string): string {
145 return model.trim().toLowerCase();
146}
147
148function bareModelName(key: string): string {
149 const slash = key.lastIndexOf("/");
150 return slash === -1 ? key : key.slice(slash + 1);
151}
152
153/**
154 * Drops a bracketed variant suffix such as `claude-fable-5-1[1m]`, which
155 * Claude Code writes for the 1M context tier. The rate table only knows the
156 * base name, and we price at the base tier anyway.
157 */
158function stripVariantSuffix(key: string): string {
159 const bracket = key.indexOf("[");
160 return bracket === -1 ? key : key.slice(0, bracket);
161}
162
163/**
164 * Models we never price, regardless of the table.
165 *
166 * `<synthetic>` marks locally generated messages that were never billed. Bare
167 * family names ("opus", "sonnet") are genuinely ambiguous across generations,
168 * so we report them as unpriced instead of guessing a generation.
169 */
170const UNPRICEABLE_MODELS = new Set([
171 "<synthetic>",
172 "synthetic",
173 "opus",
174 "sonnet",
175 "haiku",
176 "fable",
177]);
178
179export function lookupRate(table: RateTable, model: string): ModelRate | null {
180 const key = stripVariantSuffix(normalizeRateKey(model));
181 const bareName = bareModelName(key);
182 if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
183 return table.get(key) ?? null;
184}
185
186/** The parts of a transcript record that decide its price. */
187export type PricedRecord = Pick<UsageRecord, "model" | "totals" | "fast" | "reportedCostUsd">;
188
189export interface PricedUsage {
190 readonly costUsd: number;
191 readonly costSource: UsageCostSource;
192}
193
194/**
195 * Prices one record's tokens.
196 *
197 * `reasoningTokens` is intentionally not charged separately: it is already
198 * counted inside `outputTokens`.
199 */
200export function priceUsage(
201 table: RateTable,
202 record: PricedRecord,
203 overrides?: RateTable,
204): PricedUsage {
205 const { model, totals, reportedCostUsd } = record;
206 const override = overrides?.get(model.trim());
207 if (override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {
208 return { costUsd: reportedCostUsd, costSource: "providerReported" };
209 }
210
211 const rate = override ?? lookupRate(table, model);
212 if (rate === null) return { costUsd: 0, costSource: "unpriced" };
213
214 const standardCostUsd =
215 totals.uncachedInputTokens * rate.inputCostPerToken +
216 totals.cachedInputTokens * rate.cacheReadCostPerToken +
217 totals.cacheCreationTokens * rate.cacheCreationCostPerToken +
218 totals.outputTokens * rate.outputCostPerToken;
219
220 return {
221 costUsd: standardCostUsd * (record.fast ? rate.fastMultiplier : 1),
222 costSource: "modelPriced",
223 };
224}
225
226/**
227 * What the cached input would have cost at full input rates, minus what it
228 * actually cost. Drives the "cache savings" figure.
229 */
230export function cacheSavingsUsd(
231 table: RateTable,
232 record: PricedRecord,
233 overrides?: RateTable,
234): number {
235 const rate = overrides?.get(record.model.trim()) ?? lookupRate(table, record.model);
236 if (rate === null) return 0;
237 return (
238 record.totals.cachedInputTokens *
239 (rate.inputCostPerToken - rate.cacheReadCostPerToken) *
240 (record.fast ? rate.fastMultiplier : 1)
241 );
242}