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

rate-card.ts

331 lines10.4 KB

1/**
2 * Rate cards on the catalog (issue #60): store only values that parse as
3 * RateCard, compile OpenRouter listings at write, and project a compact
4 * token formula on list rows.
5 */
6import {
7 cardCurrency,
8 compileOpenRouterPricing,
9 price,
10 rateCardSchema,
11 RateCardError,
12 verifyExamples,
13} from '@modelschemas/rate-card'
14import type { RateCard } from '@modelschemas/rate-card'
15​
16import { contentHash, stableStringify } from '#/server/kv.ts'
17import { emptySources } from '#/server/providers/fact-sources.ts'
18import type { ModelFactSources } from '#/server/providers/types.ts'
19​
20/**
21 * Request-bound param names allowed even when they are not properties of
22 * the bound input schema (`input_tokens` is the type specimen). Usage-bound
23 * params skip this check.
24 */
25const CARD_LEVEL_LEVERS = new Set([
26 'input_tokens',
27 'output_tokens',
28 'cache_read_tokens',
29 'cache_write_tokens',
30 'cache_write_1h_tokens',
31 'reasoning_tokens',
32 'image_tokens',
33 'image_output_tokens',
34 'audio_tokens',
35 'audio_output_tokens',
36 'audio_cache_tokens',
37 'web_searches',
38 'requests',
39 // Seedance reference-video seconds. Not a generation-schema property;
40 // refusing it nulled the whole stored card.
41 'input_video_duration',
42])
43​
44/**
45 * What a list row says about a stored card. `null` on the row means no
46 * card; this means there is one. Token cards carry their per-million rates
47 * when those are linear (`tiered` marks a long-prompt re-quote above some
48 * threshold — the rates shown are the base); everything else names the
49 * unit it bills by and points at the full card. `currency` is the
50 * ISO-4217 code the rates are in; rows in different currencies do not
51 * compare.
52 */
53export type CompactPricing = {
54 currency: string
55 per: 'token' | 'second' | 'character' | 'image' | 'request' | 'unit'
56 inputPerMillion?: number
57 outputPerMillion?: number
58 tiered?: true
60​
61export function parseStoredRateCard(value: unknown): RateCard | null {
62 const parsed = rateCardSchema.safeParse(value)
63 return parsed.success ? parsed.data : null
65​
66function requestParamAllowed(
67 param: string,
68 requestProperties: ReadonlySet<string> | undefined,
69): boolean {
70 if (requestProperties === undefined) return true
71 if (CARD_LEVEL_LEVERS.has(param)) return true
72 if (requestProperties.has(param)) return true
73 const root = param.split('.')[0]
74 return root !== undefined && requestProperties.has(root)
76​
77export function cardRequestParamsOk(
78 card: RateCard,
79 requestProperties: ReadonlySet<string> | undefined,
80): boolean {
81 const inputs = Object.values(card.inputs).flatMap((input) => [
82 input,
83 ...(input.kind === 'number' && input.estimate
84 ? Object.values(input.estimate.inputs)
85 : []),
86 ])
87 for (const input of inputs) {
88 if (input.bound === 'usage') continue
89 if (!requestParamAllowed(input.param, requestProperties)) return false
90 }
91 return true
93​
94function examplesOk(card: RateCard): boolean {
95 return !verifyExamples(card).some((result) => !result.ok)
97​
98export interface StoreRateCardOptions {
99 /** Previously stored `models.pricing`, used to keep `source.extractedAt`. */
100 existing?: unknown
101 /**
102 * Top-level properties of the bound input schema. `undefined` skips the
103 * invented-field check (no bound schema). An empty set still refuses
104 * unknown request-bound params.
105 */
106 requestProperties?: ReadonlySet<string>
107 sourceUrl: string
108 /** Poll time, epoch seconds. */
109 now: number
111​
112export type RateCardRefuse = 'invented_param' | 'examples' | 'uncompilable'
113​
114export type StoredPricing = {
115 card: RateCard | null
116 refused?: RateCardRefuse
118​
119/**
120 * Value to write to `models.pricing`. Null means unknown — never a vendor
121 * blob, never an all-zero OpenRouter-shaped listing.
122 */
123/** Every source text a card was read from: its own plus each estimate's. */
124function sourceHashes(card: RateCard): string {
125 return [
126 card.source.hash,
127 ...Object.values(card.inputs).flatMap((input) =>
128 input.kind === 'number' && input.estimate
129 ? [input.estimate.source.hash]
130 : [],
131 ),
132 ].join()
134​
135/**
136 * A stored card stands in for a fresh one while all its source text is
137 * unchanged — except past `expiresAt`, the instant the source said the
138 * price changes, where the re-read wins.
139 */
140function reusable(
141 prior: RateCard | null,
142 hashes: string,
143 now: number,
144): prior is RateCard {
145 if (!prior || sourceHashes(prior) !== hashes) return false
146 const expiresAt = prior.source.expiresAt
147 return expiresAt === undefined || Date.parse(expiresAt) > now * 1000
149​
150/** Card contents with `extractedAt` removed, so a poll clock is not a rate change. */
151function rateBody(card: RateCard): string {
152 const { extractedAt: _extractedAt, ...source } = card.source
153 return stableStringify({ ...card, source })
155​
156export async function storeListedPricing(
157 pricing: unknown,
158 options: StoreRateCardOptions,
159): Promise<StoredPricing> {
160 if (pricing == null) return { card: null }
161​
162 const parsed = parseStoredRateCard(pricing)
163 if (parsed) {
164 if (!cardRequestParamsOk(parsed, options.requestProperties)) {
165 return { card: null, refused: 'invented_param' }
166 }
167 if (!examplesOk(parsed)) return { card: null, refused: 'examples' }
168 // Same source text and the same rates: keep the stored card so a fresh
169 // `extractedAt` alone is not a price change on every poll. A parser that
170 // reads different levers from that text replaces the stored card.
171 const prior = parseStoredRateCard(options.existing)
172 const sameRates =
173 reusable(prior, sourceHashes(parsed), options.now) &&
174 rateBody(prior) === rateBody(parsed)
175 return { card: sameRates ? prior : parsed }
176 }
177​
178 const existing = parseStoredRateCard(options.existing)
179 const listingHash = await contentHash(pricing)
180 if (reusable(existing, listingHash, options.now)) {
181 if (!cardRequestParamsOk(existing, options.requestProperties)) {
182 return { card: null, refused: 'invented_param' }
183 }
184 return { card: existing }
185 }
186​
187 const compiled = compileOpenRouterPricing(pricing, {
188 url: options.sourceUrl,
189 hash: listingHash,
190 extractedAt: new Date(options.now * 1000).toISOString(),
191 })
192 if (!compiled) return { card: null, refused: 'uncompilable' }
193 if (!cardRequestParamsOk(compiled, options.requestProperties)) {
194 return { card: null, refused: 'invented_param' }
195 }
196 return { card: compiled }
198​
199export async function toStoredRateCard(
200 pricing: unknown,
201 options: StoreRateCardOptions,
202): Promise<RateCard | null> {
203 return (await storeListedPricing(pricing, options)).card
205​
206/**
207 * Drop `factSources.pricing` when the stored card is null. If a card is
208 * stored and pricing provenance is missing, stamp `{ derivation: listing }`.
209 */
210export function reconcilePricingSource(
211 sources: ModelFactSources | null | undefined,
212 card: RateCard | null,
213): ModelFactSources | null {
214 const next: ModelFactSources = { ...(sources ?? {}) }
215 if (card === null) delete next.pricing
216 else if (next.pricing === undefined) next.pricing = { derivation: 'listing' }
217 return emptySources(next) ? null : next
219​
220function isTokenCard(card: RateCard): boolean {
221 let hasInput = false
222 for (const input of Object.values(card.inputs)) {
223 if (input.bound !== 'usage' || input.kind !== 'number') return false
224 if (input.param === 'input_tokens') hasInput = true
225 }
226 return hasInput
228​
229function tryPrice(
230 card: RateCard,
231 usage: Record<string, number>,
232): number | null {
233 try {
234 return price(card, {}, usage)
235 } catch (error) {
236 if (error instanceof RateCardError) return null
237 throw error
238 }
240​
241const LINEAR_REL_TOL = 1e-6
242​
243function linear(unitRate: number, count: number, total: number): boolean {
244 return (
245 Math.abs(unitRate * count - total) <=
246 Math.max(1e-9, Math.abs(total) * LINEAR_REL_TOL)
247 )
249​
250/**
251 * Per-million rate of one lever, probed below any prompt-size tier
252 * (1 and 1,000 tokens), plus whether a million tokens still price
253 * linearly. Null when a per-request fee or the like breaks linearity.
254 */
255function perMillion(
256 card: RateCard,
257 lever: string,
258 zeros: Record<string, number>,
259): { rate: number; tiered: boolean } | null {
260 const at1 = tryPrice(card, { ...zeros, [lever]: 1 })
261 const at1k = tryPrice(card, { ...zeros, [lever]: 1_000 })
262 const at1m = tryPrice(card, { ...zeros, [lever]: 1_000_000 })
263 if (at1 === null || at1k === null || at1m === null) return null
264 if (!linear(at1, 1_000, at1k)) return null
265 return {
266 // 2e-7 * 1e6 is 0.19999999999999998: drop the float noise, which sits
267 // past any digit a price is published to.
268 rate: Number((at1 * 1_000_000).toPrecision(12)),
269 tiered: !linear(at1, 1_000_000, at1m),
270 }
272​
273/** The unit a non-token card's quantity lever counts. */
274const UNIT_OF_LEVER: Record<string, CompactPricing['per']> = {
275 seconds: 'second',
276 audio_seconds: 'second',
277 video_seconds: 'second',
278 duration: 'second',
279 characters: 'character',
280 n: 'image',
281 num_images: 'image',
282 images: 'image',
284​
285/**
286 * List-row summary of a card. A token card gets `inputPerMillion` (and
287 * `outputPerMillion` when it prices output) at the base rate, `tiered`
288 * when a long prompt re-quotes the request; a token card whose price is
289 * not linear in either (a per-request fee) gets `per: 'token'` alone.
290 * Other cards name what they bill by, or `unit` when that is not obvious.
291 */
292export function projectTokenPricing(card: RateCard): CompactPricing {
293 const currency = cardCurrency(card)
294 if (!isTokenCard(card)) {
295 const quantity = Object.values(card.inputs).find(
296 (input) => input.kind === 'number',
297 )
298 return {
299 currency,
300 per: quantity ? (UNIT_OF_LEVER[quantity.param] ?? 'unit') : 'request',
301 }
302 }
303 const hasOutput = Object.values(card.inputs).some(
304 (input) => input.param === 'output_tokens',
305 )
306 const zeros: Record<string, number> = hasOutput
307 ? { input_tokens: 0, output_tokens: 0 }
308 : {}
309 const input = perMillion(card, 'input_tokens', zeros)
310 const output = hasOutput ? perMillion(card, 'output_tokens', zeros) : null
311 if (input === null || (hasOutput && output === null)) {
312 return { currency, per: 'token' }
313 }
314 return {
315 currency,
316 per: 'token',
317 inputPerMillion: input.rate,
318 ...(output && { outputPerMillion: output.rate }),
319 ...((input.tiered || output?.tiered) && { tiered: true as const }),
320 }
322​
323export function servePricing(
324 value: unknown,
325 mode: 'compact' | 'full',
326): RateCard | CompactPricing | null {
327 const card = parseStoredRateCard(value)
328 if (!card) return null
329 if (mode === 'full') return card
330 return projectTokenPricing(card)