Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usagePricing.ts

300 lines10.3 KB

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;
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;
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 );
44​
45type LiteLlmEntry = Readonly<Record<string, unknown>>;
46​
47function finiteNumber(value: unknown): number | null {
48 return typeof value === "number" && Number.isFinite(value) ? value : null;
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 };
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 };
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;
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 alias = bareModelName(key);
130 if (alias.length === 0 || alias === key || table.has(alias)) continue;
131 const firstParty = FIRST_PARTY_PROVIDERS.has(key.slice(0, key.indexOf("/")));
132 const held = aliasCandidates.get(alias);
133 if (held === undefined || (firstParty && !held.firstParty)) {
134 aliasCandidates.set(alias, { rate, firstParty });
135 } else if (held.rate !== null && firstParty === held.firstParty) {
136 aliasCandidates.set(alias, { rate: mergeAliasRate(held.rate, rate), firstParty });
137 }
138 }
139 for (const [alias, { rate }] of aliasCandidates) {
140 if (rate !== null) table.set(alias, rate);
141 }
142​
143 return table;
145​
146function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean {
147 if (a === null || b === null) return a === b;
148 return (
149 a.inputCostPerToken === b.inputCostPerToken &&
150 a.outputCostPerToken === b.outputCostPerToken &&
151 a.cacheReadCostPerToken === b.cacheReadCostPerToken &&
152 a.cacheCreationCostPerToken === b.cacheCreationCostPerToken
153 );
155​
156// Resellers often omit speed tiers, so a missing tier fills from the other entry instead of conflicting.
157function mergeAliasRate(a: ModelRate, b: ModelRate): ModelRate | null {
158 const fast = a.fast ?? b.fast;
159 const ultrafast = a.ultrafast ?? b.ultrafast;
160 if (
161 !sameTokenRates(a, b) ||
162 !sameTokenRates(fast, b.fast ?? fast) ||
163 !sameTokenRates(ultrafast, b.ultrafast ?? ultrafast)
164 ) {
165 return null;
166 }
167 return { ...a, fast, ultrafast };
169​
170function ratesAt(rate: ModelRate, speed: UsageSpeed): TokenRates {
171 return (speed === "standard" ? null : rate[speed]) ?? rate;
173​
174function normalizeRateKey(model: string): string {
175 return model.trim().toLowerCase();
177​
178function bareModelName(key: string): string {
179 const slash = key.lastIndexOf("/");
180 return slash === -1 ? key : key.slice(slash + 1);
182​
183// Price Claude's bracketed context variants at the base tier, the only name the rate table knows.
184function stripVariantSuffix(key: string): string {
185 const bracket = key.indexOf("[");
186 return bracket === -1 ? key : key.slice(0, bracket);
188​
189// Synthetic messages are unbilled; bare family names are generation-ambiguous and remain unpriced.
190const UNPRICEABLE_MODELS = new Set([
191 "<synthetic>",
192 "synthetic",
193 "opus",
194 "sonnet",
195 "haiku",
196 "fable",
197]);
198​
199// Immutable tables permit caching rates across twice-per-record pricing lookups.
200const resolvedRates = new WeakMap<RateTable, Map<string, ModelRate | null>>();
201​
202export function lookupRate(table: RateTable, model: string): ModelRate | null {
203 let resolved = resolvedRates.get(table);
204 if (resolved === undefined) {
205 resolved = new Map();
206 resolvedRates.set(table, resolved);
207 }
208 let rate = resolved.get(model);
209 if (rate === undefined) {
210 rate = resolveRate(table, model);
211 resolved.set(model, rate);
212 }
213 return rate;
215​
216function resolveRate(table: RateTable, model: string): ModelRate | null {
217 const key = stripVariantSuffix(normalizeRateKey(model));
218 const bareName = bareModelName(key);
219 if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
220 return table.get(key) ?? null;
222​
223export type PricedRecord = Pick<
224 UsageRecord,
225 "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd"
226>;
227​
228export interface PricedUsage {
229 readonly costUsd: number;
230 readonly costSource: UsageCostSource;
231 readonly categoryCostUsd: UsageCategoryCost | null;
232 readonly speedPremiumUsd: number;
234​
235function costByCategory(totals: UsageTokenTotals, rates: TokenRates): UsageCategoryCost {
236 return {
237 input: totals.uncachedInputTokens * rates.inputCostPerToken,
238 cacheRead: totals.cachedInputTokens * rates.cacheReadCostPerToken,
239 cacheWrite: totals.cacheCreationTokens * rates.cacheCreationCostPerToken,
240 output: totals.outputTokens * rates.outputCostPerToken,
241 };
243​
244function sumCategories(cost: UsageCategoryCost): number {
245 return cost.input + cost.cacheRead + cost.cacheWrite + cost.output;
247​
248/** Reasoning tokens are already included in outputTokens; do not charge twice. */
249export function priceUsage(
250 table: RateTable,
251 record: PricedRecord,
252 overrides?: RateTable,
253): PricedUsage {
254 const { model, totals, reportedCostUsd } = record;
255 const override = overrides?.get(model.trim());
256 const reported =
257 override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)
258 ? reportedCostUsd
259 : null;
260 const unsplit = (costUsd: number, costSource: UsageCostSource): PricedUsage => ({
261 costUsd,
262 costSource,
263 categoryCostUsd: null,
264 speedPremiumUsd: 0,
265 });
266 const rate = override ?? lookupRate(table, record.rateModel ?? model);
267 if (rate === null) {
268 return reported === null ? unsplit(0, "unpriced") : unsplit(reported, "providerReported");
269 }
270​
271 const listCost = costByCategory(totals, ratesAt(rate, record.speed));
272 const listCostUsd = sumCategories(listCost);
273 if (reported !== null && listCostUsd <= 0) return unsplit(reported, "providerReported");
274 const premiumUsd =
275 record.speed === "standard" ? 0 : listCostUsd - sumCategories(costByCategory(totals, rate));
276 const scale = reported === null ? 1 : reported / listCostUsd;
277 return {
278 costUsd: reported ?? listCostUsd,
279 costSource: reported === null ? "modelPriced" : "providerReported",
280 categoryCostUsd: {
281 input: listCost.input * scale,
282 cacheRead: listCost.cacheRead * scale,
283 cacheWrite: listCost.cacheWrite * scale,
284 output: listCost.output * scale,
285 },
286 speedPremiumUsd: premiumUsd * scale,
287 };
289​
290export function cacheSavingsUsd(
291 table: RateTable,
292 record: PricedRecord,
293 overrides?: RateTable,
294): number {
295 const rate =
296 overrides?.get(record.model.trim()) ?? lookupRate(table, record.rateModel ?? record.model);
297 if (rate === null) return 0;
298 const rates = ratesAt(rate, record.speed);
299 return record.totals.cachedInputTokens * (rates.inputCostPerToken - rates.cacheReadCostPerToken);