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 { UsageCostSource, UsageTokenTotals } from "@t3tools/contracts";
11
12/**
13 * The subset of a LiteLLM entry we price against. All values are USD per token.
14 *
15 * LiteLLM also publishes tiered variants (`*_above_272k_tokens`, `*_flex`,
16 * `*_priority`, `*_batches`). We deliberately price at the base tier: the
17 * transcripts don't record which tier served a request, so anything else would
18 * be a guess dressed up as precision.
19 */
20export interface ModelRate {
21 readonly inputCostPerToken: number;
22 readonly outputCostPerToken: number;
23 readonly cacheReadCostPerToken: number;
24 readonly cacheCreationCostPerToken: number;
25}
26
27export type RateTable = ReadonlyMap<string, ModelRate>;
28
29/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */
30interface LiteLlmEntry {
31 readonly input_cost_per_token?: unknown;
32 readonly output_cost_per_token?: unknown;
33 readonly cache_read_input_token_cost?: unknown;
34 readonly cache_creation_input_token_cost?: unknown;
35}
36
37function finiteNumber(value: unknown): number | null {
38 return typeof value === "number" && Number.isFinite(value) ? value : null;
39}
40
41/**
42 * Projects the LiteLLM document into a rate table.
43 *
44 * Entries without both an input and an output rate are dropped: a half-priced
45 * model would silently under-report cost, which is worse than reporting the
46 * model as unpriced.
47 */
48export function parseRateTable(document: unknown): RateTable {
49 const table = new Map<string, ModelRate>();
50 if (typeof document !== "object" || document === null) return table;
51
52 for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
53 if (typeof raw !== "object" || raw === null) continue;
54 const entry = raw as LiteLlmEntry;
55 const input = finiteNumber(entry.input_cost_per_token);
56 const output = finiteNumber(entry.output_cost_per_token);
57 if (input === null || output === null) continue;
58
59 table.set(normalizeModelName(name), {
60 inputCostPerToken: input,
61 outputCostPerToken: output,
62 // Anthropic bills cache reads at a discount and cache writes at a
63 // premium. When a model omits them, cached input is priced as plain
64 // input rather than as free.
65 cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input,
66 cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input,
67 });
68 }
69 return table;
70}
71
72/**
73 * Canonicalises a model name for lookup.
74 *
75 * Strips a `provider/` prefix (LiteLLM publishes both `claude-opus-5` and
76 * `anthropic/claude-opus-5`) and lowercases, since transcripts are inconsistent
77 * about casing.
78 */
79export function normalizeModelName(model: string): string {
80 const trimmed = model.trim().toLowerCase();
81 const slash = trimmed.lastIndexOf("/");
82 return slash === -1 ? trimmed : trimmed.slice(slash + 1);
83}
84
85/**
86 * Models we never price, regardless of the table.
87 *
88 * `<synthetic>` marks locally generated messages that were never billed. Bare
89 * family names ("opus", "sonnet") are genuinely ambiguous across generations,
90 * so we report them as unpriced instead of guessing a generation.
91 */
92const UNPRICEABLE_MODELS = new Set([
93 "<synthetic>",
94 "synthetic",
95 "opus",
96 "sonnet",
97 "haiku",
98 "fable",
99]);
100
101export function lookupRate(table: RateTable, model: string): ModelRate | null {
102 const trimmed = model.trim();
103 if (trimmed.length === 0) return null;
104 // A fully-qualified name (OpenCode's `providerID/modelID`) keys its own row,
105 // so two subscriptions pricing the same model differently stay distinct.
106 const direct = table.get(trimmed);
107 if (direct !== undefined) return direct;
108 const normalized = normalizeModelName(trimmed);
109 if (normalized.length === 0 || UNPRICEABLE_MODELS.has(normalized)) return null;
110 return table.get(normalized) ?? null;
111}
112
113export interface PricedUsage {
114 readonly costUsd: number;
115 readonly costSource: UsageCostSource;
116}
117
118/**
119 * Prices a bucket's tokens.
120 *
121 * `reasoningTokens` is intentionally not charged separately: it is already
122 * counted inside `outputTokens`.
123 */
124export function priceUsage(
125 table: RateTable,
126 model: string,
127 totals: UsageTokenTotals,
128 reportedCostUsd: number | null,
129): PricedUsage {
130 if (reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {
131 return { costUsd: reportedCostUsd, costSource: "providerReported" };
132 }
133
134 const rate = lookupRate(table, model);
135 if (rate === null) return { costUsd: 0, costSource: "unpriced" };
136
137 const costUsd =
138 totals.uncachedInputTokens * rate.inputCostPerToken +
139 totals.cachedInputTokens * rate.cacheReadCostPerToken +
140 totals.cacheCreationTokens * rate.cacheCreationCostPerToken +
141 totals.outputTokens * rate.outputCostPerToken;
142
143 return { costUsd, costSource: "modelPriced" };
144}
145
146/**
147 * What the cached input would have cost at full input rates, minus what it
148 * actually cost. Drives the "cache savings" figure.
149 */
150export function cacheSavingsUsd(table: RateTable, model: string, totals: UsageTokenTotals): number {
151 const rate = lookupRate(table, model);
152 if (rate === null) return 0;
153 return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken);
154}
155
156/* -------------------------------------------------------------------------- */
157/* models.dev (OpenCode go/zen) */
158/* -------------------------------------------------------------------------- */
159
160/**
161 * The models.dev providers that carry OpenCode's own subscription models.
162 *
163 * OpenCode's go tier is `opencode-go`; its zen tier is keyed as `opencode`.
164 * The names are stored as `providerID/modelID`, so the two tiers can price the
165 * same model id differently (go's "2x usage" models cost half per token).
166 */
167const MODELS_DEV_OPENCODE_PROVIDERS = ["opencode-go", "opencode"] as const;
168
169/**
170 * Projects the models.dev document into a rate table for OpenCode's go/zen
171 * models.
172 *
173 * models.dev lists prices in US dollars per million tokens. Entries without
174 * both an input and an output rate are dropped; a half-priced model would
175 * silently under-report cost, the same rule as the LiteLLM table.
176 *
177 * Rows are keyed by the fully-qualified `providerID/modelID` name so go and zen
178 * prices for one model id never collapse into each other.
179 */
180export function parseOpenCodeRates(document: unknown): RateTable {
181 const table = new Map<string, ModelRate>();
182 if (typeof document !== "object" || document === null) return table;
183 const root = document as Record<string, unknown>;
184
185 for (const providerId of MODELS_DEV_OPENCODE_PROVIDERS) {
186 const provider = root[providerId];
187 if (typeof provider !== "object" || provider === null) continue;
188 const models = (provider as Record<string, unknown>)["models"];
189 if (typeof models !== "object" || models === null) continue;
190
191 for (const [name, raw] of Object.entries(models as Record<string, unknown>)) {
192 if (typeof raw !== "object" || raw === null) continue;
193 const cost = (raw as Record<string, unknown>)["cost"];
194 if (typeof cost !== "object" || cost === null) continue;
195 const costRecord = cost as Record<string, unknown>;
196
197 const input = finiteNumber(costRecord["input"]);
198 const output = finiteNumber(costRecord["output"]);
199 if (input === null || output === null) continue;
200
201 const inputPerToken = input / 1_000_000;
202 table.set(`${providerId}/${name}`, {
203 inputCostPerToken: inputPerToken,
204 outputCostPerToken: output / 1_000_000,
205 // When a model omits them, cached input is priced as plain input.
206 cacheReadCostPerToken: (finiteNumber(costRecord["cache_read"]) ?? input) / 1_000_000,
207 cacheCreationCostPerToken: (finiteNumber(costRecord["cache_write"]) ?? input) / 1_000_000,
208 });
209 }
210 }
211 return table;
212}
213
214/** Overlays one rate table on another; later entries win on conflict. */
215export function mergeRateTables(base: RateTable, overlay: RateTable): RateTable {
216 const merged = new Map(base);
217 for (const [name, rate] of overlay) merged.set(name, rate);
218 return merged;
219}