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// LiteLLM prefixes for the model makers' own APIs; their price beats a cloud's or reseller's for a bare name.
93const FIRST_PARTY_PROVIDERS = new Set([
94 "anthropic",
95 "deepseek",
96 "gemini",
97 "meta",
98 "mistral",
99 "openai",
100 "xai",
101]);
102
103/** Drops models missing input or output rates to avoid understating cost. */
104export function parseRateTable(document: unknown): RateTable {
105 const table = new Map<string, ModelRate>();
106 if (typeof document !== "object" || document === null) return table;
107
108 for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
109 if (typeof raw !== "object" || raw === null) continue;
110 const entry = raw as LiteLlmEntry;
111 const standard = readTokenRates(entry, "");
112 if (standard === null) continue;
113
114 const key = normalizeRateKey(name);
115 if (key.length === 0) continue;
116 const multiple = fastMultiplier(entry);
117 table.set(key, {
118 ...standard,
119 fast:
120 multiple === null
121 ? readTokenRates(entry, "_priority", standard)
122 : scaleTokenRates(standard, multiple),
123 ultrafast: readTokenRates(entry, "_ultrafast", standard),
124 });
125 }
126
127 const aliasCandidates = new Map<string, { rate: ModelRate | null; firstParty: boolean }>();
128 for (const [key, rate] of table) {
129 const slash = key.indexOf("/");
130 const alias = slash === -1 ? bedrockBaseModelName(key) : bareModelName(key);
131 if (alias.length === 0 || alias === key || table.has(alias)) continue;
132 const firstParty = slash !== -1 && FIRST_PARTY_PROVIDERS.has(key.slice(0, slash));
133 const held = aliasCandidates.get(alias);
134 if (held === undefined || (firstParty && !held.firstParty)) {
135 aliasCandidates.set(alias, { rate, firstParty });
136 } else if (held.rate !== null && firstParty === held.firstParty) {
137 aliasCandidates.set(alias, { rate: mergeAliasRate(held.rate, rate), firstParty });
138 }
139 }
140 for (const [alias, { rate }] of aliasCandidates) {
141 if (rate !== null) table.set(alias, rate);
142 }
143
144 return table;
145}
146
147function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean {
148 if (a === null || b === null) return a === b;
149 return (
150 a.inputCostPerToken === b.inputCostPerToken &&
151 a.outputCostPerToken === b.outputCostPerToken &&
152 a.cacheReadCostPerToken === b.cacheReadCostPerToken &&
153 a.cacheCreationCostPerToken === b.cacheCreationCostPerToken
154 );
155}
156
157// Resellers often omit speed tiers, so a missing tier fills from the other entry instead of conflicting.
158function mergeAliasRate(a: ModelRate, b: ModelRate): ModelRate | null {
159 const fast = a.fast ?? b.fast;
160 const ultrafast = a.ultrafast ?? b.ultrafast;
161 if (
162 !sameTokenRates(a, b) ||
163 !sameTokenRates(fast, b.fast ?? fast) ||
164 !sameTokenRates(ultrafast, b.ultrafast ?? ultrafast)
165 ) {
166 return null;
167 }
168 return { ...a, fast, ultrafast };
169}
170
171function ratesAt(rate: ModelRate, speed: UsageSpeed): TokenRates {
172 return (speed === "standard" ? null : rate[speed]) ?? rate;
173}
174
175function normalizeRateKey(model: string): string {
176 return model.trim().toLowerCase();
177}
178
179function bareModelName(key: string): string {
180 const slash = key.lastIndexOf("/");
181 return slash === -1 ? key : key.slice(slash + 1);
182}
183
184// Only Bedrock's base ID gives a bare alias; its regional (us., eu.) and GovCloud IDs carry markups.
185function bedrockBaseModelName(key: string): string {
186 return key.startsWith("anthropic.") ? key.slice("anthropic.".length) : key;
187}
188
189// Price Claude's bracketed context variants at the base tier, the only name the rate table knows.
190function stripVariantSuffix(key: string): string {
191 const bracket = key.indexOf("[");
192 return bracket === -1 ? key : key.slice(0, bracket);
193}
194
195// Synthetic messages are unbilled; bare family names are generation-ambiguous and remain unpriced.
196const UNPRICEABLE_MODELS = new Set([
197 "<synthetic>",
198 "synthetic",
199 "opus",
200 "sonnet",
201 "haiku",
202 "fable",
203]);
204
205// Immutable tables permit caching rates across twice-per-record pricing lookups.
206const resolvedRates = new WeakMap<RateTable, Map<string, ModelRate | null>>();
207
208export function lookupRate(table: RateTable, model: string): ModelRate | null {
209 let resolved = resolvedRates.get(table);
210 if (resolved === undefined) {
211 resolved = new Map();
212 resolvedRates.set(table, resolved);
213 }
214 let rate = resolved.get(model);
215 if (rate === undefined) {
216 rate = resolveRate(table, model);
217 resolved.set(model, rate);
218 }
219 return rate;
220}
221
222function resolveRate(table: RateTable, model: string): ModelRate | null {
223 const key = stripVariantSuffix(normalizeRateKey(model));
224 const bareName = bareModelName(key);
225 if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
226 return table.get(key) ?? null;
227}
228
229export type PricedRecord = Pick<
230 UsageRecord,
231 "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd"
232>;
233
234export interface PricedUsage {
235 readonly costUsd: number;
236 readonly costSource: UsageCostSource;
237 readonly categoryCostUsd: UsageCategoryCost | null;
238 readonly speedPremiumUsd: number;
239}
240
241function costByCategory(totals: UsageTokenTotals, rates: TokenRates): UsageCategoryCost {
242 return {
243 input: totals.uncachedInputTokens * rates.inputCostPerToken,
244 cacheRead: totals.cachedInputTokens * rates.cacheReadCostPerToken,
245 cacheWrite: totals.cacheCreationTokens * rates.cacheCreationCostPerToken,
246 output: totals.outputTokens * rates.outputCostPerToken,
247 };
248}
249
250function sumCategories(cost: UsageCategoryCost): number {
251 return cost.input + cost.cacheRead + cost.cacheWrite + cost.output;
252}
253
254/** Reasoning tokens are already included in outputTokens; do not charge twice. */
255export function priceUsage(
256 table: RateTable,
257 record: PricedRecord,
258 overrides?: RateTable,
259): PricedUsage {
260 const { model, totals, reportedCostUsd } = record;
261 const override = overrides?.get(model.trim());
262 const reported =
263 override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)
264 ? reportedCostUsd
265 : null;
266 const unsplit = (costUsd: number, costSource: UsageCostSource): PricedUsage => ({
267 costUsd,
268 costSource,
269 categoryCostUsd: null,
270 speedPremiumUsd: 0,
271 });
272 const rate = override ?? lookupRate(table, record.rateModel ?? model);
273 if (rate === null) {
274 return reported === null ? unsplit(0, "unpriced") : unsplit(reported, "providerReported");
275 }
276
277 const listCost = costByCategory(totals, ratesAt(rate, record.speed));
278 const listCostUsd = sumCategories(listCost);
279 if (reported !== null && listCostUsd <= 0) return unsplit(reported, "providerReported");
280 const premiumUsd =
281 record.speed === "standard" ? 0 : listCostUsd - sumCategories(costByCategory(totals, rate));
282 const scale = reported === null ? 1 : reported / listCostUsd;
283 return {
284 costUsd: reported ?? listCostUsd,
285 costSource: reported === null ? "modelPriced" : "providerReported",
286 categoryCostUsd: {
287 input: listCost.input * scale,
288 cacheRead: listCost.cacheRead * scale,
289 cacheWrite: listCost.cacheWrite * scale,
290 output: listCost.output * scale,
291 },
292 speedPremiumUsd: premiumUsd * scale,
293 };
294}
295
296export function cacheSavingsUsd(
297 table: RateTable,
298 record: PricedRecord,
299 overrides?: RateTable,
300): number {
301 const rate =
302 overrides?.get(record.model.trim()) ?? lookupRate(table, record.rateModel ?? record.model);
303 if (rate === null) return 0;
304 const rates = ratesAt(rate, record.speed);
305 return record.totals.cachedInputTokens * (rates.inputCostPerToken - rates.cacheReadCostPerToken);
306}