Open History to see the last commit
1import type {
2 UsageCategoryCost,
3 UsageCostSource,
4 UsageModelPriceOverride,
5 UsageTokenTotals,
6} from "@t3tools/contracts";
7
8import type { UsageRecord, UsageSpeed } from "@t3tools/provider-core/server/usage";
9
10export interface TokenRates {
11 readonly inputCostPerToken: number;
12 readonly outputCostPerToken: number;
13 readonly cacheReadCostPerToken: number;
14 readonly cacheCreationCostPerToken: number;
15}
16
17/**
18 * LiteLLM also publishes `*_above_272k_tokens`, `*_flex`, and `*_batches` variants. Transcripts
19 * don't record those, so we don't price them.
20 */
21export interface ModelRate extends TokenRates {
22 readonly fast: TokenRates | null;
23 readonly ultrafast: TokenRates | null;
24}
25
26export type RateTable = ReadonlyMap<string, ModelRate>;
27
28export function createOverrideRateTable(
29 overrides: Readonly<Record<string, UsageModelPriceOverride>>,
30): RateTable {
31 return new Map(
32 Object.entries(overrides).map(([model, prices]) => [
33 model.trim(),
34 {
35 inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000,
36 outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000,
37 cacheReadCostPerToken:
38 (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
39 cacheCreationCostPerToken:
40 (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
41 fast: null,
42 ultrafast: null,
43 },
44 ]),
45 );
46}
47
48type LiteLlmEntry = Readonly<Record<string, unknown>>;
49
50function finiteNumber(value: unknown): number | null {
51 return typeof value === "number" && Number.isFinite(value) ? value : null;
52}
53
54/**
55 * Anthropic bills cache reads at a discount and cache writes at a premium. When the standard
56 * tier omits them, cached input is priced as plain input rather than as free.
57 */
58function readTokenRates(
59 entry: LiteLlmEntry,
60 suffix: string,
61 standard?: TokenRates,
62): TokenRates | null {
63 const input = finiteNumber(entry[`input_cost_per_token${suffix}`]);
64 const output = finiteNumber(entry[`output_cost_per_token${suffix}`]);
65 if (input === null || output === null) return null;
66 const cacheRate = (name: string, field: "cacheReadCostPerToken" | "cacheCreationCostPerToken") =>
67 finiteNumber(entry[`${name}${suffix}`]) ??
68 (standard !== undefined && standard.inputCostPerToken > 0
69 ? (standard[field] / standard.inputCostPerToken) * input
70 : input);
71 return {
72 inputCostPerToken: input,
73 outputCostPerToken: output,
74 cacheReadCostPerToken: cacheRate("cache_read_input_token_cost", "cacheReadCostPerToken"),
75 cacheCreationCostPerToken: cacheRate(
76 "cache_creation_input_token_cost",
77 "cacheCreationCostPerToken",
78 ),
79 };
80}
81
82function scaleTokenRates(rates: TokenRates, multiple: number): TokenRates {
83 return {
84 inputCostPerToken: rates.inputCostPerToken * multiple,
85 outputCostPerToken: rates.outputCostPerToken * multiple,
86 cacheReadCostPerToken: rates.cacheReadCostPerToken * multiple,
87 cacheCreationCostPerToken: rates.cacheCreationCostPerToken * multiple,
88 };
89}
90
91function fastMultiplier(entry: LiteLlmEntry): number | null {
92 const specific = entry["provider_specific_entry"];
93 if (typeof specific !== "object" || specific === null) return null;
94 const fast = finiteNumber((specific as Record<string, unknown>)["fast"]);
95 return fast !== null && fast > 0 ? fast : null;
96}
97
98/**
99 * Entries without both an input and an output rate are dropped: a half-priced model would
100 * silently under-report cost, which is worse than reporting the model as unpriced.
101 */
102export function parseRateTable(document: unknown): RateTable {
103 const table = new Map<string, ModelRate>();
104 if (typeof document !== "object" || document === null) return table;
105
106 for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
107 if (typeof raw !== "object" || raw === null) continue;
108 const entry = raw as LiteLlmEntry;
109 const standard = readTokenRates(entry, "");
110 if (standard === null) continue;
111
112 const key = normalizeRateKey(name);
113 if (key.length === 0) continue;
114 const multiple = fastMultiplier(entry);
115 table.set(key, {
116 ...standard,
117 fast:
118 multiple === null
119 ? readTokenRates(entry, "_priority", standard)
120 : scaleTokenRates(standard, multiple),
121 ultrafast: readTokenRates(entry, "_ultrafast", standard),
122 });
123 }
124
125 const aliasCandidates = new Map<string, ModelRate | null>();
126 for (const [key, rate] of table) {
127 const alias = bareModelName(key);
128 if (alias.length === 0 || alias === key || table.has(alias)) continue;
129 const held = aliasCandidates.get(alias);
130 if (held === undefined) {
131 aliasCandidates.set(alias, rate);
132 } else if (held !== null && !sameRate(held, rate)) {
133 aliasCandidates.set(alias, null);
134 }
135 }
136 for (const [alias, rate] of aliasCandidates) {
137 if (rate !== null) table.set(alias, rate);
138 }
139
140 return table;
141}
142
143function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean {
144 if (a === null || b === null) return a === b;
145 return (
146 a.inputCostPerToken === b.inputCostPerToken &&
147 a.outputCostPerToken === b.outputCostPerToken &&
148 a.cacheReadCostPerToken === b.cacheReadCostPerToken &&
149 a.cacheCreationCostPerToken === b.cacheCreationCostPerToken
150 );
151}
152
153function sameRate(a: ModelRate, b: ModelRate): boolean {
154 return (
155 sameTokenRates(a, b) &&
156 sameTokenRates(a.fast, b.fast) &&
157 sameTokenRates(a.ultrafast, b.ultrafast)
158 );
159}
160
161function ratesAt(rate: ModelRate, speed: UsageSpeed): TokenRates {
162 return (speed === "standard" ? null : rate[speed]) ?? rate;
163}
164
165function normalizeRateKey(model: string): string {
166 return model.trim().toLowerCase();
167}
168
169function bareModelName(key: string): string {
170 const slash = key.lastIndexOf("/");
171 return slash === -1 ? key : key.slice(slash + 1);
172}
173
174/**
175 * Drops a bracketed variant suffix such as `claude-fable-5-1[1m]`, which
176 * Claude Code writes for the 1M context tier. The rate table only knows the
177 * base name, and we price at the base tier anyway.
178 */
179function stripVariantSuffix(key: string): string {
180 const bracket = key.indexOf("[");
181 return bracket === -1 ? key : key.slice(0, bracket);
182}
183
184/**
185 * `<synthetic>` marks locally generated messages that were never billed. Bare family names
186 * ("opus", "sonnet") are genuinely ambiguous across generations, so we report them as unpriced
187 * instead of guessing a generation.
188 */
189const UNPRICEABLE_MODELS = new Set([
190 "<synthetic>",
191 "synthetic",
192 "opus",
193 "sonnet",
194 "haiku",
195 "fable",
196]);
197
198/**
199 * A scan prices every record twice against a few dozen models, and tables are
200 * never mutated once built.
201 */
202const resolvedRates = new WeakMap<RateTable, Map<string, ModelRate | null>>();
203
204export function lookupRate(table: RateTable, model: string): ModelRate | null {
205 let resolved = resolvedRates.get(table);
206 if (resolved === undefined) {
207 resolved = new Map();
208 resolvedRates.set(table, resolved);
209 }
210 let rate = resolved.get(model);
211 if (rate === undefined) {
212 rate = resolveRate(table, model);
213 resolved.set(model, rate);
214 }
215 return rate;
216}
217
218function resolveRate(table: RateTable, model: string): ModelRate | null {
219 const key = stripVariantSuffix(normalizeRateKey(model));
220 const bareName = bareModelName(key);
221 if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
222 return table.get(key) ?? null;
223}
224
225export type PricedRecord = Pick<
226 UsageRecord,
227 "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd"
228>;
229
230export interface PricedUsage {
231 readonly costUsd: number;
232 readonly costSource: UsageCostSource;
233 readonly categoryCostUsd: UsageCategoryCost | null;
234 readonly speedPremiumUsd: number;
235}
236
237function costByCategory(totals: UsageTokenTotals, rates: TokenRates): UsageCategoryCost {
238 return {
239 input: totals.uncachedInputTokens * rates.inputCostPerToken,
240 cacheRead: totals.cachedInputTokens * rates.cacheReadCostPerToken,
241 cacheWrite: totals.cacheCreationTokens * rates.cacheCreationCostPerToken,
242 output: totals.outputTokens * rates.outputCostPerToken,
243 };
244}
245
246function sumCategories(cost: UsageCategoryCost): number {
247 return cost.input + cost.cacheRead + cost.cacheWrite + cost.output;
248}
249
250/**
251 * `reasoningTokens` is intentionally not charged separately: it is already
252 * counted inside `outputTokens`.
253 */
254export function priceUsage(
255 table: RateTable,
256 record: PricedRecord,
257 overrides?: RateTable,
258): PricedUsage {
259 const { model, totals, reportedCostUsd } = record;
260 const override = overrides?.get(model.trim());
261 const reported =
262 override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)
263 ? reportedCostUsd
264 : null;
265 const unsplit = (costUsd: number, costSource: UsageCostSource): PricedUsage => ({
266 costUsd,
267 costSource,
268 categoryCostUsd: null,
269 speedPremiumUsd: 0,
270 });
271 const rate = override ?? lookupRate(table, record.rateModel ?? model);
272 if (rate === null) {
273 return reported === null ? unsplit(0, "unpriced") : unsplit(reported, "providerReported");
274 }
275
276 const listCost = costByCategory(totals, ratesAt(rate, record.speed));
277 const listCostUsd = sumCategories(listCost);
278 if (reported !== null && listCostUsd <= 0) return unsplit(reported, "providerReported");
279 const premiumUsd =
280 record.speed === "standard" ? 0 : listCostUsd - sumCategories(costByCategory(totals, rate));
281 const scale = reported === null ? 1 : reported / listCostUsd;
282 return {
283 costUsd: reported ?? listCostUsd,
284 costSource: reported === null ? "modelPriced" : "providerReported",
285 categoryCostUsd: {
286 input: listCost.input * scale,
287 cacheRead: listCost.cacheRead * scale,
288 cacheWrite: listCost.cacheWrite * scale,
289 output: listCost.output * scale,
290 },
291 speedPremiumUsd: premiumUsd * scale,
292 };
293}
294
295export function cacheSavingsUsd(
296 table: RateTable,
297 record: PricedRecord,
298 overrides?: RateTable,
299): number {
300 const rate =
301 overrides?.get(record.model.trim()) ?? lookupRate(table, record.rateModel ?? record.model);
302 if (rate === null) return 0;
303 const rates = ratesAt(rate, record.speed);
304 return record.totals.cachedInputTokens * (rates.inputCostPerToken - rates.cacheReadCostPerToken);
305}