Open History to see the last commit
1/**
2 * Per-token rate sheet → usage-bound token card.
3 *
4 * The shape every host publishes: a rate per lever (`input_tokens`,
5 * `output_tokens`, cache reads/writes, media tokens), optionally re-quoted
6 * above a prompt-size threshold. Counts are disjoint — `input_tokens`
7 * excludes tokens billed at `cache_read_tokens`. `input_tokens` and
8 * `output_tokens` are required when priced; `requests` defaults to 1, every
9 * other lever to 0, so a caller only supplies what it used.
10 *
11 * `compileOpenRouterPricing` maps OpenRouter's listing keys onto these
12 * levers; the native providers build the rate map from their own docs.
13 */
14import type { Expr, RateCard, Table } from './rate-card.schema.ts'
15
16/** Levers a tier threshold counts as prompt tokens. */
17const PROMPT_LEVERS = [
18 'input_tokens',
19 'cache_read_tokens',
20 'cache_write_tokens',
21 'cache_write_1h_tokens',
22]
23
24const REQUIRED = new Set(['input_tokens', 'output_tokens'])
25
26/** A re-quote that applies above `minPromptTokens` prompt tokens. */
27export interface TokenRateTier {
28 minPromptTokens: number
29 /** Full rate map at this tier (missing levers fall back to the base). */
30 rates: Record<string, number>
31}
32
33function usable(rates: Record<string, number>): boolean {
34 return Object.values(rates).every((n) => Number.isFinite(n) && n >= 0)
35}
36
37/** USD prices stay bare; any other currency wraps the expression. */
38function inCurrency(
39 currency: string | undefined,
40 expr: Expr,
41): RateCard['price'] {
42 return currency === undefined || currency === 'USD'
43 ? expr
44 : { currency: [currency, expr] }
45}
46
47/**
48 * `null` when nothing is priced: an empty, negative/NaN, or all-zero rate
49 * map is "unknown", never a free card.
50 *
51 * `extraPromptLevers` join the threshold sum. The default set is text and
52 * cache tokens; a host whose prompt length also counts audio passes those
53 * levers here so other hosts stay on the default. `currency` is the
54 * ISO-4217 code the rates are in; omit it for USD.
55 */
56export function compileTokenCard(
57 base: Record<string, number>,
58 tiers: Array<TokenRateTier>,
59 source: RateCard['source'],
60 options?: { extraPromptLevers?: ReadonlyArray<string>; currency?: string },
61): RateCard | null {
62 if (Object.keys(base).length === 0 || !usable(base)) return null
63 if (Object.values(base).every((n) => n === 0)) return null
64 if (tiers.some((tier) => !usable(tier.rates))) return null
65
66 const sorted = [...tiers].sort(
67 (a, b) => b.minPromptTokens - a.minPromptTokens,
68 )
69 const levers = [
70 ...new Set([base, ...sorted.map((t) => t.rates)].flatMap(Object.keys)),
71 ]
72 const promptTotal: Expr = {
73 '+': [...PROMPT_LEVERS, ...(options?.extraPromptLevers ?? [])]
74 .filter((lever, index, all) => all.indexOf(lever) === index)
75 .filter((lever) => levers.includes(lever))
76 .map((lever) => ({ var: lever })),
77 }
78 // Highest matching threshold wins; at or below every threshold is base.
79 const tierKey: Expr =
80 sorted.length === 0
81 ? 'base'
82 : {
83 if: [
84 ...sorted.flatMap((tier): Expr[] => [
85 { '>': [promptTotal, tier.minPromptTokens] },
86 String(tier.minPromptTokens),
87 ]),
88 'base',
89 ],
90 }
91
92 const table: Table = { base }
93 for (const tier of sorted) {
94 table[String(tier.minPromptTokens)] = { ...base, ...tier.rates }
95 }
96
97 return {
98 inputs: Object.fromEntries(
99 levers.map((lever) => [
100 lever,
101 {
102 param: lever,
103 bound: 'usage',
104 kind: 'number',
105 ...(!REQUIRED.has(lever) && {
106 default: lever === 'requests' ? 1 : 0,
107 }),
108 },
109 ]),
110 ),
111 tables: { rate: table },
112 price: inCurrency(options?.currency, {
113 '+': levers.map(
114 (lever): Expr => ({
115 // A zero count skips the lookup, so a lever a tier leaves unpriced
116 // refuses only when it is actually used.
117 if: [
118 { '>': [{ var: lever }, 0] },
119 {
120 '*': [
121 { var: lever },
122 { lookup: { table: 'rate', keys: [tierKey, lever] } },
123 ],
124 },
125 0,
126 ],
127 }),
128 ),
129 }),
130 examples: [],
131 source,
132 }
133}