Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

openrouter.ts

99 lines3.6 KB

1/**
2 * OpenRouter `pricing` listing → usage-bound token card.
3 *
4 * A listing is USD-per-unit strings (`{ prompt: "0.0000025", completion:
5 * "0.00001", input_cache_read: "0.00000125", … }`). Every priced key becomes
6 * a usage lever billed at its own rate; counts are disjoint (`input_tokens`
7 * excludes the cached tokens billed at `input_cache_read`). At least one of
8 * `prompt` or `completion` must be present; a lever that is present is
9 * required. `requests` defaults to 1, the rest to 0.
10 *
11 * `overrides` entries with `min_prompt_tokens` compile to rate tiers keyed on
12 * total prompt tokens (input + cache read + cache writes). A tier applies
13 * when the total is strictly greater than the threshold (OpenRouter's rule).
14 */
15import { compileTokenCard } from './token-card.ts'
16import type { TokenRateTier } from './token-card.ts'
17import type { RateCard } from './card.ts'
18​
19/** OpenRouter pricing key → the usage lever it prices. */
20const LEVERS: Record<string, string> = {
21 prompt: 'input_tokens',
22 completion: 'output_tokens',
23 input_cache_read: 'cache_read_tokens',
24 input_cache_write: 'cache_write_tokens',
25 input_cache_write_1h: 'cache_write_1h_tokens',
26 internal_reasoning: 'reasoning_tokens',
27 image: 'image_tokens',
28 image_output: 'image_output_tokens',
29 audio: 'audio_tokens',
30 audio_output: 'audio_output_tokens',
31 input_audio_cache: 'audio_cache_tokens',
32 web_search: 'web_searches',
33 request: 'requests',
35​
36const isRecord = (v: unknown): v is Record<string, unknown> =>
37 typeof v === 'object' && v !== null && !Array.isArray(v)
38​
39/** Numeric rates of one listing / override; `null` if any is unusable. */
40function rates(entry: Record<string, unknown>): Record<string, number> | null {
41 const out: Record<string, number> = {}
42 for (const [key, value] of Object.entries(entry)) {
43 if (
44 key === 'overrides' ||
45 key === 'min_prompt_tokens' ||
46 key.startsWith('utc_')
47 )
48 continue
49 if (key === 'discount') continue
50 const n =
51 typeof value === 'number'
52 ? value
53 : typeof value === 'string' && value.trim() !== ''
54 ? Number(value)
55 : NaN
56 // "-1" is OpenRouter's variable-price router sentinel: not a price.
57 if (!Number.isFinite(n) || n < 0) return null
58 out[key] = n
59 }
60 return out
62​
63/** Listing keys → lever names, unmapped keys kept verbatim. */
64function byLever(entry: Record<string, number>): Record<string, number> {
65 return Object.fromEntries(
66 Object.entries(entry).map(([key, rate]) => [LEVERS[key] ?? key, rate]),
67 )
69​
70export function compileOpenRouterPricing(
71 listing: unknown,
72 source: RateCard['source'],
73): RateCard | null {
74 if (!isRecord(listing)) return null
75 const base = rates(listing)
76 // One side is enough: a non-zero prompt or completion is a price. All-zero
77 // listings (and rows with neither key) still price nothing.
78 if (!base || (!('prompt' in base) && !('completion' in base))) return null
79​
80 // ponytail: time-window overrides (`utc_days`/`utc_start`/`utc_end`) need a
81 // clock the card does not have; they are skipped, so the card quotes the
82 // base (peak) rate. Add a usage-bound `utc_*` lever if off-peak quotes matter.
83 const tiers: Array<TokenRateTier> = []
84 for (const override of Array.isArray(listing.overrides)
85 ? listing.overrides
86 : []) {
87 if (!isRecord(override) || typeof override.min_prompt_tokens !== 'number')
88 continue
89 const tier = rates(override)
90 if (!tier) return null
91 tiers.push({
92 minPromptTokens: override.min_prompt_tokens,
93 rates: byLever({ ...base, ...tier }),
94 })
95 }
96​
97 // All-zero (free / placeholder) listings price nothing.
98 return compileTokenCard(byLever(base), tiers, source)