Open History to see the last commit
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 {
11 UsageCostSource,
12 UsageModelPriceOverride,
13 UsageTokenTotals,
14} from "@t3tools/contracts";
15import * as Option from "effect/Option";
16import * as Schema from "effect/Schema";
17
18/**
19 * The subset of a LiteLLM entry we price against. All values are USD per token.
20 *
21 * LiteLLM also publishes tiered variants (`*_above_272k_tokens`, `*_flex`,
22 * `*_priority`, `*_batches`). We deliberately price at the base tier: the
23 * transcripts don't record which tier served a request, so anything else would
24 * be a guess dressed up as precision.
25 */
26export interface ModelRate {
27 readonly inputCostPerToken: number;
28 readonly outputCostPerToken: number;
29 readonly cacheReadCostPerToken: number;
30 readonly cacheCreationCostPerToken: number;
31}
32
33export type RateTable = ReadonlyMap<string, ModelRate>;
34
35/** Custom IDs keep their case, provider prefix, and variant suffix. */
36export function createOverrideRateTable(
37 overrides: Readonly<Record<string, UsageModelPriceOverride>>,
38): RateTable {
39 return new Map(
40 Object.entries(overrides).map(([model, prices]) => [
41 model.trim(),
42 {
43 inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000,
44 outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000,
45 cacheReadCostPerToken:
46 (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
47 cacheCreationCostPerToken:
48 (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000,
49 },
50 ]),
51 );
52}
53
54/** Provider-advertised pricing is USD per one million tokens, never negative. */
55const NonNegativePerMillion = Schema.Number.check(Schema.isGreaterThanOrEqualTo(0));
56
57/** One provider-snapshot model entry, narrowed to the pricing fields we read. */
58const ProviderModelPricing = Schema.Struct({
59 inputPerMillion: NonNegativePerMillion,
60 outputPerMillion: NonNegativePerMillion,
61 cachedInputPerMillion: Schema.optional(NonNegativePerMillion),
62 cacheCreationPerMillion: Schema.optional(NonNegativePerMillion),
63});
64
65const ProviderModelPricingEntry = Schema.Struct({
66 slug: Schema.String,
67 pricing: Schema.optional(ProviderModelPricing),
68 pricingByVariant: Schema.optional(Schema.Record(Schema.String, ProviderModelPricing)),
69});
70
71const ProviderSnapshotPricingDocument = Schema.Struct({
72 models: Schema.Array(ProviderModelPricingEntry),
73});
74
75const decodeProviderSnapshotPricing = Schema.decodeUnknownOption(ProviderSnapshotPricingDocument);
76
77/** Convert a provider snapshot's persisted pricing metadata into rates. */
78export function parseProviderModelRateTable(document: unknown): RateTable {
79 const table = new Map<string, ModelRate>();
80 const decoded = decodeProviderSnapshotPricing(document);
81 if (Option.isNone(decoded)) return table;
82
83 const toRate = (pricing: typeof ProviderModelPricing.Type): ModelRate => ({
84 inputCostPerToken: pricing.inputPerMillion / 1_000_000,
85 outputCostPerToken: pricing.outputPerMillion / 1_000_000,
86 cacheReadCostPerToken: (pricing.cachedInputPerMillion ?? pricing.inputPerMillion) / 1_000_000,
87 cacheCreationCostPerToken:
88 (pricing.cacheCreationPerMillion ?? pricing.inputPerMillion) / 1_000_000,
89 });
90
91 for (const entry of decoded.value.models) {
92 if (entry.slug && entry.pricing !== undefined) {
93 table.set(normalizeModelName(entry.slug), toRate(entry.pricing));
94 }
95 if (entry.pricingByVariant === undefined) continue;
96 for (const [variant, pricing] of Object.entries(entry.pricingByVariant)) {
97 table.set(normalizeModelName(variant), toRate(pricing));
98 }
99 }
100 return table;
101}
102
103/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */
104interface LiteLlmEntry {
105 readonly input_cost_per_token?: unknown;
106 readonly output_cost_per_token?: unknown;
107 readonly cache_read_input_token_cost?: unknown;
108 readonly cache_creation_input_token_cost?: unknown;
109}
110
111function finiteNumber(value: unknown): number | null {
112 return typeof value === "number" && Number.isFinite(value) ? value : null;
113}
114
115/**
116 * Projects the LiteLLM document into a rate table.
117 *
118 * Entries without both an input and an output rate are dropped: a half-priced
119 * model would silently under-report cost, which is worse than reporting the
120 * model as unpriced.
121 *
122 * Entries keep their full normalized key; a bare name is aliased only when no
123 * canonical entry exists and every qualified entry has the same rate.
124 */
125export function parseRateTable(document: unknown): RateTable {
126 const table = new Map<string, ModelRate>();
127 if (typeof document !== "object" || document === null) return table;
128
129 for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
130 if (typeof raw !== "object" || raw === null) continue;
131 const entry = raw as LiteLlmEntry;
132 const input = finiteNumber(entry.input_cost_per_token);
133 const output = finiteNumber(entry.output_cost_per_token);
134 if (input === null || output === null) continue;
135
136 const key = normalizeRateKey(name);
137 if (key.length === 0) continue;
138 table.set(key, {
139 inputCostPerToken: input,
140 outputCostPerToken: output,
141 // Anthropic bills cache reads at a discount and cache writes at a
142 // premium. When a model omits them, cached input is priced as plain
143 // input rather than as free.
144 cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input,
145 cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input,
146 });
147 }
148
149 // `null` marks a bare name claimed at conflicting rates: no alias for it.
150 const aliasCandidates = new Map<string, ModelRate | null>();
151 for (const [key, rate] of table) {
152 const alias = bareModelName(key);
153 if (alias.length === 0 || alias === key || table.has(alias)) continue;
154 const held = aliasCandidates.get(alias);
155 if (held === undefined) {
156 aliasCandidates.set(alias, rate);
157 } else if (held !== null && !sameRate(held, rate)) {
158 aliasCandidates.set(alias, null);
159 }
160 }
161 for (const [alias, rate] of aliasCandidates) {
162 if (rate !== null) table.set(alias, rate);
163 }
164
165 return table;
166}
167
168function sameRate(a: ModelRate, b: ModelRate): boolean {
169 return (
170 a.inputCostPerToken === b.inputCostPerToken &&
171 a.outputCostPerToken === b.outputCostPerToken &&
172 a.cacheReadCostPerToken === b.cacheReadCostPerToken &&
173 a.cacheCreationCostPerToken === b.cacheCreationCostPerToken
174 );
175}
176
177function normalizeRateKey(model: string): string {
178 return model.trim().toLowerCase();
179}
180
181function bareModelName(key: string): string {
182 const slash = key.lastIndexOf("/");
183 return slash === -1 ? key : key.slice(slash + 1);
184}
185
186/**
187 * Canonicalises a model name for lookup.
188 *
189 * Strips a `provider/` prefix and lowercases, since transcripts are
190 * inconsistent about casing.
191 */
192export function normalizeModelName(model: string): string {
193 return bareModelName(normalizeRateKey(model));
194}
195
196/**
197 * Drops a bracketed variant suffix such as `claude-fable-5-1[1m]`, which
198 * Claude Code writes for the 1M context tier. The rate table only knows the
199 * base name, and we price at the base tier anyway.
200 */
201function stripVariantSuffix(key: string): string {
202 const bracket = key.indexOf("[");
203 return bracket === -1 ? key : key.slice(0, bracket);
204}
205
206/**
207 * Models we never price, regardless of the table.
208 *
209 * `<synthetic>` marks locally generated messages that were never billed. Bare
210 * family names ("opus", "sonnet") are genuinely ambiguous across generations,
211 * so we report them as unpriced instead of guessing a generation.
212 */
213const UNPRICEABLE_MODELS = new Set([
214 "<synthetic>",
215 "synthetic",
216 "opus",
217 "sonnet",
218 "haiku",
219 "fable",
220]);
221
222export function lookupRate(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 interface PricedUsage {
230 readonly costUsd: number;
231 readonly costSource: UsageCostSource;
232}
233
234/**
235 * Prices a bucket's tokens.
236 *
237 * `reasoningTokens` is intentionally not charged separately: it is already
238 * counted inside `outputTokens`.
239 */
240export function priceUsage(
241 table: RateTable,
242 model: string,
243 totals: UsageTokenTotals,
244 reportedCostUsd: number | null,
245 overrides?: RateTable,
246): PricedUsage {
247 const override = overrides?.get(model.trim());
248 if (override === undefined && reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {
249 return { costUsd: reportedCostUsd, costSource: "providerReported" };
250 }
251
252 const rate = override ?? lookupRate(table, model);
253 if (rate === null) return { costUsd: 0, costSource: "unpriced" };
254
255 const costUsd =
256 totals.uncachedInputTokens * rate.inputCostPerToken +
257 totals.cachedInputTokens * rate.cacheReadCostPerToken +
258 totals.cacheCreationTokens * rate.cacheCreationCostPerToken +
259 totals.outputTokens * rate.outputCostPerToken;
260
261 return { costUsd, costSource: "modelPriced" };
262}
263
264/**
265 * What the cached input would have cost at full input rates, minus what it
266 * actually cost. Drives the "cache savings" figure.
267 */
268export function cacheSavingsUsd(
269 table: RateTable,
270 model: string,
271 totals: UsageTokenTotals,
272 overrides?: RateTable,
273): number {
274 const rate = overrides?.get(model.trim()) ?? lookupRate(table, model);
275 if (rate === null) return 0;
276 return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken);
277}