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

usagePricing.ts

148 lines5.0 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​
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;
36​
37function finiteNumber(value: unknown): number | null {
38 return typeof value === "number" && Number.isFinite(value) ? value : null;
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;
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);
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 normalized = normalizeModelName(model);
103 if (normalized.length === 0 || UNPRICEABLE_MODELS.has(normalized)) return null;
104 return table.get(normalized) ?? null;
106​
107export interface PricedUsage {
108 readonly costUsd: number;
109 readonly costSource: UsageCostSource;
111​
112/**
113 * Prices a bucket's tokens.
114 *
115 * `reasoningTokens` is intentionally not charged separately: it is already
116 * counted inside `outputTokens`.
117 */
118export function priceUsage(
119 table: RateTable,
120 model: string,
121 totals: UsageTokenTotals,
122 reportedCostUsd: number | null,
123): PricedUsage {
124 if (reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {
125 return { costUsd: reportedCostUsd, costSource: "providerReported" };
126 }
127​
128 const rate = lookupRate(table, model);
129 if (rate === null) return { costUsd: 0, costSource: "unpriced" };
130​
131 const costUsd =
132 totals.uncachedInputTokens * rate.inputCostPerToken +
133 totals.cachedInputTokens * rate.cacheReadCostPerToken +
134 totals.cacheCreationTokens * rate.cacheCreationCostPerToken +
135 totals.outputTokens * rate.outputCostPerToken;
136​
137 return { costUsd, costSource: "modelPriced" };
139​
140/**
141 * What the cached input would have cost at full input rates, minus what it
142 * actually cost. Drives the "cache savings" figure.
143 */
144export function cacheSavingsUsd(table: RateTable, model: string, totals: UsageTokenTotals): number {
145 const rate = lookupRate(table, model);
146 if (rate === null) return 0;
147 return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken);