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/** Omits LiteLLM's above_272k_tokens, flex and batches variants, which transcripts do not record. */
18export interface ModelRate extends TokenRates {
19 readonly fast: TokenRates | null;
20 readonly ultrafast: TokenRates | null;
21}
22
23export type RateTable = ReadonlyMap<string, ModelRate>;
24
25export function createOverrideRateTable(
26 overrides: Readonly<Record<string, UsageModelPriceOverride>>,
27): RateTable {
28 return new Map(
29 Object.entries(overrides).map(([model, prices]) => [
30 model.trim(),
31 {
32 inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000,
33 outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000,
34 cacheReadCostPerToken:
35 (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
36 cacheCreationCostPerToken:
37 (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
38 fast: null,
39 ultrafast: null,
40 },
41 ]),
42 );
43}
44
45type LiteLlmEntry = Readonly<Record<string, unknown>>;
46
47function finiteNumber(value: unknown): number | null {
48 return typeof value === "number" && Number.isFinite(value) ? value : null;
49}
50
51// Missing cache rates fall back to input pricing; Anthropic normally discounts reads and charges extra for writes.
52function readTokenRates(
53 entry: LiteLlmEntry,
54 suffix: string,
55 standard?: TokenRates,
56): TokenRates | null {
57 const input = finiteNumber(entry[`input_cost_per_token${suffix}`]);
58 const output = finiteNumber(entry[`output_cost_per_token${suffix}`]);
59 if (input === null || output === null) return null;
60 const cacheRate = (name: string, field: "cacheReadCostPerToken" | "cacheCreationCostPerToken") =>
61 finiteNumber(entry[`${name}${suffix}`]) ??
62 (standard !== undefined && standard.inputCostPerToken > 0
63 ? (standard[field] / standard.inputCostPerToken) * input
64 : input);
65 return {
66 inputCostPerToken: input,
67 outputCostPerToken: output,
68 cacheReadCostPerToken: cacheRate("cache_read_input_token_cost", "cacheReadCostPerToken"),
69 cacheCreationCostPerToken: cacheRate(
70 "cache_creation_input_token_cost",
71 "cacheCreationCostPerToken",
72 ),
73 };
74}
75
76function scaleTokenRates(rates: TokenRates, multiple: number): TokenRates {
77 return {
78 inputCostPerToken: rates.inputCostPerToken * multiple,
79 outputCostPerToken: rates.outputCostPerToken * multiple,
80 cacheReadCostPerToken: rates.cacheReadCostPerToken * multiple,
81 cacheCreationCostPerToken: rates.cacheCreationCostPerToken * multiple,
82 };
83}
84
85function fastMultiplier(entry: LiteLlmEntry): number | null {
86 const specific = entry["provider_specific_entry"];
87 if (typeof specific !== "object" || specific === null) return null;
88 const fast = finiteNumber((specific as Record<string, unknown>)["fast"]);
89 return fast !== null && fast > 0 ? fast : null;
90}
91
92/** Drops models missing input or output rates to avoid understating cost. */
93export function parseRateTable(document: unknown): RateTable {
94 const table = new Map<string, ModelRate>();
95 if (typeof document !== "object" || document === null) return table;
96
97 for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
98 if (typeof raw !== "object" || raw === null) continue;
99 const entry = raw as LiteLlmEntry;
100 const standard = readTokenRates(entry, "");
101 if (standard === null) continue;
102
103 const key = normalizeRateKey(name);
104 if (key.length === 0) continue;
105 const multiple = fastMultiplier(entry);
106 table.set(key, {
107 ...standard,
108 fast:
109 multiple === null
110 ? readTokenRates(entry, "_priority", standard)
111 : scaleTokenRates(standard, multiple),
112 ultrafast: readTokenRates(entry, "_ultrafast", standard),
113 });
114 }
115
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) {
124 aliasCandidates.set(alias, mergeAliasRate(held, rate));
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 sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean {
135 if (a === null || b === null) return a === b;
136 return (
137 a.inputCostPerToken === b.inputCostPerToken &&
138 a.outputCostPerToken === b.outputCostPerToken &&
139 a.cacheReadCostPerToken === b.cacheReadCostPerToken &&
140 a.cacheCreationCostPerToken === b.cacheCreationCostPerToken
141 );
142}
143
144// Resellers often omit speed tiers, so a missing tier fills from the other entry instead of conflicting.
145function mergeAliasRate(a: ModelRate, b: ModelRate): ModelRate | null {
146 const fast = a.fast ?? b.fast;
147 const ultrafast = a.ultrafast ?? b.ultrafast;
148 if (
149 !sameTokenRates(a, b) ||
150 !sameTokenRates(fast, b.fast ?? fast) ||
151 !sameTokenRates(ultrafast, b.ultrafast ?? ultrafast)
152 ) {
153 return null;
154 }
155 return { ...a, fast, ultrafast };
156}
157
158function ratesAt(rate: ModelRate, speed: UsageSpeed): TokenRates {
159 return (speed === "standard" ? null : rate[speed]) ?? rate;
160}
161
162function normalizeRateKey(model: string): string {
163 return model.trim().toLowerCase();
164}
165
166function bareModelName(key: string): string {
167 const slash = key.lastIndexOf("/");
168 return slash === -1 ? key : key.slice(slash + 1);
169}
170
171// Price Claude's bracketed context variants at the base tier, the only name the rate table knows.
172function stripVariantSuffix(key: string): string {
173 const bracket = key.indexOf("[");
174 return bracket === -1 ? key : key.slice(0, bracket);
175}
176
177// Synthetic messages are unbilled; bare family names are generation-ambiguous and remain unpriced.
178const UNPRICEABLE_MODELS = new Set([
179 "<synthetic>",
180 "synthetic",
181 "opus",
182 "sonnet",
183 "haiku",
184 "fable",
185]);
186
187// Immutable tables permit caching rates across twice-per-record pricing lookups.
188const resolvedRates = new WeakMap<RateTable, Map<string, ModelRate | null>>();
189
190export function lookupRate(table: RateTable, model: string): ModelRate | null {
191 let resolved = resolvedRates.get(table);
192 if (resolved === undefined) {
193 resolved = new Map();
194 resolvedRates.set(table, resolved);
195 }
196 let rate = resolved.get(model);
197 if (rate === undefined) {
198 rate = resolveRate(table, model);
199 resolved.set(model, rate);
200 }
201 return rate;
202}
203
204function resolveRate(table: RateTable, model: string): ModelRate | null {
205 const key = stripVariantSuffix(normalizeRateKey(model));
206 const bareName = bareModelName(key);
207 if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
208 return table.get(key) ?? null;
209}
210
211export type PricedRecord = Pick<
212 UsageRecord,
213 "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd"
214>;
215
216export interface PricedUsage {
217 readonly costUsd: number;
218 readonly costSource: UsageCostSource;
219 readonly categoryCostUsd: UsageCategoryCost | null;
220 readonly speedPremiumUsd: number;
221}
222
223function costByCategory(totals: UsageTokenTotals, rates: TokenRates): UsageCategoryCost {
224 return {
225 input: totals.uncachedInputTokens * rates.inputCostPerToken,
226 cacheRead: totals.cachedInputTokens * rates.cacheReadCostPerToken,
227 cacheWrite: totals.cacheCreationTokens * rates.cacheCreationCostPerToken,
228 output: totals.outputTokens * rates.outputCostPerToken,
229 };
230}
231
232function sumCategories(cost: UsageCategoryCost): number {
233 return cost.input + cost.cacheRead + cost.cacheWrite + cost.output;
234}
235
236/** Reasoning tokens are already included in outputTokens; do not charge twice. */
237export function priceUsage(
238 table: RateTable,
239 record: PricedRecord,
240 overrides?: RateTable,
241): PricedUsage {
242 const { model, totals, reportedCostUsd } = record;
243 const override = overrides?.get(model.trim());
244 const reported =
245 override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)
246 ? reportedCostUsd
247 : null;
248 const unsplit = (costUsd: number, costSource: UsageCostSource): PricedUsage => ({
249 costUsd,
250 costSource,
251 categoryCostUsd: null,
252 speedPremiumUsd: 0,
253 });
254 const rate = override ?? lookupRate(table, record.rateModel ?? model);
255 if (rate === null) {
256 return reported === null ? unsplit(0, "unpriced") : unsplit(reported, "providerReported");
257 }
258
259 const listCost = costByCategory(totals, ratesAt(rate, record.speed));
260 const listCostUsd = sumCategories(listCost);
261 if (reported !== null && listCostUsd <= 0) return unsplit(reported, "providerReported");
262 const premiumUsd =
263 record.speed === "standard" ? 0 : listCostUsd - sumCategories(costByCategory(totals, rate));
264 const scale = reported === null ? 1 : reported / listCostUsd;
265 return {
266 costUsd: reported ?? listCostUsd,
267 costSource: reported === null ? "modelPriced" : "providerReported",
268 categoryCostUsd: {
269 input: listCost.input * scale,
270 cacheRead: listCost.cacheRead * scale,
271 cacheWrite: listCost.cacheWrite * scale,
272 output: listCost.output * scale,
273 },
274 speedPremiumUsd: premiumUsd * scale,
275 };
276}
277
278export function cacheSavingsUsd(
279 table: RateTable,
280 record: PricedRecord,
281 overrides?: RateTable,
282): number {
283 const rate =
284 overrides?.get(record.model.trim()) ?? lookupRate(table, record.rateModel ?? record.model);
285 if (rate === null) return 0;
286 const rates = ratesAt(rate, record.speed);
287 return record.totals.cachedInputTokens * (rates.inputCostPerToken - rates.cacheReadCostPerToken);
288}