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
130/**
131 * Canonicalises a model name for lookup.
132 *
133 * Strips a `provider/` prefix and lowercases, since transcripts are
134 * inconsistent about casing.
135 */
136export function normalizeModelName(model: string): string {
137 return bareModelName(normalizeRateKey(model));
138}
139
140function bareModelName(key: string): string {
141 const slash = key.lastIndexOf("/");
142 return slash === -1 ? key : key.slice(slash + 1);
143}
144
145/**
146 * Drops a bracketed variant suffix such as `claude-fable-5-1[1m]`, which
147 * Claude Code writes for the 1M context tier. The rate table only knows the
148 * base name, and we price at the base tier anyway.
149 */
150function stripVariantSuffix(key: string): string {
151 const bracket = key.indexOf("[");
152 return bracket === -1 ? key : key.slice(0, bracket);
153}
154
155/**
156 * Models we never price, regardless of the table.
157 *
158 * `<synthetic>` marks locally generated messages that were never billed. Bare
159 * family names ("opus", "sonnet") are genuinely ambiguous across generations,
160 * so we report them as unpriced instead of guessing a generation.
161 */
162const UNPRICEABLE_MODELS = new Set([
163 "<synthetic>",
164 "synthetic",
165 "opus",
166 "sonnet",
167 "haiku",
168 "fable",
169]);
170
171export function lookupRate(table: RateTable, model: string): ModelRate | null {
172 const key = stripVariantSuffix(normalizeRateKey(model));
173 const bareName = bareModelName(key);
174 if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
175 return table.get(key) ?? null;
176}
177
178export interface PricedUsage {
179 readonly costUsd: number;
180 readonly costSource: UsageCostSource;
181}
182
183/**
184 * Prices a bucket's tokens.
185 *
186 * `reasoningTokens` is intentionally not charged separately: it is already
187 * counted inside `outputTokens`.
188 */
189export function priceUsage(
190 table: RateTable,
191 model: string,
192 totals: UsageTokenTotals,
193 reportedCostUsd: number | null,
194 overrides?: RateTable,
195): PricedUsage {
196 const override = overrides?.get(model.trim());
197 if (override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {
198 return { costUsd: reportedCostUsd, costSource: "providerReported" };
199 }
200
201 const rate = override ?? lookupRate(table, model);
202 if (rate === null) return { costUsd: 0, costSource: "unpriced" };
203
204 const costUsd =
205 totals.uncachedInputTokens * rate.inputCostPerToken +
206 totals.cachedInputTokens * rate.cacheReadCostPerToken +
207 totals.cacheCreationTokens * rate.cacheCreationCostPerToken +
208 totals.outputTokens * rate.outputCostPerToken;
209
210 return { costUsd, costSource: "modelPriced" };
211}
212
213/**
214 * What the cached input would have cost at full input rates, minus what it
215 * actually cost. Drives the "cache savings" figure.
216 */
217export function cacheSavingsUsd(
218 table: RateTable,
219 model: string,
220 totals: UsageTokenTotals,
221 overrides?: RateTable,
222): number {
223 const rate = overrides?.get(model.trim()) ?? lookupRate(table, model);
224 if (rate === null) return 0;
225 return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken);
226}