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

usagePricing.ts

222 lines7.8 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, 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;
26​
27/**
28 * Parsed pricing data with source models kept separate from derived aliases.
29 *
30 * Keeping these indexes distinct prevents a convenience alias from inflating
31 * the model count or being mistaken for an exact provider-qualified entry.
32 */
33export interface RateTable {
34 readonly exactRates: ReadonlyMap<string, ModelRate>;
35 readonly bareAliases: ReadonlyMap<string, ModelRate>;
36 readonly modelCount: number;
38​
39export function emptyRateTable(): RateTable {
40 return { exactRates: new Map(), bareAliases: new Map(), modelCount: 0 };
42​
43/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */
44interface LiteLlmEntry {
45 readonly input_cost_per_token?: unknown;
46 readonly output_cost_per_token?: unknown;
47 readonly cache_read_input_token_cost?: unknown;
48 readonly cache_creation_input_token_cost?: unknown;
50​
51function finiteNumber(value: unknown): number | null {
52 return typeof value === "number" && Number.isFinite(value) ? value : null;
54​
55/**
56 * Projects the LiteLLM document into a rate table.
57 *
58 * Entries without both an input and an output rate are dropped: a half-priced
59 * model would silently under-report cost, which is worse than reporting the
60 * model as unpriced. Provider-qualified keys remain distinct. A bare alias is
61 * added only for a canonical entry or one unambiguous provider candidate.
62 */
63export function parseRateTable(document: unknown): RateTable {
64 const candidatesByKey = new Map<
65 string,
66 Array<{ readonly rawName: string; readonly rate: ModelRate }>
67 >();
68 if (typeof document !== "object" || document === null) return emptyRateTable();
69​
70 for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {
71 if (typeof raw !== "object" || raw === null) continue;
72 const entry = raw as LiteLlmEntry;
73 const input = finiteNumber(entry.input_cost_per_token);
74 const output = finiteNumber(entry.output_cost_per_token);
75 if (input === null || output === null) continue;
76​
77 const key = normalizeRateKey(name);
78 if (key.length === 0) continue;
79 const rate = {
80 inputCostPerToken: input,
81 outputCostPerToken: output,
82 // Anthropic bills cache reads at a discount and cache writes at a
83 // premium. When a model omits them, cached input is priced as plain
84 // input rather than as free.
85 cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input,
86 cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input,
87 };
88 const candidates = candidatesByKey.get(key) ?? [];
89 candidates.push({ rawName: name, rate });
90 candidatesByKey.set(key, candidates);
91 }
92​
93 const exactRates = new Map<string, ModelRate>();
94 for (const [key, candidates] of candidatesByKey) {
95 const selected = selectExactCandidate(key, candidates);
96 if (selected !== null) exactRates.set(key, selected.rate);
97 }
98​
99 const candidatesByAlias = new Map<
100 string,
101 Array<{ readonly key: string; readonly rate: ModelRate }>
102 >();
103 for (const [key, rate] of exactRates) {
104 const alias = normalizeModelName(key);
105 const candidates = candidatesByAlias.get(alias) ?? [];
106 candidates.push({ key, rate });
107 candidatesByAlias.set(alias, candidates);
108 }
109​
110 const bareAliases = new Map<string, ModelRate>();
111 for (const [alias, candidates] of candidatesByAlias) {
112 const canonical = candidates.find((candidate) => candidate.key === alias);
113 if (canonical === undefined && candidates.length === 1) {
114 const [candidate] = candidates;
115 if (candidate !== undefined) bareAliases.set(alias, candidate.rate);
116 }
117 }
118​
119 return { exactRates, bareAliases, modelCount: exactRates.size };
121​
122/**
123 * Selects one source entry after normalization.
124 *
125 * A collision is only resolved when one entry has the canonical normalized
126 * spelling verbatim. Otherwise neither variant has trustworthy provenance, so
127 * dropping the key is safer than making pricing depend on document order.
128 */
129function selectExactCandidate(
130 key: string,
131 candidates: readonly { readonly rawName: string; readonly rate: ModelRate }[],
132): { readonly rawName: string; readonly rate: ModelRate } | null {
133 if (candidates.length === 1) return candidates[0] ?? null;
134 return candidates.find((candidate) => candidate.rawName === key) ?? null;
136​
137export function rateTableModelCount(table: RateTable): number {
138 return table.modelCount;
140​
141function normalizeRateKey(model: string): string {
142 return model.trim().toLowerCase();
144​
145/**
146 * Canonicalises a model name for lookup.
147 *
148 * Strips a `provider/` prefix and lowercases. This derives a candidate bare
149 * alias; exact provider-qualified lookup uses the normalized full key first.
150 */
151export function normalizeModelName(model: string): string {
152 const trimmed = normalizeRateKey(model);
153 const slash = trimmed.lastIndexOf("/");
154 return slash === -1 ? trimmed : trimmed.slice(slash + 1);
156​
157/**
158 * Models we never price, regardless of the table.
159 *
160 * `<synthetic>` marks locally generated messages that were never billed. Bare
161 * family names ("opus", "sonnet") are genuinely ambiguous across generations,
162 * so we report them as unpriced instead of guessing a generation.
163 */
164const UNPRICEABLE_MODELS = new Set([
165 "<synthetic>",
166 "synthetic",
167 "opus",
168 "sonnet",
169 "haiku",
170 "fable",
171]);
172​
173export function lookupRate(table: RateTable, model: string): ModelRate | null {
174 const exact = normalizeRateKey(model);
175 const normalized = normalizeModelName(model);
176 if (normalized.length === 0 || UNPRICEABLE_MODELS.has(normalized)) return null;
177 if (exact.includes("/")) return table.exactRates.get(exact) ?? null;
178 return table.exactRates.get(exact) ?? table.bareAliases.get(exact) ?? null;
180​
181export interface PricedUsage {
182 readonly costUsd: number;
183 readonly costSource: UsageCostSource;
185​
186/**
187 * Prices a bucket's tokens.
188 *
189 * `reasoningTokens` is intentionally not charged separately: it is already
190 * counted inside `outputTokens`.
191 */
192export function priceUsage(
193 table: RateTable,
194 model: string,
195 totals: UsageTokenTotals,
196 reportedCostUsd: number | null,
197): PricedUsage {
198 if (reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {
199 return { costUsd: reportedCostUsd, costSource: "providerReported" };
200 }
201​
202 const rate = lookupRate(table, model);
203 if (rate === null) return { costUsd: 0, costSource: "unpriced" };
204​
205 const costUsd =
206 totals.uncachedInputTokens * rate.inputCostPerToken +
207 totals.cachedInputTokens * rate.cacheReadCostPerToken +
208 totals.cacheCreationTokens * rate.cacheCreationCostPerToken +
209 totals.outputTokens * rate.outputCostPerToken;
210​
211 return { costUsd, costSource: "modelPriced" };
213​
214/**
215 * What the cached input would have cost at full input rates, minus what it
216 * actually cost. Drives the "cache savings" figure.
217 */
218export function cacheSavingsUsd(table: RateTable, model: string, totals: UsageTokenTotals): number {
219 const rate = lookupRate(table, model);
220 if (rate === null) return 0;
221 return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken);