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

usagePricing.ts

296 lines10.1 KB

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, UsageModelPriceOverride } from "@t3tools/contracts";
11​
12import type { UsageRecord, UsageSpeed } from "./usageTranscripts.ts";
13​
14/** Token rates for one billing speed. All values are USD per token. */
15export interface TokenRates {
16 readonly inputCostPerToken: number;
17 readonly outputCostPerToken: number;
18 readonly cacheReadCostPerToken: number;
19 readonly cacheCreationCostPerToken: number;
21​
22/**
23 * The subset of a LiteLLM entry we price against: standard rates, plus rates
24 * for each faster speed the model publishes. A request at a speed with no
25 * published rates bills at the standard rates.
26 *
27 * LiteLLM also publishes `*_above_272k_tokens`, `*_flex`, and `*_batches`
28 * variants. Transcripts don't record those, so we don't price them.
29 */
30export interface ModelRate extends TokenRates {
31 /**
32 * From LiteLLM's `provider_specific_entry.fast` multiple (Claude fast mode),
33 * or else its `*_priority` rates (Codex `priority`).
34 */
35 readonly fast: TokenRates | null;
36 /** From LiteLLM's `*_ultrafast` rates (Codex `ultrafast`). */
37 readonly ultrafast: TokenRates | null;
39​
40export type RateTable = ReadonlyMap<string, ModelRate>;
41​
42/**
43 * Custom IDs keep their case, provider prefix, and variant suffix. Custom rates
44 * apply as entered, at every speed.
45 */
46export function createOverrideRateTable(
47 overrides: Readonly<Record<string, UsageModelPriceOverride>>,
48): RateTable {
49 return new Map(
50 Object.entries(overrides).map(([model, prices]) => [
51 model.trim(),
52 {
53 inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000,
54 outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000,
55 cacheReadCostPerToken:
56 (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
57 cacheCreationCostPerToken:
58 (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
59 fast: null,
60 ultrafast: null,
61 },
62 ]),
63 );
65​
66/** One raw LiteLLM entry. Field names carry a tier suffix, e.g. `_priority`. */
67type LiteLlmEntry = Readonly<Record<string, unknown>>;
68​
69function finiteNumber(value: unknown): number | null {
70 return typeof value === "number" && Number.isFinite(value) ? value : null;
72​
73/**
74 * Reads one rate set, `suffix` selecting a tier such as `_priority`. Returns
75 * `null` without both an input and an output rate.
76 *
77 * Anthropic bills cache reads at a discount and cache writes at a premium.
78 * When the standard tier omits them, cached input is priced as plain input
79 * rather than as free. A faster tier that omits them keeps the standard tier's
80 * cache-to-input ratio.
81 */
82function readTokenRates(
83 entry: LiteLlmEntry,
84 suffix: string,
85 standard?: TokenRates,
86): TokenRates | null {
87 const input = finiteNumber(entry[`input_cost_per_token${suffix}`]);
88 const output = finiteNumber(entry[`output_cost_per_token${suffix}`]);
89 if (input === null || output === null) return null;
90 const cacheRate = (name: string, field: "cacheReadCostPerToken" | "cacheCreationCostPerToken") =>
91 finiteNumber(entry[`${name}${suffix}`]) ??
92 (standard !== undefined && standard.inputCostPerToken > 0
93 ? (standard[field] / standard.inputCostPerToken) * input
94 : input);
95 return {
96 inputCostPerToken: input,
97 outputCostPerToken: output,
98 cacheReadCostPerToken: cacheRate("cache_read_input_token_cost", "cacheReadCostPerToken"),
99 cacheCreationCostPerToken: cacheRate(
100 "cache_creation_input_token_cost",
101 "cacheCreationCostPerToken",
102 ),
103 };
105​
106function scaleTokenRates(rates: TokenRates, multiple: number): TokenRates {
107 return {
108 inputCostPerToken: rates.inputCostPerToken * multiple,
109 outputCostPerToken: rates.outputCostPerToken * multiple,
110 cacheReadCostPerToken: rates.cacheReadCostPerToken * multiple,
111 cacheCreationCostPerToken: rates.cacheCreationCostPerToken * multiple,
112 };
114​
115/** Reads `provider_specific_entry.fast`, e.g. `2` for Claude Opus 5.5. */
116function fastMultiplier(entry: LiteLlmEntry): number | null {
117 const specific = entry["provider_specific_entry"];
118 if (typeof specific !== "object" || specific === null) return null;
119 const fast = finiteNumber((specific as Record<string, unknown>)["fast"]);
120 return fast !== null && fast > 0 ? fast : null;
122​
123/**
124 * Projects the LiteLLM document into a rate table.
125 *
126 * Entries without both an input and an output rate are dropped: a half-priced
127 * model would silently under-report cost, which is worse than reporting the
128 * model as unpriced.
129 *
130 * Entries keep their full normalized key; a bare name is aliased only when no
131 * canonical entry exists and every qualified entry has the same rate.
132 */
133export function parseRateTable(document: unknown): RateTable {
134 const table = new Map<string, ModelRate>();
135 if (typeof document !== "object" || document === null) return table;
136​
137 for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
138 if (typeof raw !== "object" || raw === null) continue;
139 const entry = raw as LiteLlmEntry;
140 const standard = readTokenRates(entry, "");
141 if (standard === null) continue;
142​
143 const key = normalizeRateKey(name);
144 if (key.length === 0) continue;
145 const multiple = fastMultiplier(entry);
146 table.set(key, {
147 ...standard,
148 fast:
149 multiple === null
150 ? readTokenRates(entry, "_priority", standard)
151 : scaleTokenRates(standard, multiple),
152 ultrafast: readTokenRates(entry, "_ultrafast", standard),
153 });
154 }
155​
156 // `null` marks a bare name claimed at conflicting rates: no alias for it.
157 const aliasCandidates = new Map<string, ModelRate | null>();
158 for (const [key, rate] of table) {
159 const alias = bareModelName(key);
160 if (alias.length === 0 || alias === key || table.has(alias)) continue;
161 const held = aliasCandidates.get(alias);
162 if (held === undefined) {
163 aliasCandidates.set(alias, rate);
164 } else if (held !== null && !sameRate(held, rate)) {
165 aliasCandidates.set(alias, null);
166 }
167 }
168 for (const [alias, rate] of aliasCandidates) {
169 if (rate !== null) table.set(alias, rate);
170 }
171​
172 return table;
174​
175function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean {
176 if (a === null || b === null) return a === b;
177 return (
178 a.inputCostPerToken === b.inputCostPerToken &&
179 a.outputCostPerToken === b.outputCostPerToken &&
180 a.cacheReadCostPerToken === b.cacheReadCostPerToken &&
181 a.cacheCreationCostPerToken === b.cacheCreationCostPerToken
182 );
184​
185function sameRate(a: ModelRate, b: ModelRate): boolean {
186 return (
187 sameTokenRates(a, b) &&
188 sameTokenRates(a.fast, b.fast) &&
189 sameTokenRates(a.ultrafast, b.ultrafast)
190 );
192​
193/** The rates a request at `speed` bills at. */
194function ratesAt(rate: ModelRate, speed: UsageSpeed): TokenRates {
195 return (speed === "standard" ? null : rate[speed]) ?? rate;
197​
198function normalizeRateKey(model: string): string {
199 return model.trim().toLowerCase();
201​
202function bareModelName(key: string): string {
203 const slash = key.lastIndexOf("/");
204 return slash === -1 ? key : key.slice(slash + 1);
206​
207/**
208 * Drops a bracketed variant suffix such as `claude-fable-5-1[1m]`, which
209 * Claude Code writes for the 1M context tier. The rate table only knows the
210 * base name, and we price at the base tier anyway.
211 */
212function stripVariantSuffix(key: string): string {
213 const bracket = key.indexOf("[");
214 return bracket === -1 ? key : key.slice(0, bracket);
216​
217/**
218 * Models we never price, regardless of the table.
219 *
220 * `<synthetic>` marks locally generated messages that were never billed. Bare
221 * family names ("opus", "sonnet") are genuinely ambiguous across generations,
222 * so we report them as unpriced instead of guessing a generation.
223 */
224const UNPRICEABLE_MODELS = new Set([
225 "<synthetic>",
226 "synthetic",
227 "opus",
228 "sonnet",
229 "haiku",
230 "fable",
231]);
232​
233export function lookupRate(table: RateTable, model: string): ModelRate | null {
234 const key = stripVariantSuffix(normalizeRateKey(model));
235 const bareName = bareModelName(key);
236 if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
237 return table.get(key) ?? null;
239​
240/** The parts of a transcript record that decide its price. */
241export type PricedRecord = Pick<
242 UsageRecord,
243 "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd"
244>;
245​
246export interface PricedUsage {
247 readonly costUsd: number;
248 readonly costSource: UsageCostSource;
250​
251/**
252 * Prices one record's tokens.
253 *
254 * `reasoningTokens` is intentionally not charged separately: it is already
255 * counted inside `outputTokens`.
256 */
257export function priceUsage(
258 table: RateTable,
259 record: PricedRecord,
260 overrides?: RateTable,
261): PricedUsage {
262 const { model, totals, reportedCostUsd } = record;
263 const override = overrides?.get(model.trim());
264 if (override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {
265 return { costUsd: reportedCostUsd, costSource: "providerReported" };
266 }
267​
268 const rate = override ?? lookupRate(table, record.rateModel ?? model);
269 if (rate === null) return { costUsd: 0, costSource: "unpriced" };
270​
271 const rates = ratesAt(rate, record.speed);
272 return {
273 costUsd:
274 totals.uncachedInputTokens * rates.inputCostPerToken +
275 totals.cachedInputTokens * rates.cacheReadCostPerToken +
276 totals.cacheCreationTokens * rates.cacheCreationCostPerToken +
277 totals.outputTokens * rates.outputCostPerToken,
278 costSource: "modelPriced",
279 };
281​
282/**
283 * What the cached input would have cost at full input rates, minus what it
284 * actually cost. Drives the "cache savings" figure.
285 */
286export function cacheSavingsUsd(
287 table: RateTable,
288 record: PricedRecord,
289 overrides?: RateTable,
290): number {
291 const rate =
292 overrides?.get(record.model.trim()) ?? lookupRate(table, record.rateModel ?? record.model);
293 if (rate === null) return 0;
294 const rates = ratesAt(rate, record.speed);
295 return record.totals.cachedInputTokens * (rates.inputCostPerToken - rates.cacheReadCostPerToken);