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

usagePricing.ts

246 lines8.4 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 } from "./usageTranscripts.ts";
13​
14/**
15 * The subset of a LiteLLM entry we price against. All values are USD per token.
16 *
17 * LiteLLM also publishes tiered variants (`*_above_272k_tokens`, `*_flex`,
18 * `*_priority`, `*_batches`). We deliberately price at the base tier: the
19 * transcripts don't record which tier served a request, so anything else would
20 * be a guess dressed up as precision.
21 */
22export interface ModelRate {
23 readonly inputCostPerToken: number;
24 readonly outputCostPerToken: number;
25 readonly cacheReadCostPerToken: number;
26 readonly cacheCreationCostPerToken: number;
27 /**
28 * Multiple of the rates above billed for a fast-mode request, from LiteLLM's
29 * `provider_specific_entry.fast`. `1` when the model publishes no fast tier.
30 */
31 readonly fastMultiplier: number;
33​
34export type RateTable = ReadonlyMap<string, ModelRate>;
35​
36/**
37 * Custom IDs keep their case, provider prefix, and variant suffix. Custom rates
38 * apply as entered, fast-mode requests included.
39 */
40export function createOverrideRateTable(
41 overrides: Readonly<Record<string, UsageModelPriceOverride>>,
42): RateTable {
43 return new Map(
44 Object.entries(overrides).map(([model, prices]) => [
45 model.trim(),
46 {
47 inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000,
48 outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000,
49 cacheReadCostPerToken:
50 (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
51 cacheCreationCostPerToken:
52 (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
53 fastMultiplier: 1,
54 },
55 ]),
56 );
58​
59/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */
60interface LiteLlmEntry {
61 readonly input_cost_per_token?: unknown;
62 readonly output_cost_per_token?: unknown;
63 readonly cache_read_input_token_cost?: unknown;
64 readonly cache_creation_input_token_cost?: unknown;
65 readonly provider_specific_entry?: unknown;
67​
68function finiteNumber(value: unknown): number | null {
69 return typeof value === "number" && Number.isFinite(value) ? value : null;
71​
72/** Reads `provider_specific_entry.fast`, e.g. `2` for Claude Opus 5.5. */
73function fastMultiplier(entry: LiteLlmEntry): number {
74 const specific = entry.provider_specific_entry;
75 if (typeof specific !== "object" || specific === null) return 1;
76 const fast = finiteNumber((specific as Record<string, unknown>)["fast"]);
77 return fast !== null && fast > 0 ? fast : 1;
79​
80/**
81 * Projects the LiteLLM document into a rate table.
82 *
83 * Entries without both an input and an output rate are dropped: a half-priced
84 * model would silently under-report cost, which is worse than reporting the
85 * model as unpriced.
86 *
87 * Entries keep their full normalized key; a bare name is aliased only when no
88 * canonical entry exists and every qualified entry has the same rate.
89 */
90export function parseRateTable(document: unknown): RateTable {
91 const table = new Map<string, ModelRate>();
92 if (typeof document !== "object" || document === null) return table;
93​
94 for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
95 if (typeof raw !== "object" || raw === null) continue;
96 const entry = raw as LiteLlmEntry;
97 const input = finiteNumber(entry.input_cost_per_token);
98 const output = finiteNumber(entry.output_cost_per_token);
99 if (input === null || output === null) continue;
100​
101 const key = normalizeRateKey(name);
102 if (key.length === 0) continue;
103 table.set(key, {
104 inputCostPerToken: input,
105 outputCostPerToken: output,
106 // Anthropic bills cache reads at a discount and cache writes at a
107 // premium. When a model omits them, cached input is priced as plain
108 // input rather than as free.
109 cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input,
110 cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input,
111 fastMultiplier: fastMultiplier(entry),
112 });
113 }
114​
115 // `null` marks a bare name claimed at conflicting rates: no alias for it.
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 && !sameRate(held, rate)) {
124 aliasCandidates.set(alias, null);
125 }
126 }
127 for (const [alias, rate] of aliasCandidates) {
128 if (rate !== null) table.set(alias, rate);
129 }
130​
131 return table;
133​
134function sameRate(a: ModelRate, b: ModelRate): boolean {
135 return (
136 a.inputCostPerToken === b.inputCostPerToken &&
137 a.outputCostPerToken === b.outputCostPerToken &&
138 a.cacheReadCostPerToken === b.cacheReadCostPerToken &&
139 a.cacheCreationCostPerToken === b.cacheCreationCostPerToken &&
140 a.fastMultiplier === b.fastMultiplier
141 );
143​
144function normalizeRateKey(model: string): string {
145 return model.trim().toLowerCase();
147​
148function bareModelName(key: string): string {
149 const slash = key.lastIndexOf("/");
150 return slash === -1 ? key : key.slice(slash + 1);
152​
153/**
154 * Drops a bracketed variant suffix such as `claude-fable-5-1[1m]`, which
155 * Claude Code writes for the 1M context tier. The rate table only knows the
156 * base name, and we price at the base tier anyway.
157 */
158function stripVariantSuffix(key: string): string {
159 const bracket = key.indexOf("[");
160 return bracket === -1 ? key : key.slice(0, bracket);
162​
163/**
164 * Models we never price, regardless of the table.
165 *
166 * `<synthetic>` marks locally generated messages that were never billed. Bare
167 * family names ("opus", "sonnet") are genuinely ambiguous across generations,
168 * so we report them as unpriced instead of guessing a generation.
169 */
170const UNPRICEABLE_MODELS = new Set([
171 "<synthetic>",
172 "synthetic",
173 "opus",
174 "sonnet",
175 "haiku",
176 "fable",
177]);
178​
179export function lookupRate(table: RateTable, model: string): ModelRate | null {
180 const key = stripVariantSuffix(normalizeRateKey(model));
181 const bareName = bareModelName(key);
182 if (bareName.length === 0 || UNPRICEABLE_MODELS.has(bareName)) return null;
183 return table.get(key) ?? null;
185​
186/** The parts of a transcript record that decide its price. */
187export type PricedRecord = Pick<
188 UsageRecord,
189 "model" | "rateModel" | "totals" | "fast" | "reportedCostUsd"
190>;
191​
192export interface PricedUsage {
193 readonly costUsd: number;
194 readonly costSource: UsageCostSource;
196​
197/**
198 * Prices one record's tokens.
199 *
200 * `reasoningTokens` is intentionally not charged separately: it is already
201 * counted inside `outputTokens`.
202 */
203export function priceUsage(
204 table: RateTable,
205 record: PricedRecord,
206 overrides?: RateTable,
207): PricedUsage {
208 const { model, totals, reportedCostUsd } = record;
209 const override = overrides?.get(model.trim());
210 if (override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {
211 return { costUsd: reportedCostUsd, costSource: "providerReported" };
212 }
213​
214 const rate = override ?? lookupRate(table, record.rateModel ?? model);
215 if (rate === null) return { costUsd: 0, costSource: "unpriced" };
216​
217 const standardCostUsd =
218 totals.uncachedInputTokens * rate.inputCostPerToken +
219 totals.cachedInputTokens * rate.cacheReadCostPerToken +
220 totals.cacheCreationTokens * rate.cacheCreationCostPerToken +
221 totals.outputTokens * rate.outputCostPerToken;
222​
223 return {
224 costUsd: standardCostUsd * (record.fast ? rate.fastMultiplier : 1),
225 costSource: "modelPriced",
226 };
228​
229/**
230 * What the cached input would have cost at full input rates, minus what it
231 * actually cost. Drives the "cache savings" figure.
232 */
233export function cacheSavingsUsd(
234 table: RateTable,
235 record: PricedRecord,
236 overrides?: RateTable,
237): number {
238 const rate =
239 overrides?.get(record.model.trim()) ?? lookupRate(table, record.rateModel ?? record.model);
240 if (rate === null) return 0;
241 return (
242 record.totals.cachedInputTokens *
243 (rate.inputCostPerToken - rate.cacheReadCostPerToken) *
244 (record.fast ? rate.fastMultiplier : 1)
245 );