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