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

model-facts.test.ts

1,238 lines38.0 KB

1import { describe, expect, it } from 'vitest'
2​
3import { anthropicCapabilities } from './anthropic.ts'
4import { parseAnthropicPricing } from './anthropic-pricing.ts'
5import { ANTHROPIC_PRICING_PAGE } from './fixtures/anthropic-pricing.ts'
6import { parseGeminiPricing } from './gemini-pricing.ts'
7import { geminiCapabilities } from './gemini.ts'
8import {
9 grokImageCard,
10 grokRateCard,
11 grokVideoCard,
12 parseGrokContextWindows,
13 parseGrokMaxOutput,
14 grokReasons,
15 parseGrokVideoPrices,
16 withGrokImageQuality,
17} from './grok.ts'
18import { markdownTableRows, tokenCount, undatedId } from './model-facts.ts'
19import { price } from '@modelschemas/rate-card'
20import { openAiCompatModelFacts } from './openai-compat.ts'
21import {
22 pageSlugFor,
23 parseModelIndex,
24 parseModelPage,
25 parseModelPricing,
26 parseOpenAiSearchPricing,
27 parseReasoningEffort,
28} from './openai-model-docs.ts'
29​
30describe('model-facts helpers', () => {
31 it('parses token counts with separators and k/M suffixes', () => {
32 expect(tokenCount('1,048,576')).toBe(1_048_576)
33 expect(tokenCount('500k')).toBe(500_000)
34 expect(tokenCount('1M')).toBe(1_000_000)
35 })
36​
37 it('strips snapshot dates', () => {
38 expect(undatedId('gpt-5-2025-08-07')).toBe('gpt-5')
39 expect(undatedId('claude-opus-4-5-20251101')).toBe('claude-opus-4-5')
40 expect(undatedId('grok-4.20-0309-reasoning')).toBe(
41 'grok-4.20-0309-reasoning',
42 )
43 })
44​
45 it('splits markdown table rows and drops separators', () => {
46 expect(
47 markdownTableRows('| a | b |\n| --- | ---: |\n| 1 | 2 |\ntext'),
48 ).toEqual([
49 ['a', 'b'],
50 ['1', '2'],
51 ])
52 })
53})
54​
55describe('anthropic models api', () => {
56 it('derives request features only from the capability tree', () => {
57 expect(
58 anthropicCapabilities({
59 id: 'claude-fable-5-1',
60 capabilities: {
61 thinking: { supported: true },
62 effort: { supported: true },
63 structured_outputs: { supported: true },
64 },
65 }),
66 ).toEqual([
67 'reasoning',
68 'reasoning_effort',
69 'structured_outputs',
70 'response_format',
71 ])
72 expect(
73 anthropicCapabilities({ id: 'claude-x', capabilities: {} }),
74 ).toBeNull()
75 })
76})
77​
78describe('gemini models api', () => {
79 it('derives request features only from row fields', () => {
80 expect(
81 geminiCapabilities({ thinking: true, temperature: 1, topP: 0.95 }),
82 ).toEqual(['reasoning', 'temperature', 'top_p'])
83 expect(geminiCapabilities({})).toBeNull()
84 })
85})
86​
87describe('xai model docs', () => {
88 it('reads context windows and ignores the per-image table', () => {
89 const md = `
90| Model | Context | Input / 1M tokens | Cached input / 1M tokens | Output / 1M tokens |
91| --- | --- | --- | --- | --- |
92| grok-4.6 (< 200k prompt tokens) | 500k | $2.00 | $0.50 | $6.00 |
93| grok-4.6 (≥ 200k prompt tokens) | 500k | $4.00 | $1.00 | $12.00 |
94| grok-4.3 (< 200k prompt tokens) | 1M | $1.25 | $0.20 | $2.50 |
95​
96| Model | Cost |
97| --- | --- |
98| grok-imagine-image | $0.02 / image |
100 expect([...parseGrokContextWindows(md)]).toEqual([
101 ['grok-4.6', 500_000],
102 ['grok-4.3', 1_000_000],
103 ])
104 })
105})
106​
107describe('xai per-model docs', () => {
108 it('reads the Reasoning capability bullet', () => {
109 const page = (value: string) =>
110 `# Grok\n\n## Capabilities\n\n- **Function calling:** Yes\n- **Reasoning:** ${value}\n- **Reasoning efforts (supported):** \`low\`\n`
111 expect(grokReasons(page('Yes'))).toBe(true)
112 expect(grokReasons(page('No'))).toBe(false)
113 expect(grokReasons('# Grok\n\n## Capabilities\n')).toBe(false)
114 })
115})
116​
117describe('openai model docs', () => {
118 const page = `# GPT-5
119​
120Model ID: \`gpt-5\`
121​
122Reasoning.effort supports: minimal, low, medium, and high.
123​
124## Model details
125​
126- Default snapshot: \`gpt-5-2025-08-07\`
127- Input modalities: text, image
128- Output modalities: text
129- 400,000 context window
130- Maximum input tokens: 272,000
131- 128,000 max output tokens
132- Reasoning token support
133​
134## Supported features
135​
136- streaming
137- structured_outputs
138- function_calling
139​
140## Supported tools
141​
142- function_calling
143- web_search
144- hosted_shell
145- skills
146- computer_use
147​
148## Snapshots
149​
150- \`gpt-5-2025-08-07\`
151- \`gpt-5-2025-09-01\`
152​
153## Rate limits
155 it('parses details, features, snapshots', () => {
156 const parsed = parseModelPage(page)
157 expect(parsed?.ids).toEqual([
158 'gpt-5',
159 'gpt-5-2025-08-07',
160 'gpt-5-2025-09-01',
161 ])
162 expect(parsed?.pricedIds).toEqual(['gpt-5', 'gpt-5-2025-08-07'])
163 expect(parsed?.facts).toEqual({
164 contextWindow: 400_000,
165 maxOutput: 128_000,
166 modalities: { input: ['text', 'image'], output: ['text'] },
167 capabilities: [
168 'tools',
169 'reasoning',
170 'structured_outputs',
171 'response_format',
172 ],
173 reasoning: {
174 mode: 'effort',
175 mandatory: null,
176 efforts: ['minimal', 'low', 'medium', 'high'],
177 },
178 // Docs names map to Responses tool types; client-side ones drop.
179 serverTools: ['web_search', 'shell', 'computer'],
180 })
181 })
182​
183 it('leaves serverTools null when the page names no tool ids', () => {
184 const bare = page.replace(
185 /## Supported tools[\s\S]*?## Snapshots/,
186 '## Snapshots',
187 )
188 expect(parseModelPage(bare)?.facts.serverTools).toBeNull()
189 })
190​
191 it('reads every effort phrasing; none makes reasoning optional', () => {
192 expect(
193 parseReasoningEffort(
194 'Reasoning.effort supports: none (default), low, medium, and high.',
195 ),
196 ).toEqual({
197 mode: 'effort',
198 mandatory: false,
199 efforts: ['none', 'low', 'medium', 'high'],
200 })
201 expect(
202 parseReasoningEffort(
203 'GPT-5.2 Pro supports reasoning.effort: medium, high, xhigh.',
204 ),
205 ).toEqual({
206 mode: 'effort',
207 mandatory: null,
208 efforts: ['medium', 'high', 'xhigh'],
209 })
210 expect(
211 parseReasoningEffort(
212 'GPT-5 Pro defaults to (and only supports) `reasoning.effort: high`.',
213 ),
214 ).toEqual({ mode: 'effort', mandatory: null, efforts: ['high'] })
215 expect(parseReasoningEffort('No effort prose.')).toBeNull()
216 })
217​
218 it('resolves listed ids to index slugs, dated snapshots via the alias', () => {
219 const slugs = parseModelIndex(
220 '- [GPT-5](/api/docs/models/gpt-5.md): x\n- [Whisper](/api/docs/models/whisper-1.md): y',
221 )
222 expect(pageSlugFor('gpt-5-2025-08-07', slugs)).toBe('gpt-5')
223 expect(pageSlugFor('whisper-1', slugs)).toBe('whisper-1')
224 expect(pageSlugFor('gpt-5-search-api', slugs)).toBeNull()
225 // The models index dropped Sora after the Videos API shutdown. The
226 // pages still publish per-second rates, so the slug is fetched anyway.
227 expect(pageSlugFor('sora-2', slugs)).toBe('sora-2')
228 expect(pageSlugFor('sora-2-pro', slugs)).toBe('sora-2-pro')
229 expect(pageSlugFor('sora-2-2025-10-06', slugs)).toBe('sora-2')
230 expect(pageSlugFor('sora-2-pro-2025-10-06', slugs)).toBe('sora-2-pro')
231 // Dated TTS snapshots have no page of their own and are not the
232 // family's default snapshot, so they do not inherit tts-1's price.
233 expect(pageSlugFor('tts-1-1106', slugs)).toBeNull()
234 expect(pageSlugFor('tts-1-hd-1106', slugs)).toBeNull()
235 })
236})
237​
238describe('openai-compatible model rows', () => {
239 it('maps the extension fields groq/jina/fireworks/moonshot/mistral publish', () => {
240 expect(
241 openAiCompatModelFacts({
242 id: 'openai/gpt-oss-120b',
243 context_window: 131072,
244 max_completion_tokens: 65536,
245 input_modalities: ['text'],
246 output_modalities: ['text'],
247 supported_sampling_parameters: ['temperature', 'top_p', 'stop'],
248 supported_features: [
249 'tools',
250 'json_mode',
251 'structured_outputs',
252 'reasoning',
253 ],
254 }),
255 ).toEqual({
256 contextWindow: 131072,
257 maxOutput: 65536,
258 modalities: { input: ['text'], output: ['text'] },
259 capabilities: [
260 'tools',
261 'reasoning',
262 'temperature',
263 'top_p',
264 'structured_outputs',
265 'response_format',
266 ],
267 })
268 expect(
269 openAiCompatModelFacts({
270 id: 'kimi-k2.6',
271 context_length: 262144,
272 supports_reasoning: true,
273 }),
274 ).toEqual({ contextWindow: 262144, capabilities: ['reasoning'] })
275 expect(
276 openAiCompatModelFacts({
277 id: 'mistral-large-latest',
278 max_context_length: 262144,
279 capabilities: {
280 function_calling: true,
281 vision: true,
282 reasoning: false,
283 },
284 }),
285 ).toEqual({ contextWindow: 262144, capabilities: ['tools'] })
286 expect(openAiCompatModelFacts({ id: 'x', max_output_length: 0 })).toEqual(
287 {},
288 )
289 })
290})
291​
292describe('openai-compatible model rows (novita / cohere vocab)', () => {
293 it('normalises hyphenated features and cohere feature names', () => {
294 expect(
295 openAiCompatModelFacts({
296 id: 'zai-org/glm-5.3-flash',
297 context_size: 1_048_576,
298 max_output_tokens: 131_072,
299 input_modalities: ['text', 'image', 'video'],
300 output_modalities: ['text'],
301 features: ['function-calling', 'structured-outputs', 'reasoning'],
302 }),
303 ).toEqual({
304 contextWindow: 1_048_576,
305 maxOutput: 131_072,
306 modalities: { input: ['text', 'image', 'video'], output: ['text'] },
307 capabilities: [
308 'tools',
309 'reasoning',
310 'structured_outputs',
311 'response_format',
312 ],
313 })
314 expect(
315 openAiCompatModelFacts({
316 id: 'command-a-03-2025',
317 context_length: 288_000,
318 features: ['json_mode', 'json_schema', 'tools', 'tool_choice'],
319 }),
320 ).toEqual({
321 contextWindow: 288_000,
322 capabilities: [
323 'tools',
324 'tool_choice',
325 'structured_outputs',
326 'response_format',
327 ],
328 })
329 })
330})
331​
332describe('openai pricing tables', () => {
333 const pricing = (body: string) =>
334 `# Model\n\nModel ID: \`m\`\n\n## Pricing\n\n${body}\n## Endpoints\n`
335​
336 it('reads every token lever off the per-million tables', () => {
337 expect(
338 parseModelPricing(
339 pricing(`### Text tokens
340​
341| Metric | Price | Unit |
342| --- | ---: | --- |
343| Input | $1.25 | 1M tokens |
344| Cached input | $0.125 | 1M tokens |
345| Output | $10 | 1M tokens |
346​
347### Audio tokens
348​
349| Metric | Price | Unit |
350| --- | ---: | --- |
351| Input | $32 | 1M tokens |
352| Output | $64 | 1M tokens |
353`),
354 ),
355 ).toEqual({
356 rates: {
357 input_tokens: 1.25e-6,
358 cache_read_tokens: 0.125e-6,
359 output_tokens: 10e-6,
360 audio_tokens: 32e-6,
361 audio_output_tokens: 64e-6,
362 },
363 tiers: [],
364 })
365 })
366​
367 it('uses the first Text tokens table when the heading is repeated', () => {
368 // o3.md publishes standard rates, then the same heading again at half
369 // price for batch/flex, with no label on the second table.
370 expect(
371 parseModelPricing(
372 pricing(`### Text tokens
373​
374| Metric | Price | Unit |
375| --- | ---: | --- |
376| Input | $2 | 1M tokens |
377| Cached input | $0.5 | 1M tokens |
378| Output | $8 | 1M tokens |
379​
380### Text tokens
381​
382| Metric | Price | Unit |
383| --- | ---: | --- |
384| Input | $1 | 1M tokens |
385| Cached input | $0.25 | 1M tokens |
386| Output | $4 | 1M tokens |
387`),
388 ),
389 ).toEqual({
390 rates: {
391 input_tokens: 0.000002,
392 cache_read_tokens: 5e-7,
393 output_tokens: 0.000008,
394 },
395 tiers: [],
396 })
397 })
398​
399 it('prices the alias and default snapshot, not an older dated snapshot', () => {
400 const parsed = parseModelPage(`# GPT-4o
401​
402Model ID: \`gpt-4o\`
403​
404## Model details
405​
406- Default snapshot: \`gpt-4o-2024-08-06\`
407​
408## Pricing
409​
410### Text tokens
411​
412| Metric | Price | Unit |
413| --- | ---: | --- |
414| Input | $2.50 | 1M tokens |
415| Cached input | $1.25 | 1M tokens |
416| Output | $10 | 1M tokens |
417​
418## Snapshots
419​
420- \`gpt-4o-2024-08-06\`
421- \`gpt-4o-2024-11-20\`
422- \`gpt-4o-2024-05-13\`
423`)
424 expect(parsed?.pricedIds).toEqual(['gpt-4o', 'gpt-4o-2024-08-06'])
425 expect(parsed?.ids).toContain('gpt-4o-2024-05-13')
426 expect(parsed?.pricing?.rates).toEqual({
427 input_tokens: 2.5e-6,
428 cache_read_tokens: 1.25e-6,
429 output_tokens: 10e-6,
430 })
431 })
432​
433 it('reads an embeddings page', () => {
434 expect(
435 parseModelPricing(
436 pricing(`### Embeddings
437​
438| Metric | Price | Unit |
439| --- | ---: | --- |
440| Cost | $0.02 | 1M tokens |
441`),
442 ),
443 ).toEqual({ rates: { input_tokens: 0.02e-6 }, tiers: [] })
444 })
445​
446 it('treats the per-image table as a restatement of the token price', () => {
447 // OpenAI bills image models per token; the per-image table is the
448 // equivalent cost of one image at a size and quality.
449 expect(
450 parseModelPricing(
451 pricing(`### Image tokens
452​
453| Metric | Price | Unit |
454| --- | ---: | --- |
455| Input | $10 | 1M tokens |
456| Output | $40 | 1M tokens |
457​
458### Image generation
459​
460| Metric | Price | Unit |
461| --- | ---: | --- |
462| Quality | Low | image |
463| 1024x1024 | $0.011 | image |
464`),
465 ),
466 ).toEqual({
467 rates: { image_tokens: 10e-6, image_output_tokens: 40e-6 },
468 tiers: [],
469 })
470 })
471​
472 it('refuses a section priced in a unit it has no lever for', () => {
473 expect(
474 parseModelPricing(
475 pricing(`### Pricing
476​
477| Metric | Price | Unit |
478| --- | ---: | --- |
479| Cost | $0.10 | GB-hour |
480`),
481 ),
482 ).toBeNull()
483 })
484​
485 it('reads the long-prompt re-quote and cache-write multiplier', () => {
486 const page = pricing(`### Text tokens
487​
488| Metric | Price | Unit |
489| --- | ---: | --- |
490| Input | $10 | 1M tokens |
491| Cached input | $1 | 1M tokens |
492| Output | $50 | 1M tokens |
493​
494- Prompts with more than 272K input tokens are priced at 2x input and cache rates and 1.5x output for the full request.
495- Cache writes are billed at 1.25x the uncached input token rate.
496- Batch and Flex are priced at 50% of Standard rates.
497`)
498 expect(parseModelPricing(page)).toEqual({
499 rates: {
500 input_tokens: 10e-6,
501 cache_read_tokens: 1e-6,
502 cache_write_tokens: 12.5e-6,
503 output_tokens: 50e-6,
504 },
505 tiers: [
506 {
507 minPromptTokens: 272_000,
508 rates: {
509 input_tokens: 20e-6,
510 cache_read_tokens: 2e-6,
511 cache_write_tokens: 25e-6,
512 output_tokens: (50 / 1e6) * 1.5,
513 },
514 },
515 ],
516 })
517 })
518​
519 it('stamps a promo end so the card is re-read after it', () => {
520 const page = pricing(`### Text tokens
521​
522| Metric | Price | Unit |
523| --- | ---: | --- |
524| Input | $4 | 1M tokens |
525| Output | $20 | 1M tokens |
526​
527- GPT-5.6 Sol costs $4 per million input tokens and $20 per million output tokens, a 20% reduction in input pricing. GPT-5.6 Sol’s promotional pricing is available at least through November 21, 2026.
528`)
529 expect(parseModelPricing(page)?.expiresAt).toBe('2026-11-22T00:00:00.000Z')
530 })
531​
532 it('prices a per-minute model by the duration the caller measures', () => {
533 expect(
534 parseModelPricing(
535 pricing(`### Transcription audio duration
536​
537| Metric | Price | Unit |
538| --- | ---: | --- |
539| Price | $0.0045 | minute |
540`),
541 ),
542 ).toEqual({
543 rates: {},
544 tiers: [],
545 unit: {
546 quantity: { param: 'audio_seconds', bound: 'usage' },
547 rates: 0.0045 / 60,
548 },
549 })
550 })
551​
552 it('prices sora-2 and sora-2-pro from their own video tables', () => {
553 expect(
554 parseModelPricing(
555 pricing(`### Video generation
556​
557| Metric | Price | Unit |
558| --- | ---: | --- |
559| Portrait: 720x1280
560Landscape: 1280x720 | $0.1 | second |
561`),
562 )?.unit,
563 ).toEqual({
564 quantity: { param: 'seconds', bound: 'request' },
565 keys: [{ param: 'size', values: ['720x1280', '1280x720'] }],
566 rates: { '720x1280': 0.1, '1280x720': 0.1 },
567 })
568 expect(
569 parseModelPricing(
570 pricing(`### Video generation
571​
572| Metric | Price | Unit |
573| --- | ---: | --- |
574| Portrait: 720x1280
575Landscape: 1280x720 | $0.3 | second |
576| Portrait: 1024x1792
577Landscape: 1792x1024 | $0.5 | second |
578| Portrait: 1080x1920
579Landscape: 1920x1080 | $0.7 | second |
580`),
581 )?.unit?.rates,
582 ).toEqual({
583 '720x1280': 0.3,
584 '1280x720': 0.3,
585 '1024x1792': 0.5,
586 '1792x1024': 0.5,
587 '1080x1920': 0.7,
588 '1920x1080': 0.7,
589 })
590 })
591​
592 it('leaves image-2, moderation, and dated TTS snapshots unpriced', () => {
593 const image = parseModelPage(`# GPT-Image-2
594​
595Model ID: \`gpt-image-2\`
596​
597GPT Image 2 points at the [pricing page](/api/docs/pricing#image-generation) but this page lists no amount.
598​
599## Model details
600​
601- Default snapshot: \`gpt-image-2-2026-04-21\`
602​
603## Snapshots
604​
605- \`gpt-image-2-2026-04-21\`
606`)
607 expect(image?.pricing).toBeNull()
608 expect(image?.pricedIds).toEqual(['gpt-image-2', 'gpt-image-2-2026-04-21'])
609​
610 const moderation = parseModelPage(`# omni-moderation
611​
612Model ID: \`omni-moderation-latest\`
613​
614Moderation models are free models designed to detect harmful content.
615​
616## Model details
617​
618- Default snapshot: \`omni-moderation-2024-09-26\`
619​
620## Snapshots
621​
622- \`omni-moderation-2024-09-26\`
623`)
624 expect(moderation?.pricing).toBeNull()
625​
626 const tts = parseModelPage(`# TTS-1
627​
628Model ID: \`tts-1\`
629​
630## Model details
631​
632- Default snapshot: \`tts-1\`
633​
634## Pricing
635​
636### Pricing
637​
638| Metric | Price | Unit |
639| --- | ---: | --- |
640| Use case | Speech generation | 1M tokens |
641| Cost | $15 | 1M characters |
642​
643## Snapshots
644​
645- \`tts-1\`
646`)
647 expect(tts?.pricedIds).toEqual(['tts-1'])
648 expect(tts?.ids).not.toContain('tts-1-1106')
649 expect(tts?.pricing?.unit?.rates).toBe(15 / 1e6)
650 })
651​
652 it('prices speech by character and video by size and second', () => {
653 expect(
654 parseModelPricing(
655 pricing(`### Pricing
656​
657| Metric | Price | Unit |
658| --- | ---: | --- |
659| Use case | Speech generation | 1M tokens |
660| Cost | $15 | 1M characters |
661`),
662 )?.unit,
663 ).toEqual({
664 quantity: { param: 'characters', bound: 'usage' },
665 rates: 15 / 1e6,
666 })
667 // A video row names both orientations of one size in its metric cell,
668 // and the cell's newline splits the row across two lines.
669 expect(
670 parseModelPricing(
671 pricing(`### Video generation
672​
673| Metric | Price | Unit |
674| --- | ---: | --- |
675| Portrait: 720x1280
676Landscape: 1280x720 | $0.3 | second |
677| Portrait: 1080x1920
678Landscape: 1920x1080 | $0.7 | second |
679`),
680 )?.unit,
681 ).toEqual({
682 quantity: { param: 'seconds', bound: 'request' },
683 keys: [
684 {
685 param: 'size',
686 values: ['720x1280', '1280x720', '1080x1920', '1920x1080'],
687 },
688 ],
689 rates: {
690 '720x1280': 0.3,
691 '1280x720': 0.3,
692 '1080x1920': 0.7,
693 '1920x1080': 0.7,
694 },
695 })
696 })
697​
698 it('refuses a page that mixes a token table with a per-unit one', () => {
699 expect(
700 parseModelPricing(
701 pricing(`### Text tokens
702​
703| Metric | Price | Unit |
704| --- | ---: | --- |
705| Input | $5 | 1M tokens |
706​
707### Live session duration
708​
709| Metric | Price | Unit |
710| --- | ---: | --- |
711| Per minute | $0.05 | minute |
712`),
713 ),
714 ).toBeNull()
715 })
716​
717 it('accepts a cached-input bullet that restates the table', () => {
718 const page = pricing(`### Text tokens
719​
720| Metric | Price | Unit |
721| --- | ---: | --- |
722| Input | $0.1 | 1M tokens |
723| Cached input | $0.01 | 1M tokens |
724| Cache writes | $0.125 | 1M tokens |
725| Output | $0.5 | 1M tokens |
726​
727- Cached input tokens are priced at 10% of the uncached input token rate.
728- Cache writes are billed at 1.25x the uncached input token rate.
729- Regional processing adds a 10% premium where available.
730`)
731 expect(parseModelPricing(page)?.rates).toEqual({
732 input_tokens: 0.1 / 1e6,
733 cache_read_tokens: 0.01 / 1e6,
734 cache_write_tokens: 0.125 / 1e6,
735 output_tokens: 0.5 / 1e6,
736 })
737 })
738​
739 it('refuses a cached-input bullet that disagrees with the table', () => {
740 const page = pricing(`### Text tokens
741​
742| Metric | Price | Unit |
743| --- | ---: | --- |
744| Input | $1 | 1M tokens |
745| Cached input | $0.5 | 1M tokens |
746| Output | $2 | 1M tokens |
747​
748- Cached input tokens are priced at 10% of the uncached input token rate.
749`)
750 expect(parseModelPricing(page)).toBeNull()
751 })
752​
753 it('refuses an unrecognised bullet that quotes a surcharge', () => {
754 const page = pricing(`### Text tokens
755​
756| Metric | Price | Unit |
757| --- | ---: | --- |
758| Input | $10 | 1M tokens |
759| Output | $50 | 1M tokens |
760​
761- Requests using the widget tool are charged a 3x multiplier.
762`)
763 expect(parseModelPricing(page)).toBeNull()
764 })
765​
766 it('refuses an unpriced row and a page with no pricing', () => {
767 expect(
768 parseModelPricing(
769 pricing(`### Text tokens
770​
771| Metric | Price | Unit |
772| --- | ---: | --- |
773| Input | Free | 1M tokens |
774`),
775 ),
776 ).toBeNull()
777 expect(parseModelPricing('# Model\n\nModel ID: `m`\n')).toBeNull()
778 })
779​
780 it('prices gpt-5-search-api from the specialized table and not a dated twin', () => {
781 const page = `Specialized models
782​
783Prices per 1M tokens.
784​
785Standard
786​
787### Grouped Pricing Table data
788​
789| Category | Model | Input | Cached input | Output |
790| --- | --- | --- | --- | --- |
791| Search | gpt-5-search-api | $1.25 | $0.125 | $10.00 |
792| Embedding | text-embedding-3-small | $0.02 | - | - |
793| Moderation | omni-moderation-latest | Free | - | - |
794​
795Fast
796​
797### Grouped Pricing Table data
798​
799| Category | Model | Input | Cached input | Output |
800| --- | --- | --- | --- | --- |
801| Search | gpt-5-search-api | $9.99 | $9.99 | $9.99 |
803 const rates = parseOpenAiSearchPricing(page)
804 expect(rates.get('gpt-5-search-api')).toEqual({
805 input_tokens: 1.25 / 1e6,
806 cache_read_tokens: 0.125 / 1e6,
807 output_tokens: 10 / 1e6,
808 })
809 expect(rates.has('text-embedding-3-small')).toBe(false)
810 expect(rates.has('omni-moderation-latest')).toBe(false)
811 expect(rates.has('gpt-5-search-api-2025-10-14')).toBe(false)
812 expect(rates.has('gpt-3.5-turbo-16k')).toBe(false)
813 })
814})
815​
816describe('anthropic pricing page', () => {
817 it('reads HTML-footnoted cache rates from the upstream table', () => {
818 const rows = parseAnthropicPricing(ANTHROPIC_PRICING_PAGE)
819 expect(rows.size).toBe(18)
820 expect(rows.get('claude opus 5.5')?.cache_read_tokens).toBeCloseTo(
821 0.2e-6,
822 15,
823 )
824 expect(rows.get('claude fable 5.1')?.cache_read_tokens).toBe(0.25e-6)
825 expect(rows.get('claude sonnet 5')?.input_tokens).toBe(2e-6)
826 expect(rows.get('claude sonnet 5')?.output_tokens).toBe(10e-6)
827 for (const [name, rates] of rows) {
828 if ('cache_write_tokens' in rates || 'cache_write_1h_tokens' in rates) {
829 expect(
830 rates.cache_read_tokens,
831 `${name} must price cache reads`,
832 ).toBeGreaterThan(0)
833 }
834 }
835 })
836​
837 const page = `# Pricing
838​
839## Model pricing
840​
841| Model | Base input tokens | 5m cache writes | 1h cache writes | Cache hits and refreshes | Output tokens |
842| --- | --- | --- | --- | --- | --- |
843| Claude Fable 5.1 | $10 / MTok | $12.50 / MTok | $20 / MTok | $0.25 / MTok1 | $50 / MTok |
844| Claude Opus 4 ([retired](https://example.com/deprecations)) | $15 / MTok | $18.75 / MTok | $30 / MTok | $1.50 / MTok | $75 / MTok |
845​
846## Batch pricing
847​
848| Model | Batch input | Batch output |
849| --- | --- | --- |
850| Claude Fable 5.1 | $5 / MTok | $25 / MTok |
852​
853 it('keys rows by display name and reads every lever column', () => {
854 const rows = parseAnthropicPricing(page)
855 expect(rows.get('claude fable 5.1')).toEqual({
856 input_tokens: 10e-6,
857 cache_write_tokens: 12.5e-6,
858 cache_write_1h_tokens: 20e-6,
859 cache_read_tokens: 0.25e-6,
860 output_tokens: 50e-6,
861 })
862 // The name cell's retirement link is not part of the key.
863 expect(rows.get('claude opus 4')?.input_tokens).toBe(15e-6)
864 // Batch rates live in another section and are not levers.
865 expect(rows.size).toBe(2)
866 })
867​
868 it('parses nothing when the section is gone', () => {
869 expect(parseAnthropicPricing('# Pricing\n\n## Something else\n').size).toBe(
870 0,
871 )
872 })
873})
874​
875describe('grok model prices', () => {
876 const model = {
877 id: 'grok-4.20-0309-reasoning',
878 prompt_text_token_price: 12_500,
879 cached_prompt_text_token_price: 2_000,
880 completion_text_token_price: 25_000,
881 prompt_text_token_price_long_context: 25_000,
882 cached_prompt_text_token_price_long_context: 4_000,
883 completion_text_token_price_long_context: 50_000,
884 long_context_threshold: 200_000,
885 }
886​
887 it('reads xAI’s 1e-10 USD units as per-token rates', async () => {
888 const card = await grokRateCard(model)
889 if (!card) throw new Error('did not compile')
890 expect(
891 price(card, {}, { input_tokens: 1e5, output_tokens: 0 }),
892 ).toBeCloseTo(0.125, 9)
893 expect(
894 price(card, {}, { input_tokens: 0, output_tokens: 1e5 }),
895 ).toBeCloseTo(0.25, 9)
896 })
897​
898 it('bills the long-context rate at the threshold, not above it', async () => {
899 const card = await grokRateCard(model)
900 if (!card) throw new Error('did not compile')
901 const perMillion = (tokens: number) =>
902 (price(card, {}, { input_tokens: tokens, output_tokens: 0 }) / tokens) *
903 1e6
904 expect(perMillion(199_999)).toBeCloseTo(1.25, 6)
905 expect(perMillion(200_000)).toBeCloseTo(2.5, 6)
906 })
907​
908 it('has no card for a model xAI does not price', async () => {
909 expect(await grokRateCard({ id: 'grok-imagine-video' })).toBeNull()
910 })
911​
912 it('prices images per image, by the (quality, resolution) matrix when there is one', async () => {
913 const card = await grokImageCard({
914 id: 'grok-imagine-image',
915 image_price: 200_000_000,
916 })
917 if (!card) throw new Error('did not compile')
918 expect(price(card, {}, {})).toBeCloseTo(0.02, 9)
919 expect(price(card, { n: 4 }, {})).toBeCloseTo(0.08, 9)
920 // Live 2026-10-04: grok-imagine-image-2.0 prices by quality and
921 // resolution. `quality` is a request field (the guide and xai-sdk-ts;
922 // the OpenAPI document omits it) and defaults to `auto`, which serves
923 // `low` for generation. The pricing page's $0.04 is the low/1k cell.
924 const matrix = await grokImageCard({
925 id: 'grok-imagine-image-2.0',
926 image_price: 600_000_000,
927 pricing: [
928 { quality: 'low', resolution: '1k', price_per_image: 4e8 },
929 { quality: 'low', resolution: '2k', price_per_image: 6e8 },
930 { quality: 'medium', resolution: '1k', price_per_image: 6e8 },
931 { quality: 'medium', resolution: '2k', price_per_image: 8e8 },
932 ],
933 })
934 if (!matrix) throw new Error('did not compile')
935 expect(price(matrix, {}, {})).toBeCloseTo(0.04, 9)
936 expect(price(matrix, { quality: 'auto' }, {})).toBeCloseTo(0.04, 9)
937 expect(
938 price(matrix, { quality: 'medium', resolution: '2k' }, {}),
939 ).toBeCloseTo(0.08, 9)
940 expect(
941 price(matrix, { quality: 'low', resolution: '2k', n: 2 }, {}),
942 ).toBeCloseTo(0.12, 9)
943 expect(matrix.inputs.quality).toMatchObject({
944 bound: 'request',
945 default: 'auto',
946 })
947 // A dimension the request cannot state has no card, flat price or not.
948 expect(
949 await grokImageCard({
950 id: 'grok-imagine-image',
951 image_price: 200_000_000,
952 pricing: [{ tier: 'pro', price_per_image: 7e8 }],
953 }),
954 ).toBeNull()
955 })
956​
957 it('adds the documented quality field the OpenAPI document omits', () => {
958 const spec = withGrokImageQuality({
959 components: {
960 schemas: {
961 GenerateImageRequest: { properties: { prompt: { type: 'string' } } },
962 EditImageRequest: { properties: { prompt: { type: 'string' } } },
963 GenerateVideoRequest: { properties: { prompt: { type: 'string' } } },
964 },
965 },
966 })
967 const schemas = spec.components?.schemas as Record<
968 string,
969 { properties: Record<string, unknown> }
970 >
971 expect(schemas.GenerateImageRequest?.properties.quality).toMatchObject({
972 enum: ['low', 'medium', 'auto'],
973 })
974 expect(schemas.EditImageRequest?.properties.quality).toBeDefined()
975 expect(schemas.GenerateVideoRequest?.properties.quality).toBeUndefined()
976 })
977​
978 it('reads a stated output cap and ignores "no limit" and price rows', () => {
979 const page = `# Grok 3
980​
981## At a glance
982​
983- **Context window:** 131,072 tokens
984- **Output limit:** 8,192 tokens
986 expect(parseGrokMaxOutput(page)).toBe(8_192)
987 expect(
988 parseGrokMaxOutput(
989 '| Property | Value |\n| --- | --- |\n| Output limit | No text output limit |\n',
990 ),
991 ).toBeNull()
992 expect(
993 parseGrokMaxOutput(
994 '| Type | Price |\n| --- | --- |\n| Output | $6.00 |\n',
995 ),
996 ).toBeNull()
997 })
998​
999 it('prices video per second off the docs table', async () => {
1000 const rates = parseGrokVideoPrices(`### Imagine Pricing
1001​
1002| Model | Cost |
1003| --- | --- |
1004| grok-imagine-image | $0.02 / image |
1005| grok-imagine-video | $0.050 / sec |
1006| grok-imagine-video-1.5 | $0.080 / sec |
1008 expect([...rates]).toEqual([
1009 ['grok-imagine-video', 0.05],
1010 ['grok-imagine-video-1.5', 0.08],
1011 ])
1012 const card = await grokVideoCard(rates.get('grok-imagine-video'))
1013 if (!card) throw new Error('did not compile')
1014 expect(price(card, { duration: 6 }, {})).toBeCloseTo(0.3, 9)
1015 expect(await grokVideoCard(undefined)).toBeNull()
1016 })
1018​
1019describe('gemini pricing page', () => {
1020 const section = (
1021 id: string,
1022 rows: string,
1023 extraIds: Array<string> = [],
1024 ) => `<div class="models-section">
1025 <div class="heading-group"><h2 id="${id}">Name</h2>
1026 <em>${[id, ...extraIds]
1027 .map(
1028 (each) =>
1029 `<a href="/gemini-api/docs/models/${each}"><code translate="no" dir="ltr">${each}</code></a>`,
1031 .join('')}</em></div>
1032 </div>
1033 <div><devsite-selector><section><h3 id="standard" data-text="Standard">Standard</h3><table class="pricing-table">
1034 <thead><tr><th></th><th scope="col">Free Tier</th><th scope="col">Paid Tier, per 1M tokens in USD</th></tr></thead>
1035 <tbody>${rows}</tbody></table></section>
1036 <section><h3 id="batch" data-text="Batch">Batch</h3><table class="pricing-table"><tbody>
1037 <tr><td>Input price</td><td>Not available</td><td>$0.15</td></tr>
1038 </tbody></table></section></devsite-selector></div>`
1039​
1040 const NOW = Date.UTC(2026, 8, 16)
1041​
1042 it('reads text and audio rates off the Standard table', () => {
1043 const rows = parseGeminiPricing(
1044 section(
1045 'gemini-2.5-flash',
1046 `<tr><td>Input price</td><td>Free of charge</td><td>$0.30 (text / image / video)<br>$1.00 (audio)</td></tr>
1047 <tr><td>Output price (including thinking tokens)</td><td>Free of charge</td><td>$2.50</td></tr>
1048 <tr><td>Context caching price</td><td>Not available</td><td>$0.03 (text / image / video)<br>$0.1 (audio)<br>$1.00 / 1,000,000 tokens per hour (storage price)</td></tr>
1049 <tr><td>Grounding with Google Search</td><td>Free</td><td>1,500 RPD (free), then $35 / 1,000 grounded prompts</td></tr>`,
1050 ),
1051 NOW,
1053 expect(rows.get('gemini-2.5-flash')?.base).toEqual({
1054 input_tokens: 0.3e-6,
1055 audio_tokens: 1e-6,
1056 output_tokens: 2.5e-6,
1057 cache_read_tokens: 0.03e-6,
1058 audio_cache_tokens: 0.1 / 1e6,
1059 })
1060 // Batch is a separate tab, and cache storage is a per-hour rate.
1061 expect(rows.get('gemini-2.5-flash')?.tiers).toEqual([])
1062 })
1063​
1064 it('copies one Standard table onto every id the heading names', () => {
1065 const rows = parseGeminiPricing(
1066 section(
1067 'gemini-3.1-pro-preview',
1068 `<tr><td>Input price</td><td>Not available</td><td>$2.00</td></tr>
1069 <tr><td>Output price (including thinking tokens)</td><td>Not available</td><td>$12.00</td></tr>`,
1070 ['gemini-3.1-pro-preview-customtools'],
1071 ),
1072 NOW,
1074 expect(rows.get('gemini-3.1-pro-preview')?.base).toEqual({
1075 input_tokens: 2e-6,
1076 output_tokens: 12e-6,
1077 })
1078 expect(rows.get('gemini-3.1-pro-preview-customtools')?.base).toEqual(
1079 rows.get('gemini-3.1-pro-preview')?.base,
1081 })
1082​
1083 it('does not price models the heading does not name', () => {
1084 const rows = parseGeminiPricing(
1085 section(
1086 'gemini-2.5-flash',
1087 `<tr><td>Input price</td><td>Free of charge</td><td>$0.30</td></tr>
1088 <tr><td>Output price (including thinking tokens)</td><td>Free of charge</td><td>$2.50</td></tr>`,
1089 ),
1090 NOW,
1092 expect(rows.has('gemini-2.5-flash')).toBe(true)
1093 expect(rows.has('aqa')).toBe(false)
1094 expect(rows.has('antigravity-preview-09-2026')).toBe(false)
1095 expect(rows.has('gemini-flash-latest')).toBe(false)
1096 })
1097​
1098 it('compiles the long-prompt re-quote as a tier', () => {
1099 const rows = parseGeminiPricing(
1100 section(
1101 'gemini-2.5-pro',
1102 `<tr><td>Input price</td><td>Free of charge</td><td>$1.25, prompts <= 200k tokens<br>$2.50, prompts > 200k tokens</td></tr>
1103 <tr><td>Output price (including thinking tokens)</td><td>Free of charge</td><td>$10.00, prompts <= 200k<br>$15.00, prompts > 200k</td></tr>`,
1104 ),
1105 NOW,
1107 expect(rows.get('gemini-2.5-pro')?.base).toEqual({
1108 input_tokens: 1.25e-6,
1109 output_tokens: 10e-6,
1110 })
1111 expect(rows.get('gemini-2.5-pro')?.tiers).toEqual([
1113 minPromptTokens: 200_000,
1114 rates: { input_tokens: 2.5e-6, output_tokens: 15e-6 },
1115 },
1116 ])
1117 })
1118​
1119 it('takes the dated price in effect and stamps its expiry', () => {
1120 const page = section(
1121 'gemini-3.8-flash',
1122 `<tr><td>Input price</td><td>Not available</td><td>$0.75 through December 31, 2026.<br>$1.50 starting January 1, 2027.</td></tr>
1123 <tr><td>Output price (including thinking tokens)</td><td>Not available</td><td>$3.75 through December 31, 2026.<br>$7.50 starting January 1, 2027.</td></tr>`,
1125 expect(parseGeminiPricing(page, NOW).get('gemini-3.8-flash')).toEqual({
1126 base: { input_tokens: 0.75e-6, output_tokens: 3.75e-6 },
1127 tiers: [],
1128 expiresAt: '2027-01-01T00:00:00.000Z',
1129 })
1130 expect(
1131 parseGeminiPricing(page, Date.UTC(2027, 5, 1)).get('gemini-3.8-flash'),
1132 ).toEqual({
1133 base: { input_tokens: 1.5e-6, output_tokens: 7.5e-6 },
1134 tiers: [],
1135 })
1136 })
1137​
1138 it('gives a separately priced modality its own lever', () => {
1139 // Gemini sums text, image and video into one prompt-token count, so a
1140 // rate covering them all is the input lever; audio is priced apart.
1141 const rows = parseGeminiPricing(
1142 section(
1143 'gemini-3-pro-image',
1144 `<tr><td>Input price</td><td>Not available</td><td>$2.00 (text/image),<br>equivalent to $0.0011 per image</td></tr>
1145 <tr><td>Output price</td><td>Not available</td><td>$12.00 (text and thinking)<br>$120.00 (images)<br>Equivalent to $0.134 per 1K/2K image<br>and $0.24 per 4K image</td></tr>`,
1146 ),
1147 NOW,
1149 // The per-image lines restate the token rate; they are not extra cost.
1150 expect(rows.get('gemini-3-pro-image')?.base).toEqual({
1151 input_tokens: 2e-6,
1152 output_tokens: 12e-6,
1153 image_output_tokens: 120e-6,
1154 })
1155 })
1156​
1157 it('reads a per-modality row and an audio-only rate', () => {
1158 const rows = parseGeminiPricing(
1159 section(
1160 'gemini-embedding-2',
1161 `<tr><td>Text input price</td><td>Not available</td><td>$0.20</td></tr>
1162 <tr><td>Image input price</td><td>Not available</td><td>$0.45 ($0.00012 per image)</td></tr>
1163 <tr><td>Audio input price</td><td>Not available</td><td>$6.50 ($0.00016 per second)</td></tr>`,
1164 ),
1165 NOW,
1167 expect(rows.get('gemini-embedding-2')?.base).toEqual({
1168 input_tokens: 0.2 / 1e6,
1169 image_tokens: 0.45 / 1e6,
1170 audio_tokens: 6.5 / 1e6,
1171 })
1172 })
1173​
1174 it('cards a per-second section, one row per model id', () => {
1175 const page = `<div class="models-section">
1176 <div class="heading-group"><h2 id="veo-3.1">Veo 3.1</h2>
1177 <em><a href="/a"><code translate="no" dir="ltr">veo-3.1-generate-preview</code></a>,
1178 <a href="/b"><code translate="no" dir="ltr">veo-3.1-fast-generate-preview</code></a>,
1179 <a href="/c"><code translate="no" dir="ltr">veo-3.1-lite-generate-preview</code></a></em></div>
1180 </div>
1181 <table class="pricing-table"><thead><tr><th></th><th scope="col">Free Tier</th>
1182 <th scope="col">Paid Tier, per second in USD</th></tr></thead><tbody>
1183 <tr><td>Veo 3.1 Standard video with audio price (default)</td><td>Not available</td><td>$0.40 (720p and 1080p)<br>$0.60 (4k)</td></tr>
1184 <tr><td>Veo 3.1 Fast video with audio price (default)</td><td>Not available</td><td>$0.10 (720p)<br>$0.30 (4k)</td></tr>
1185 <tr><td>Veo 3.1 Lite video with audio price (default)</td><td>Not available</td><td>$0.05 (720p)<br>(4k output not supported)</td></tr>
1186 <tr><td>Used to improve our products</td><td>Yes</td><td>No</td></tr>
1187 </tbody></table>`
1188 const rows = parseGeminiPricing(page, Date.UTC(2026, 8, 16))
1189 expect(rows.get('veo-3.1-generate-preview')?.unit).toEqual({
1190 // Duration and size sit under the request's untyped `parameters`.
1191 quantity: { param: 'video_seconds', bound: 'usage' },
1192 keys: [
1194 param: 'resolution',
1195 bound: 'usage',
1196 values: ['720p', '1080p', '4k'],
1197 },
1198 ],
1199 rates: { '720p': 0.4, '1080p': 0.4, '4k': 0.6 },
1200 })
1201 expect(rows.get('veo-3.1-fast-generate-preview')?.unit?.rates).toEqual({
1202 '720p': 0.1,
1203 '4k': 0.3,
1204 })
1205 // A size the model cannot output is not a rate.
1206 expect(rows.get('veo-3.1-lite-generate-preview')?.unit?.rates).toEqual({
1207 '720p': 0.05,
1208 })
1209 })
1210​
1211 it('cards a per-request section flat', () => {
1212 const page = `<div class="models-section">
1213 <div class="heading-group"><h2 id="lyria">Lyria</h2>
1214 <em><a href="/a"><code translate="no" dir="ltr">lyria-3-clip-preview</code></a>,
1215 <a href="/b"><code translate="no" dir="ltr">lyria-3-pro-preview</code></a></em></div>
1216 </div>
1217 <table class="pricing-table"><thead><tr><th></th><th scope="col">Free Tier</th>
1218 <th scope="col">Paid Tier, per request in USD</th></tr></thead><tbody>
1219 <tr><td>Lyria 3 Clip Preview (30s)</td><td>Not available</td><td>$0.04 per song</td></tr>
1220 <tr><td>Lyria 3 Pro Preview (Full Song)</td><td>Not available</td><td>$0.08 per song</td></tr>
1221 </tbody></table>`
1222 const rows = parseGeminiPricing(page, Date.UTC(2026, 8, 16))
1223 expect(rows.get('lyria-3-clip-preview')?.unit).toEqual({ rates: 0.04 })
1224 expect(rows.get('lyria-3-pro-preview')?.unit).toEqual({ rates: 0.08 })
1225 })
1226​
1227 it('refuses a model whose bill is not only tokens', () => {
1228 // A row priced per image (not a restatement of a token rate), a
1229 // modality the row has no lever for, and a priced row with no lever.
1230 const perImage = `<tr><td>Input price</td><td>Not available</td><td>$0.30 (text / image)</td></tr>
1231 <tr><td>Output price</td><td>Not available</td><td>$0.039 per image</td></tr>`
1232 const perSong = `<tr><td>Lyria 3.5 (Full Song)</td><td>Not available</td><td>$0.08 per song</td></tr>`
1233 const unknownModality = `<tr><td>Input price</td><td>Not available</td><td>$1.00 (hologram)</td></tr>`
1234 for (const rows of [perImage, perSong, unknownModality]) {
1235 expect(parseGeminiPricing(section('m', rows), NOW).size).toBe(0)
1237 })