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