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

rate-card.ts

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