Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2
3import { GPT_4O } from '../../packages/rate-card/src/fixtures/gpt-4o.ts'
4import { NANO_BANANA_2 } from '../../packages/rate-card/src/fixtures/nano-banana-2.ts'
5import {
6 cardCurrency,
7 compileOpenRouterPricing,
8 compileTokenCard,
9 compileUnitCard,
10} from '@modelschemas/rate-card'
11import type { RateCard } from '@modelschemas/rate-card'
12
13import { contentHash } from '#/server/kv.ts'
14import { compileSeedanceCard } from '#/server/providers/byteplus-pricing.ts'
15import { bytePlusArkSpec } from '#/server/providers/byteplus-spec.ts'
16import {
17 cardRequestParamsOk,
18 parseStoredRateCard,
19 projectTokenPricing,
20 servePricing,
21 storeListedPricing,
22 toStoredRateCard,
23} from '#/server/rate-card.ts'
24
25const SOURCE_URL = 'https://openrouter.ai/api/v1/models'
26const NOW = 1_781_150_000
27
28const GPT_4O_LISTING = {
29 prompt: '0.0000025',
30 completion: '0.00001',
31 input_cache_read: '0.00000125',
32}
33
34function mediaCard(param: string): RateCard {
35 return {
36 inputs: {
37 duration: { param, kind: 'number', default: 5 },
38 },
39 tables: {},
40 price: { '*': [{ var: 'duration' }, 0.1] },
41 examples: [],
42 source: GPT_4O.source,
43 }
44}
45
46describe('parseStoredRateCard', () => {
47 it('accepts a RateCard and rejects vendor blobs', () => {
48 expect(parseStoredRateCard(GPT_4O)).toEqual(GPT_4O)
49 expect(parseStoredRateCard(GPT_4O_LISTING)).toBeNull()
50 expect(parseStoredRateCard({ prompt: '0', completion: '0' })).toBeNull()
51 expect(
52 parseStoredRateCard({ amount_per_sec: 17, unit: 'credits' }),
53 ).toBeNull()
54 expect(parseStoredRateCard(null)).toBeNull()
55 })
56})
57
58describe('toStoredRateCard', () => {
59 it('stores a RateCard that parses and whose examples verify', async () => {
60 expect(
61 await toStoredRateCard(GPT_4O, { sourceUrl: SOURCE_URL, now: NOW }),
62 ).toEqual(GPT_4O)
63 })
64
65 it('compiles an OpenRouter listing into a usage-bound token card', async () => {
66 const card = await toStoredRateCard(GPT_4O_LISTING, {
67 sourceUrl: SOURCE_URL,
68 now: NOW,
69 })
70 expect(card).not.toBeNull()
71 expect(card?.inputs.input_tokens?.bound).toBe('usage')
72 expect(card?.inputs.output_tokens?.bound).toBe('usage')
73 expect(card?.source.url).toBe(SOURCE_URL)
74 expect(card?.source.hash).toBe(await contentHash(GPT_4O_LISTING))
75 expect(card?.source.extractedAt).toBe(new Date(NOW * 1000).toISOString())
76 })
77
78 it('reuses an existing compiled card when the listing hash matches', async () => {
79 const first = await toStoredRateCard(GPT_4O_LISTING, {
80 sourceUrl: SOURCE_URL,
81 now: NOW,
82 })
83 const later = await toStoredRateCard(GPT_4O_LISTING, {
84 existing: first,
85 sourceUrl: SOURCE_URL,
86 now: NOW + 900,
87 })
88 expect(later).toEqual(first)
89 expect(later?.source.extractedAt).toBe(first?.source.extractedAt)
90 })
91
92 it('turns Together-style all-zero listings into null', async () => {
93 expect(
94 await toStoredRateCard(
95 { prompt: '0', completion: '0' },
96 { sourceUrl: SOURCE_URL, now: NOW },
97 ),
98 ).toBeNull()
99 })
100
101 it('refuses unknown blobs rather than storing them', async () => {
102 expect(
103 await toStoredRateCard(
104 { amount_per_sec: 17, unit: 'credits' },
105 { sourceUrl: SOURCE_URL, now: NOW },
106 ),
107 ).toBeNull()
108 })
109
110 it('refuses a request-bound param that is not on the bound schema', async () => {
111 const card = mediaCard('quality')
112 expect(
113 await toStoredRateCard(card, {
114 sourceUrl: SOURCE_URL,
115 now: NOW,
116 requestProperties: new Set(['model', 'messages']),
117 }),
118 ).toBeNull()
119 })
120
121 it('allows a request-bound param that is a schema property', async () => {
122 const card = mediaCard('duration')
123 expect(
124 await toStoredRateCard(card, {
125 sourceUrl: SOURCE_URL,
126 now: NOW,
127 requestProperties: new Set(['duration', 'generate_audio']),
128 }),
129 ).toEqual(card)
130 })
131
132 it('allows documented card-level levers such as input_tokens', async () => {
133 const card: RateCard = {
134 ...GPT_4O,
135 inputs: {
136 ...GPT_4O.inputs,
137 input_tokens: {
138 param: 'input_tokens',
139 bound: 'request',
140 kind: 'number',
141 },
142 },
143 }
144 expect(
145 await toStoredRateCard(card, {
146 sourceUrl: SOURCE_URL,
147 now: NOW,
148 requestProperties: new Set(['model', 'messages']),
149 }),
150 ).toEqual(card)
151 })
152
153 it('skips the schema check when the model has no bound input schema', async () => {
154 const card = mediaCard('quality')
155 expect(
156 await toStoredRateCard(card, { sourceUrl: SOURCE_URL, now: NOW }),
157 ).toEqual(card)
158 })
159
160 it('recompiles when the listing rates change', async () => {
161 const first = await toStoredRateCard(GPT_4O_LISTING, {
162 sourceUrl: SOURCE_URL,
163 now: NOW,
164 })
165 const raised = { prompt: '0.000005', completion: '0.00002' }
166 const later = await toStoredRateCard(raised, {
167 existing: first,
168 sourceUrl: SOURCE_URL,
169 now: NOW + 900,
170 })
171 expect(later?.source.hash).toBe(await contentHash(raised))
172 expect(later?.source.hash).not.toBe(first?.source.hash)
173 expect(later?.source.extractedAt).toBe(
174 new Date((NOW + 900) * 1000).toISOString(),
175 )
176 })
177
178 it('refuses a schema-valid card whose examples do not verify', async () => {
179 const first = GPT_4O.examples[0]
180 if (!first) throw new Error('fixture missing examples')
181 const bad: RateCard = {
182 ...GPT_4O,
183 examples: [{ ...first, usd: 999 }],
184 }
185 expect(
186 await storeListedPricing(bad, { sourceUrl: SOURCE_URL, now: NOW }),
187 ).toEqual({ card: null, refused: 'examples' })
188 })
189
190 it('keeps the stored card when a re-parse reports the same source hash', async () => {
191 const stored: RateCard = {
192 ...GPT_4O,
193 source: { ...GPT_4O.source, extractedAt: '2026-01-01T00:00:00.000Z' },
194 }
195 const reparsed: RateCard = {
196 ...GPT_4O,
197 source: { ...GPT_4O.source, extractedAt: '2026-06-01T00:00:00.000Z' },
198 }
199 expect(
200 await storeListedPricing(reparsed, {
201 existing: stored,
202 sourceUrl: SOURCE_URL,
203 now: NOW,
204 }),
205 ).toEqual({ card: stored })
206 })
207
208 it('replaces the stored card when the same source text parses to different rates', async () => {
209 const stored: RateCard = {
210 ...GPT_4O,
211 inputs: {
212 ...GPT_4O.inputs,
213 cache_write_tokens: {
214 param: 'cache_write_tokens',
215 bound: 'usage',
216 kind: 'number',
217 },
218 },
219 }
220 const reparsed: RateCard = {
221 ...GPT_4O,
222 source: { ...GPT_4O.source, extractedAt: '2026-06-01T00:00:00.000Z' },
223 }
224 expect(
225 await storeListedPricing(reparsed, {
226 existing: stored,
227 sourceUrl: SOURCE_URL,
228 now: NOW,
229 }),
230 ).toEqual({ card: reparsed })
231 })
232
233 it('re-reads a card whose source named a price change that has passed', async () => {
234 const stored: RateCard = {
235 ...GPT_4O,
236 source: {
237 ...GPT_4O.source,
238 extractedAt: '2026-01-01T00:00:00.000Z',
239 expiresAt: '2026-06-01T00:00:00.000Z',
240 },
241 }
242 const reparsed: RateCard = {
243 ...GPT_4O,
244 source: { ...GPT_4O.source, extractedAt: '2026-06-02T00:00:00.000Z' },
245 }
246 expect(
247 await storeListedPricing(reparsed, {
248 existing: stored,
249 sourceUrl: SOURCE_URL,
250 now: NOW,
251 }),
252 ).toEqual({ card: reparsed })
253 })
254
255 it('names invented_param vs uncompilable on refuse', async () => {
256 expect(
257 await storeListedPricing(mediaCard('quality'), {
258 sourceUrl: SOURCE_URL,
259 now: NOW,
260 requestProperties: new Set(['model']),
261 }),
262 ).toEqual({ card: null, refused: 'invented_param' })
263 expect(
264 await storeListedPricing(
265 { prompt: '0', completion: '0' },
266 { sourceUrl: SOURCE_URL, now: NOW },
267 ),
268 ).toEqual({ card: null, refused: 'uncompilable' })
269 })
270})
271
272describe('projectTokenPricing', () => {
273 it('projects a simple token formula to per-million rates', () => {
274 expect(projectTokenPricing(GPT_4O)).toEqual({
275 currency: 'USD',
276 per: 'token',
277 inputPerMillion: 2.5,
278 outputPerMillion: 10,
279 })
280 })
281
282 it('says which currency the rates are in', () => {
283 const card = compileTokenCard(
284 { input_tokens: 20 / 1e6, output_tokens: 100 / 1e6 },
285 [],
286 GPT_4O.source,
287 { currency: 'CNY' },
288 )
289 if (!card) throw new Error('did not compile')
290 expect(projectTokenPricing(card)).toEqual({
291 currency: 'CNY',
292 per: 'token',
293 inputPerMillion: 20,
294 outputPerMillion: 100,
295 })
296 // The currency survives the stored-card parse, so it is never USD.
297 const stored = parseStoredRateCard(JSON.parse(JSON.stringify(card)))
298 expect(stored && cardCurrency(stored)).toBe('CNY')
299 })
300
301 // Per-token rates whose `× 1e6` is not the published figure in a double.
302 it.each([
303 [2e-7, 0.2],
304 [1.45e-6, 1.45],
305 [6.72e-7, 0.672],
306 [1.7e-7, 0.17],
307 [2.64e-7, 0.264],
308 [2.76e-7, 0.276],
309 [3e-8, 0.03],
310 [1.5e-5, 15],
311 ])('serves %d per token as %d per million, no float noise', (rate, per) => {
312 const card = compileTokenCard(
313 { input_tokens: rate, output_tokens: rate },
314 [],
315 GPT_4O.source,
316 )
317 if (!card) throw new Error('did not compile')
318 expect(projectTokenPricing(card)).toEqual({
319 currency: 'USD',
320 per: 'token',
321 inputPerMillion: per,
322 outputPerMillion: per,
323 })
324 })
325
326 it('names the unit a media card bills by', () => {
327 expect(projectTokenPricing(NANO_BANANA_2)).toEqual({
328 currency: 'USD',
329 per: 'image',
330 })
331 const perSecond = compileUnitCard(
332 { quantity: { param: 'audio_seconds', bound: 'usage' }, rates: 1e-4 },
333 GPT_4O.source,
334 )
335 if (!perSecond) throw new Error('did not compile')
336 expect(projectTokenPricing(perSecond)).toEqual({
337 currency: 'USD',
338 per: 'second',
339 })
340 const flat = compileUnitCard({ rates: 0.08 }, GPT_4O.source)
341 if (!flat) throw new Error('did not compile')
342 expect(projectTokenPricing(flat)).toEqual({
343 currency: 'USD',
344 per: 'request',
345 })
346 })
347
348 it('shows the base rate of a tiered card and says so', () => {
349 const card = compileTokenCard(
350 { input_tokens: 10e-6, output_tokens: 50e-6 },
351 [
352 {
353 minPromptTokens: 272_000,
354 rates: { input_tokens: 20e-6, output_tokens: 75e-6 },
355 },
356 ],
357 GPT_4O.source,
358 )
359 if (!card) throw new Error('did not compile')
360 expect(projectTokenPricing(card)).toEqual({
361 currency: 'USD',
362 per: 'token',
363 inputPerMillion: 10,
364 outputPerMillion: 50,
365 tiered: true,
366 })
367 })
368
369 it('projects an embeddings card without an output rate', () => {
370 const card = compileTokenCard({ input_tokens: 0.02e-6 }, [], GPT_4O.source)
371 if (!card) throw new Error('did not compile')
372 expect(projectTokenPricing(card)).toEqual({
373 currency: 'USD',
374 per: 'token',
375 inputPerMillion: 0.02,
376 })
377 })
378
379 it('drops the rates when a per-request fee breaks linearity', () => {
380 const card = compileOpenRouterPricing(
381 {
382 prompt: '0.0000025',
383 completion: '0.00001',
384 request: '0.01',
385 },
386 GPT_4O.source,
387 )
388 expect(card).not.toBeNull()
389 if (!card) return
390 expect(projectTokenPricing(card)).toEqual({
391 currency: 'USD',
392 per: 'token',
393 })
394 expect(servePricing(card, 'full')).toEqual(card)
395 })
396})
397
398describe('servePricing', () => {
399 it('serves a compact projection on list and the full card on detail', () => {
400 expect(servePricing(GPT_4O, 'compact')).toEqual({
401 currency: 'USD',
402 per: 'token',
403 inputPerMillion: 2.5,
404 outputPerMillion: 10,
405 })
406 expect(servePricing(GPT_4O, 'full')).toEqual(GPT_4O)
407 expect(servePricing(NANO_BANANA_2, 'compact')).toEqual({
408 currency: 'USD',
409 per: 'image',
410 })
411 expect(servePricing(NANO_BANANA_2, 'full')).toEqual(NANO_BANANA_2)
412 })
413
414 it('does not serve leftover vendor blobs', () => {
415 expect(servePricing(GPT_4O_LISTING, 'full')).toBeNull()
416 expect(servePricing({ prompt: '0', completion: '0' }, 'compact')).toBeNull()
417 })
418})
419
420/** A Seedance-shaped card whose completion_tokens estimate reads `guideHash`. */
421function estimatedCard(guideHash: string, param = 'duration'): RateCard {
422 const card = compileSeedanceCard(
423 { default: { '*': { all: 2.5 } } },
424 GPT_4O.source,
425 {
426 model: { fps: 24, dims: { '720p': { '16:9': { w: 1280, h: 720 } } } },
427 url: 'https://example.com/guide',
428 hash: guideHash,
429 },
430 )
431 if (!card) throw new Error('no card')
432 const tokens = card.inputs.completion_tokens
433 if (tokens?.kind === 'number' && tokens.estimate && param !== 'duration') {
434 tokens.estimate.inputs.duration = { param, kind: 'number' }
435 }
436 return card
437}
438
439describe('estimate sources', () => {
440 it('replaces a stored card when only the estimate source changed', async () => {
441 const stored = estimatedCard('b'.repeat(64))
442 const fresh = estimatedCard('c'.repeat(64))
443 expect(
444 await storeListedPricing(fresh, {
445 existing: stored,
446 sourceUrl: SOURCE_URL,
447 now: NOW,
448 }),
449 ).toEqual({ card: fresh })
450 expect(
451 await storeListedPricing(estimatedCard('b'.repeat(64)), {
452 existing: stored,
453 sourceUrl: SOURCE_URL,
454 now: NOW,
455 }),
456 ).toEqual({ card: stored })
457 })
458
459 it("checks an estimate's request levers against the bound schema", () => {
460 const spec = bytePlusArkSpec() as {
461 components: { schemas: Record<string, { properties?: object }> }
462 }
463 const task = new Set(
464 Object.keys(
465 spec.components.schemas.VideoTaskCreateRequest?.properties ?? {},
466 ),
467 )
468 expect(cardRequestParamsOk(estimatedCard('b'.repeat(64)), task)).toBe(true)
469 expect(
470 cardRequestParamsOk(estimatedCard('b'.repeat(64), 'seconds'), task),
471 ).toBe(false)
472 })
473})