Open History to see the last commit
1import {
2 OPENAI_REALTIME_EFFORT_URL,
3 openaiRealtimeEfforts,
4 openaiRealtimeSelects,
5} from './openai-realtime-efforts.ts'
6/**
7 * OpenAI model facts from OpenAI's own docs. `GET /v1/models` is `id` +
8 * `created` only; developers.openai.com serves every model page as
9 * markdown (`/api/docs/models/{slug}.md`) with a fixed "Model details"
10 * bullet list, a "Supported features" list, and the page's snapshot ids. The index (`/api/docs/models/all.md`) is the
11 * slug list: `/api/docs/models.md` lists only current models since
12 * 2026-11-03 (#570), and older listed ids lost their pages (and prices). Only pages the listed ids resolve to are fetched (~65 of the
13 * ~130 listed ids share a page), bounded-concurrency, memoised six hours.
14 */
15import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
16import type {
17 RateCard,
18 TokenRateTier,
19 UnitCardSpec,
20} from '@modelschemas/rate-card'
21
22import { serverToolsSilent, tagDocsFacts } from './fact-sources.ts'
23import {
24 NO_FACTS,
25 assertParsed,
26 docsRun,
27 mapConcurrent,
28 markdownSection,
29 markdownTableRows,
30 parseDay,
31 tokenCount,
32 tryDocs,
33 unavailable,
34 undatedId,
35} from './model-facts.ts'
36import type { DocsRun, ModelFacts } from './model-facts.ts'
37import {
38 OPENAI_GPT51_GUIDE_URL,
39 OPENAI_GPT52_GUIDE_URL,
40 OPENAI_GPT5_GUIDE_URL,
41 loadGuide,
42 parseGpt51NoneGuide,
43 parseGpt52SamplingGuide,
44 parseGpt5FamilyGuide,
45} from './openai-gpt5-guides.ts'
46import { fetchText, sha256Text } from './types.ts'
47import type {
48 FactSource,
49 ModelFactSources,
50 ModelInfo,
51 ModelReasoning,
52} from './types.ts'
53import type { Fetcher } from './us-egress.ts'
54
55export const OPENAI_MODELS_INDEX_URL =
56 'https://developers.openai.com/api/docs/models/all.md'
57export const OPENAI_PRICING_URL =
58 'https://developers.openai.com/api/docs/pricing.md'
59export const OPENAI_MODEL_PAGE = (slug: string) =>
60 `https://developers.openai.com/api/docs/models/${slug}.md`
61
62/** Page slugs linked from the models index. */
63export function parseModelIndex(markdown: string): Set<string> {
64 return new Set(
65 [
66 ...markdown.matchAll(/\]\(\/api\/docs\/models\/([^)\s]+?)\.md\)/g),
67 ].flatMap((m) => (m[1] ? [m[1]] : [])),
68 )
69}
70
71export interface OpenAiModelPage {
72 /** Every id the page speaks for: `Model ID`, default snapshot, snapshots. */
73 ids: Array<string>
74 /**
75 * Ids the page's price belongs to: the model id and its default snapshot.
76 * An older dated snapshot keeps the page's other facts but not this price.
77 */
78 pricedIds: Array<string>
79 facts: ModelFacts
80 /** Token rates and tiers, or null when the page prices otherwise. */
81 pricing: DocsPricing | null
82 /**
83 * The Endpoints table marks Responses, every Realtime route and Live Not
84 * supported, so the page's empty tool list is the whole statement (#707).
85 */
86 toolsSilent?: true
87}
88
89/** Endpoint name → Supported, from the page's Endpoints table. */
90function parseEndpoints(markdown: string): Map<string, boolean> {
91 const out = new Map<string, boolean>()
92 for (const row of markdownTableRows(markdownSection(markdown, 'Endpoints'))) {
93 const [name, , support] = row.map((cell) => cell.trim())
94 if (!name || !support || name === 'Endpoint') continue
95 if (support === 'Supported') out.set(name, true)
96 else if (support === 'Not supported') out.set(name, false)
97 }
98 return out
99}
100
101/**
102 * Pricing subsection → the lever each `Metric` row prices. Every other
103 * subsection (image/video generation, audio duration, a per-call tool fee)
104 * refuses the whole model: a card quoting only its token rows would
105 * understate the bill. Unknown means null, never a partial card.
106 */
107const PRICING_LEVERS: Record<string, Record<string, string>> = {
108 'Text tokens': {
109 Input: 'input_tokens',
110 'Cached input': 'cache_read_tokens',
111 'Cache writes': 'cache_write_tokens',
112 Output: 'output_tokens',
113 },
114 'Audio tokens': {
115 Input: 'audio_tokens',
116 'Cached input': 'audio_cache_tokens',
117 Output: 'audio_output_tokens',
118 },
119 'Image tokens': {
120 Input: 'image_tokens',
121 'Cached input': 'image_cache_tokens',
122 Output: 'image_output_tokens',
123 },
124 Embeddings: { Cost: 'input_tokens' },
125}
126
127/**
128 * Sections priced per unit rather than per token. `Pricing` is the legacy
129 * tts/whisper table, whose `Cost` row carries the unit.
130 */
131const UNIT_SECTIONS = new Set([
132 'Realtime audio duration',
133 'Transcription audio duration',
134 'Live session duration',
135 'Video generation',
136 'Pricing',
137])
138
139/**
140 * Sections that restate a token price per unit rather than adding a cost.
141 * OpenAI's image models bill by tokens ("Prices per 1M tokens" on the
142 * pricing page); the per-image table is the equivalent cost of one image at
143 * a quality and size, already covered by the Image tokens rows.
144 */
145const DERIVED_SECTIONS = new Set(['Image generation'])
146
147const DAY_MS = 86_400_000
148
149/** `$1.25` → 1.25; null for anything that is not a plain dollar amount. */
150function usd(cell: string | undefined): number | null {
151 const amount = cell?.match(/^\$([\d,]+(?:\.\d+)?)$/)?.[1]
152 return amount === undefined ? null : Number(amount.replace(/,/g, ''))
153}
154
155/**
156 * Prose under the tables that changes the price. A bullet naming a
157 * non-default service tier, an opt-in endpoint or nothing billable is
158 * prose; anything else that quotes a multiplier or an amount refuses the
159 * model, so a new kind of surcharge cannot slip past as prose.
160 */
161const PROSE_BULLETS =
162 /\bbatch\b|\bflex\b|fast mode|priority|regional processing|data residency|calculator|does not offer|not billed|rather than text tokens|token rates match/i
163
164/** Levers a "…x input and cache rates" multiplier re-quotes. */
165const INPUT_LEVERS = [
166 'input_tokens',
167 'cache_read_tokens',
168 'cache_write_tokens',
169 'image_tokens',
170 'image_cache_tokens',
171 'audio_tokens',
172 'audio_cache_tokens',
173]
174const OUTPUT_LEVERS = [
175 'output_tokens',
176 'image_output_tokens',
177 'audio_output_tokens',
178]
179
180export interface DocsPricing {
181 rates: Record<string, number>
182 tiers: Array<TokenRateTier>
183 /** Promo end the page names, as an ISO instant. */
184 expiresAt?: string
185 /** Set instead of `rates` when the model is billed per unit. */
186 unit?: UnitCardSpec
187 /**
188 * Active and standby session seconds, each USD per second. Set instead
189 * of `unit` when a live page states both rates. Neither rate alone is
190 * this card.
191 */
192 session?: { activeSeconds: number; standbySeconds: number }
193 /** A Cached input cell was "-" or blank. Not a rate. */
194 cacheReadNotOffered?: true
195}
196
197/** Unit a price is quoted in → the lever it bills, and units per quote. */
198const UNITS: Record<string, { param: string; per: number }> = {
199 minute: { param: 'audio_seconds', per: 60 },
200 second: { param: 'seconds', per: 1 },
201 '1M characters': { param: 'characters', per: 1e6 },
202}
203
204/**
205 * Metric names on a live-session table that are each their own usage
206 * quantity. Any other unsized name in a multi-row table refuses the model.
207 */
208const LIVE_SESSION_METRICS = ['Active', 'Standby'] as const
209
210type ParsedUnit =
211 | { spec: UnitCardSpec }
212 | { session: { activeSeconds: number; standbySeconds: number } }
213
214/**
215 * A per-unit section: one rate, one per output size, or active and standby
216 * session time. The metric cell of a video row names the sizes the rate
217 * covers ("Portrait: 720x1280 Landscape: 1280x720"), which are `size`
218 * values on the request. Several unsized rows are a live session only when
219 * they are exactly Active and Standby; one of those names without the
220 * other refuses, and so does any other pair.
221 */
222function parseUnitSection(block: string): ParsedUnit | null {
223 const rates: Record<string, number> = {}
224 const flats: Array<{ metric: string; perSecond: number }> = []
225 let unit: { param: string; per: number } | undefined
226 for (const [metric = '', price, cell] of markdownTableRows(block)) {
227 if (metric === 'Metric') continue
228 const rate = usd(price)
229 const found = cell === undefined ? undefined : UNITS[cell]
230 // "Use case | Speech generation | 1M tokens" labels the table, and a
231 // row this parser cannot price at all refuses the model.
232 if (rate === null) {
233 if (metric === 'Use case' || metric === 'Quality') continue
234 return null
235 }
236 if (!found) return null
237 if (unit && unit.param !== found.param) return null
238 unit = found
239 const sizes = [...metric.matchAll(/(\d{3,4}x\d{3,4})/g)].map(
240 ([size]) => size,
241 )
242 if (sizes.length === 0) {
243 flats.push({ metric, perSecond: rate / found.per })
244 continue
245 }
246 for (const size of sizes) rates[size] = rate / found.per
247 }
248 if (!unit) return null
249 const sized = Object.keys(rates).length > 0
250 if (sized && flats.length > 0) return null
251 // Duration and characters are measured after the call; a video's length
252 // and size are fields of the request that asked for it.
253 const bound = unit.param === 'seconds' ? 'request' : 'usage'
254 if (sized) {
255 return {
256 spec: {
257 quantity: { param: unit.param, bound },
258 keys: [{ param: 'size', values: Object.keys(rates) }],
259 rates,
260 },
261 }
262 }
263 const only = flats[0]
264 if (flats.length === 1 && only) {
265 // Active or Standby alone is half a live card, not the old single rate.
266 if (
267 only.metric === 'Active' ||
268 only.metric === 'Standby' ||
269 !(only.perSecond > 0)
270 ) {
271 return null
272 }
273 return {
274 spec: {
275 quantity: { param: unit.param, bound },
276 rates: only.perSecond,
277 },
278 }
279 }
280 if (
281 flats.length !== 2 ||
282 (unit.param !== 'audio_seconds' && unit.param !== 'seconds')
283 ) {
284 return null
285 }
286 const byMetric = new Map(flats.map((row) => [row.metric, row.perSecond]))
287 const active = byMetric.get('Active')
288 const standby = byMetric.get('Standby')
289 if (
290 byMetric.size !== LIVE_SESSION_METRICS.length ||
291 active === undefined ||
292 standby === undefined ||
293 !(active > 0) ||
294 !(standby > 0)
295 ) {
296 return null
297 }
298 return { session: { activeSeconds: active, standbySeconds: standby } }
299}
300
301/**
302 * Active and standby session seconds, summed. Each lever is the duration
303 * the caller measured; neither defaults, so an omitted one is not billed
304 * as zero. Rates are USD per second.
305 */
306export function compileLiveSessionCard(
307 rates: { activeSeconds: number; standbySeconds: number },
308 source: RateCard['source'],
309): RateCard | null {
310 const { activeSeconds, standbySeconds } = rates
311 if (!(activeSeconds > 0) || !(standbySeconds > 0)) return null
312 const lever = (param: 'active_seconds' | 'standby_seconds') =>
313 ({
314 param,
315 bound: 'usage' as const,
316 kind: 'number' as const,
317 }) satisfies RateCard['inputs'][string]
318 return {
319 inputs: {
320 active_seconds: lever('active_seconds'),
321 standby_seconds: lever('standby_seconds'),
322 },
323 tables: {},
324 price: {
325 '+': [
326 { '*': [{ var: 'active_seconds' }, activeSeconds] },
327 { '*': [{ var: 'standby_seconds' }, standbySeconds] },
328 ],
329 },
330 examples: [],
331 source,
332 }
333}
334
335/**
336 * Search rows on the pricing page's Specialized models Standard table
337 * (issue #111). `gpt-5-search-api` has no model page. Embeddings,
338 * moderation, and other categories are not read here. The Fast table
339 * further down is a different tier, so it is not part of this card.
340 * A dash or blank cached-input cell is a stated absence, not $0.
341 */
342export function parseOpenAiSearchPricing(
343 markdown: string,
344): Map<string, Record<string, number>> & { cacheReadNotOffered: Set<string> } {
345 const start = markdown.indexOf('Specialized models')
346 const out = new Map<string, Record<string, number>>() as Map<
347 string,
348 Record<string, number>
349 > & { cacheReadNotOffered: Set<string> }
350 out.cacheReadNotOffered = new Set()
351 if (start < 0) return out
352 const rest = markdown.slice(start)
353 const fastAt = rest.search(/\nFast\b/)
354 const standard = fastAt < 0 ? rest : rest.slice(0, fastAt)
355 for (const [
356 category = '',
357 model = '',
358 input,
359 cached,
360 output,
361 ] of markdownTableRows(standard)) {
362 if (category !== 'Search' || model === '' || out.has(model)) continue
363 const inputUsd = usd(input)
364 const outputUsd = usd(output)
365 if (inputUsd === null || outputUsd === null) continue
366 const rates: Record<string, number> = {
367 input_tokens: inputUsd / 1e6,
368 output_tokens: outputUsd / 1e6,
369 }
370 if (cached !== undefined && cached !== '-' && cached.trim() !== '') {
371 const cachedUsd = usd(cached)
372 if (cachedUsd === null) continue
373 rates.cache_read_tokens = cachedUsd / 1e6
374 } else if (cached === '-' || cached?.trim() === '') {
375 out.cacheReadNotOffered.add(model)
376 }
377 out.set(model, rates)
378 }
379 return out
380}
381
382/**
383 * Per-token rates, long-prompt tiers and promo end from a model page's
384 * `## Pricing` section.
385 */
386export function parseModelPricing(markdown: string): DocsPricing | null {
387 const pricing = markdownSection(markdown, 'Pricing')
388 const rates: Record<string, number> = {}
389 let cacheReadNotOffered = false
390 const blocks = pricing.split('\n### ').slice(1)
391 // o3.md repeats `### Text tokens`: the first table is standard, the second
392 // is the half-price batch/flex table with no heading of its own. A later
393 // copy of a heading already priced is not the base rate, so it is dropped
394 // rather than overwriting it. Prompt-length tiers stay a separate shape.
395 const pricedHeadings = new Set<string>()
396 for (const block of blocks) {
397 const heading = block.split('\n')[0]?.trim() ?? ''
398 if (DERIVED_SECTIONS.has(heading)) continue
399 if (pricedHeadings.has(heading)) continue
400 pricedHeadings.add(heading)
401 if (UNIT_SECTIONS.has(heading)) {
402 // A model is billed one way: a page mixing token tables with a
403 // per-unit one is a shape this parser does not know.
404 if (blocks.length !== 1) return null
405 const parsed = parseUnitSection(block)
406 if (!parsed) return null
407 return 'session' in parsed
408 ? { rates: {}, tiers: [], session: parsed.session }
409 : { rates: {}, tiers: [], unit: parsed.spec }
410 }
411 const levers = PRICING_LEVERS[heading]
412 if (!levers) return null
413 for (const [metric = '', price, unit] of markdownTableRows(block)) {
414 if (metric === 'Metric') continue
415 const lever = levers[metric]
416 const cell = price?.trim() ?? ''
417 if (
418 lever === 'cache_read_tokens' &&
419 (cell === '-' || cell === '—' || cell === '–' || cell === '')
420 ) {
421 cacheReadNotOffered = true
422 continue
423 }
424 const rate = usd(price)
425 if (!lever || rate === null || unit !== '1M tokens') return null
426 rates[lever] = rate / 1e6
427 if (lever === 'cache_read_tokens') cacheReadNotOffered = false
428 }
429 }
430 if (Object.keys(rates).length === 0) return null
431
432 const bullets = [...pricing.matchAll(/^- (.+)$/gm)].map(
433 ([, bullet = '']) => bullet,
434 )
435 const out: DocsPricing = {
436 rates,
437 tiers: [],
438 ...(cacheReadNotOffered ? { cacheReadNotOffered: true as const } : {}),
439 }
440
441 // Rate-adding bullets first: a tier re-quotes whatever levers exist.
442 for (const bullet of bullets) {
443 // "Cache writes are billed at 1.25x the uncached input token rate."
444 const cacheWrite = bullet.match(
445 /cache writes are billed at ([\d.]+)x the uncached input token rate/i,
446 )
447 const input = rates.input_tokens
448 if (
449 cacheWrite?.[1] &&
450 input !== undefined &&
451 !('cache_write_tokens' in rates)
452 ) {
453 rates.cache_write_tokens = input * Number(cacheWrite[1])
454 }
455 // "…promotional pricing is available at least through November 21, 2026."
456 const promo = bullet.match(
457 /promotional pricing[^.]*through ([a-z]+ \d{1,2}, \d{4})/i,
458 )
459 if (promo?.[1]) {
460 const day = parseDay(promo[1])
461 if (day === null) return null
462 out.expiresAt = new Date(day + DAY_MS).toISOString()
463 }
464 }
465
466 for (const bullet of bullets) {
467 if (/cache writes are billed at|promotional pricing/i.test(bullet)) continue
468 // "Cached input tokens are priced at 10% of the uncached input token
469 // rate." GPT-6 Luna and Sol restate the Cached input row. A percentage
470 // that does not match that row is a different price, so the page refuses.
471 const cacheRead = bullet.match(
472 /cached input tokens are priced at ([\d.]+)% of the uncached input token rate/i,
473 )
474 if (cacheRead?.[1]) {
475 const input = rates.input_tokens
476 const factor = Number(cacheRead[1]) / 100
477 if (input === undefined || !Number.isFinite(factor)) return null
478 const expected = input * factor
479 const cached = rates.cache_read_tokens
480 if (cached === undefined) {
481 rates.cache_read_tokens = expected
482 } else if (Math.abs(cached - expected) > Math.abs(expected) * 1e-9) {
483 return null
484 }
485 continue
486 }
487 // "Prompts with >272K input tokens are priced at 2x input and 1.5x
488 // output for the full request" — a whole-request re-quote of every
489 // rate, which is exactly a tier.
490 const long = bullet.match(
491 /prompts with (?:more than |>)([\d,.]+\s*[km]?) input tokens are priced at ([\d.]+)x input(?: and cache rates)? and ([\d.]+)x output/i,
492 )
493 if (long) {
494 const threshold = tokenCount(long[1])
495 if (threshold === null) return null
496 const tier: Record<string, number> = {}
497 for (const [lever, rate] of Object.entries(rates)) {
498 const factor = INPUT_LEVERS.includes(lever)
499 ? Number(long[2])
500 : OUTPUT_LEVERS.includes(lever)
501 ? Number(long[3])
502 : null
503 // A lever the sentence does not cover would be quoted at the base
504 // rate inside the tier, which is a guess.
505 if (factor === null) return null
506 tier[lever] = rate * factor
507 }
508 out.tiers.push({ minPromptTokens: threshold, rates: tier })
509 continue
510 }
511 // "Cache-write prices shown use 30-minute retention. Standard cache
512 // writes cost $1.25 … for 30-minute retention and $2.50 for 12-hour
513 // retention." The table's Cache writes cell is the 30-minute rate.
514 // A 12-hour retention is a second TTL this card does not model, so it
515 // is prose when the 30-minute amount matches and a refusal when it
516 // does not.
517 const cacheRetention = bullet.match(
518 /cache-write prices shown use 30-minute retention\. standard cache writes cost \$([\d.]+) per million tokens for 30-minute retention and \$[\d.]+ for 12-hour retention/i,
519 )
520 if (cacheRetention?.[1]) {
521 const written = rates.cache_write_tokens
522 const thirty = Number(cacheRetention[1]) / 1e6
523 if (
524 written === undefined ||
525 !Number.isFinite(thirty) ||
526 Math.abs(written - thirty) > Math.abs(thirty) * 1e-9
527 ) {
528 return null
529 }
530 continue
531 }
532 if (PROSE_BULLETS.test(bullet)) continue
533 // An unrecognised bullet that quotes money, a multiplier or a
534 // percentage may be a surcharge this card would drop.
535 if (/\$|\b\d+(\.\d+)?x\b|%/.test(bullet)) return null
536 }
537 return out
538}
539
540function listValues(block: string, label: string): Array<string> {
541 const match = block.match(new RegExp(`^- ${label}: (.+)$`, 'm'))
542 return match?.[1]
543 ? match[1].split(',').map((s) => s.trim().toLowerCase())
544 : []
545}
546
547/** Parse one model page's details, features and snapshot ids. */
548export function parseModelPage(markdown: string): OpenAiModelPage | null {
549 const modelId = markdown.match(/^Model ID: `([^`]+)`/m)?.[1]
550 if (!modelId) return null
551 const details = markdownSection(markdown, 'Model details')
552 const ids = new Set<string>([modelId])
553 const pricedIds = new Set<string>([modelId])
554 const snapshot = details.match(/^- Default snapshot: `([^`]+)`/m)?.[1]
555 if (snapshot) {
556 ids.add(snapshot)
557 pricedIds.add(snapshot)
558 }
559 for (const m of markdownSection(markdown, 'Snapshots').matchAll(
560 /^- `([^`]+)`/gm,
561 )) {
562 if (m[1]) ids.add(m[1])
563 }
564
565 const input = listValues(details, 'Input modalities')
566 const output = listValues(details, 'Output modalities')
567 const contextWindow = tokenCount(
568 details.match(/^- ([\d,]+) context window/m)?.[1],
569 )
570 const maxOutput = tokenCount(
571 details.match(/^- ([\d,]+) max output tokens/m)?.[1],
572 )
573
574 const features = new Set(
575 [
576 ...markdownSection(markdown, 'Supported features').matchAll(/^- (\S+)/gm),
577 ].map((m) => m[1] ?? ''),
578 )
579 // `file_uploads` is the page's per-model statement that the model takes
580 // `input_file` / `file` parts (the file-inputs guide: PDFs on every such
581 // model, other documents as extracted text). Absent, nothing is said; a
582 // page that states no input modalities gets none from this alone.
583 if (
584 features.has('file_uploads') &&
585 input.length > 0 &&
586 !input.includes('file')
587 ) {
588 input.push('file')
589 }
590 const reasoning = /^- Reasoning token support/m.test(details)
591 const capabilities: Array<string> = []
592 if (features.has('function_calling')) capabilities.push('tools')
593 if (reasoning) capabilities.push('reasoning')
594 // Effort levels and sampling-param support appear only in prose on the
595 // page; neither is a field, so neither is asserted here.
596 if (features.has('structured_outputs')) {
597 capabilities.push('structured_outputs', 'response_format')
598 }
599
600 const serverTools = [
601 ...markdownSection(markdown, 'Supported tools').matchAll(/^- (\S+)/gm),
602 ].flatMap((m) => {
603 const type = RESPONSES_TOOL_TYPES[m[1] ?? '']
604 return type ? [type] : []
605 })
606 // Silent only when the page states the model has no route that takes
607 // hosted tools: Responses, every Realtime route and Live all Not supported.
608 // A Responses page with no "Supported tools" section (gpt-4, gpt-image-1
609 // and 7 others on 2026-11-21) states nothing.
610 const endpoints = parseEndpoints(markdown)
611 const toolRoutes = [...endpoints].filter(
612 ([name]) =>
613 name === 'Responses' || name === 'Live' || name.startsWith('Realtime'),
614 )
615 const toolsSilent =
616 serverTools.length === 0 &&
617 endpoints.has('Responses') &&
618 endpoints.has('Realtime') &&
619 toolRoutes.every(([, supported]) => !supported)
620
621 return {
622 ids: [...ids],
623 pricedIds: [...pricedIds],
624 pricing: parseModelPricing(markdown),
625 ...(toolsSilent ? { toolsSilent: true as const } : {}),
626 facts: {
627 contextWindow,
628 maxOutput,
629 modalities:
630 input.length > 0 || output.length > 0 ? { input, output } : null,
631 capabilities: capabilities.length > 0 ? capabilities : null,
632 reasoning: reasoning ? parseReasoningEffort(markdown) : null,
633 serverTools: serverTools.length > 0 ? serverTools : null,
634 },
635 }
636}
637
638/**
639 * "Supported tools" names → Responses API `tools[].type`. `function_calling`
640 * is a client tool and `skills` rides on `shell`; neither is a type.
641 */
642const RESPONSES_TOOL_TYPES: Record<string, string> = {
643 web_search: 'web_search',
644 file_search: 'file_search',
645 tool_search: 'tool_search',
646 image_generation: 'image_generation',
647 code_interpreter: 'code_interpreter',
648 hosted_shell: 'shell',
649 apply_patch: 'apply_patch',
650 computer_use: 'computer',
651 mcp: 'mcp',
652}
653
654const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']
655
656/**
657 * Effort levels from the page's prose: "Reasoning.effort supports: none
658 * (default), low, …" or "defaults to (and only supports) `reasoning.effort:
659 * high`". Reasoning is optional only when `none` is accepted. The page's
660 * own exhaustive list with no off value means thinking cannot be turned
661 * off. Without a list, its mode stays unknown; capability is separate.
662 */
663export function parseReasoningEffort(markdown: string): ModelReasoning | null {
664 const prose = markdown.replace(/```[\s\S]*?```/g, '')
665 const only = prose.match(
666 /only supports\)?\s*`reasoning\.effort:\s*([a-z]+)`/i,
667 )?.[1]
668 const list =
669 prose.match(
670 /(?:reasoning\.effort`?\s+supports:?|supports\s+`?reasoning\.effort`?:?)\s*([^.!]+?)(?=\.(?:\s|$)|\n\s*\n|$)/i,
671 ) ??
672 prose.match(
673 /supports\s+((?:`[a-z]+`[^.!]*?)+)\s+reasoning effort settings/i,
674 ) ??
675 prose.match(/Configurable reasoning effort:[^\n]*?\(([^)]+)\)/i)
676 const words = only
677 ? [only.toLowerCase()]
678 : (list?.[1]?.toLowerCase().match(/[a-z]+/g) ?? [])
679 const efforts = EFFORTS.filter((level) => words.includes(level))
680 if (!efforts.length) {
681 // "The API rejects requests that set reasoning effort to `none`" (GPT-6.2
682 // pages, #711): the effort control exists and its off value is refused.
683 if (/rejects requests that set reasoning effort to `none`/i.test(prose)) {
684 return { mode: 'effort', mandatory: true }
685 }
686 const explicitControl = prose.split('\n').some((line) => {
687 const declaration = line.match(
688 /^(.*?)\bsupports configurable reasoning effort\b/i,
689 )
690 return (
691 declaration !== null &&
692 !/\b(?:not|never|cannot|no)\b|doesn't/i.test(declaration[1] ?? '')
693 )
694 })
695 return explicitControl ? { mode: 'effort', mandatory: null } : null
696 }
697 // The page's own list is exhaustive and names no off value, so thinking
698 // cannot be turned off. Prose that denies that ("not always on") leaves
699 // it unstated. A shared family guide does not come through here.
700 const denied =
701 /(?:reasoning|thinking)\s+(?:is\s+)?not\s+(?:always on|mandatory|required)/i.test(
702 prose,
703 ) || /can be (?:disabled|turned off)/i.test(prose)
704 return {
705 mode: 'effort',
706 mandatory: efforts.includes('none') ? false : denied ? null : true,
707 ...(efforts.length > 0 ? { efforts } : {}),
708 }
709}
710
711/**
712 * Model pages the models index no longer links, which still publish a price.
713 * Dated snapshots resolve to that page; `pricedIds` decides whether the
714 * price applies. A family page is never used for an id that is not that
715 * page's model id or its dated form (`tts-1-1106` is not `tts-1`).
716 */
717const UNINDEXED_MODEL_PAGES = new Set(['sora-2', 'sora-2-pro'])
718
719/** Page slug a listed id resolves to, or null when the docs have no page. */
720export function pageSlugFor(rawId: string, slugs: Set<string>): string | null {
721 if (slugs.has(rawId)) return rawId
722 const undated = undatedId(rawId)
723 if (slugs.has(undated)) return undated
724 if (UNINDEXED_MODEL_PAGES.has(rawId)) return rawId
725 if (UNINDEXED_MODEL_PAGES.has(undated)) return undated
726 return null
727}
728
729/**
730 * Ids whose listing should load the GPT-5 guides. Wider than the sentences:
731 * a parsed guide applies only to the ids it names.
732 */
733function gpt5GuideSelects(rawId: string): boolean {
734 return /^gpt-5(?:-[a-z][a-z0-9-]*)?$/.test(undatedId(rawId))
735}
736
737/**
738 * Ids a failed family or sampling guide may hold. The parsed family sentence
739 * wins; without it, only the three ids those guides are written for.
740 */
741const GPT5_GUIDE_FAMILY = ['gpt-5', 'gpt-5-mini', 'gpt-5-nano']
742
743function guideNames(rawId: string, ids: Array<string>): boolean {
744 return ids.includes(rawId) || ids.includes(undatedId(rawId))
745}
746
747type OpenAiDocsFacts = ModelFacts &
748 Pick<ModelInfo, 'unsupportedCapabilities' | 'absent' | 'aliases' | 'aliasOf'>
749
750type AliasFacts = Pick<ModelInfo, 'aliases' | 'aliasOf'> & {
751 factSources: ModelFactSources
752}
753
754/**
755 * Alias links the model pages state (issue #709). A page's `Model ID` is
756 * an alias of its `Default snapshot` when the two differ: the alias row
757 * points at the snapshot, and the snapshot lists the alias. The page lists
758 * "all available snapshots and aliases", so another snapshot it names has
759 * no alias. Read from the parsed page: `ids[0]` is the Model ID and the
760 * default snapshot is the other priced id.
761 */
762export function openaiAliasFacts(
763 pages: ReadonlyArray<{
764 url: string
765 hash: string
766 ids: ReadonlyArray<string>
767 pricedIds: ReadonlyArray<string>
768 }>,
769): Map<string, AliasFacts> {
770 const out = new Map<string, AliasFacts>()
771 const get = (id: string) => {
772 const facts = out.get(id) ?? { factSources: {} }
773 out.set(id, facts)
774 return facts
775 }
776 for (const page of pages) {
777 const modelId = page.ids[0]
778 if (modelId === undefined) continue
779 const snapshot = page.pricedIds.find((id) => id !== modelId)
780 const source = (path: string): FactSource => ({
781 derivation: 'docs-derived',
782 sourceUrl: page.url,
783 sourceHash: page.hash,
784 path,
785 })
786 if (snapshot !== undefined) {
787 const alias = get(modelId)
788 alias.aliasOf = snapshot
789 alias.factSources.aliasOf = source('Default snapshot')
790 const target = get(snapshot)
791 target.aliases = [...new Set([...(target.aliases ?? []), modelId])].sort()
792 target.factSources.aliases = source('Default snapshot')
793 }
794 for (const id of page.ids) {
795 if (id === modelId || id === snapshot) continue
796 const other = get(id)
797 other.factSources.aliases ??= source('Snapshots')
798 }
799 }
800 return out
801}
802
803/** Facts a model page (via the index that names it) feeds. */
804const PAGE_FACTS = [
805 'contextWindow',
806 'maxOutput',
807 'modalities',
808 'capabilities',
809 'pricing',
810 'reasoning',
811 'serverTools',
812 'aliases',
813 'aliasOf',
814] as const
815
816/**
817 * Facts for the listed ids. Pages are fetched once per slug and memoised;
818 * a page's snapshot list also seeds ids the index alone couldn't resolve.
819 * Every docs load goes through `tryDocs`, so a failed one leaves the facts
820 * it feeds `unavailable` on the rows it speaks for and the listing still
821 * polls: the index or a model page (every page fact; a failed page may be
822 * the alias page that seeds an id, so unresolved ids too), the pricing
823 * page (an unpriced row's pricing), the realtime guide (reasoning on a
824 * realtime id whose effort-mode page lists no efforts).
825 * A failed family or sampling guide marks `absent` on the ids it speaks for.
826 * A failed GPT-5.1 guide does not: the family list stays, with mandatory null.
827 * Every load goes through `fetcher`; the poll passes the US egress, since
828 * the docs host answered 403 to loads from hkg1 (#505).
829 */
830export async function openaiModelFacts(
831 rawIds: Array<string>,
832 kv?: KVNamespace,
833 run: DocsRun = docsRun(),
834 fetcher: Fetcher = fetch,
835): Promise<(rawId: string) => OpenAiDocsFacts> {
836 const indexed = await tryDocs(run, OPENAI_MODELS_INDEX_URL, (cached) =>
837 cached(kv, OPENAI_MODELS_INDEX_URL, async () => {
838 const parsed = [
839 ...parseModelIndex(
840 await fetchText(OPENAI_MODELS_INDEX_URL, undefined, fetcher),
841 ),
842 ]
843 if (parsed.length === 0) {
844 throw new Error('openai models index: parsed 0 page slugs')
845 }
846 return parsed
847 }),
848 )
849 const slugs = new Set(indexed)
850 const needed = [
851 ...new Set(
852 rawIds
853 .map((id) => pageSlugFor(id, slugs))
854 .filter((slug): slug is string => slug !== null),
855 ),
856 ]
857 const searchDoc = await tryDocs(run, OPENAI_PRICING_URL, (cached) =>
858 // v2: the cached value gained `cacheReadNotOffered`; a v1 value lacks it.
859 cached(kv, `${OPENAI_PRICING_URL}#search-v2`, async () => {
860 const markdown = await fetchText(OPENAI_PRICING_URL, undefined, fetcher)
861 const parsed = parseOpenAiSearchPricing(markdown)
862 assertParsed(parsed, 'openai pricing page search rows')
863 return {
864 rates: Object.fromEntries(parsed),
865 cacheReadNotOffered: [...parsed.cacheReadNotOffered],
866 hash: await sha256Text(markdown),
867 extractedAt: new Date().toISOString(),
868 }
869 }),
870 )
871 const pageLoads = await mapConcurrent(needed, 8, async (slug) => {
872 const page = await tryDocs(run, OPENAI_MODEL_PAGE(slug), (cached) =>
873 cached(kv, OPENAI_MODEL_PAGE(slug), async () => {
874 const markdown = await fetchText(
875 OPENAI_MODEL_PAGE(slug),
876 undefined,
877 fetcher,
878 )
879 const parsed = parseModelPage(markdown)
880 if (!parsed) {
881 throw new Error(`openai model page ${slug}: no Model ID`)
882 }
883 // The card's provenance hashes the page as served, so an unchanged
884 // page keeps the stored card (and its `extractedAt`) on re-parse.
885 return {
886 ...parsed,
887 hash: await sha256Text(markdown),
888 extractedAt: new Date().toISOString(),
889 }
890 }),
891 )
892 return page ? { slug, page } : null
893 })
894 const pages = pageLoads.filter((page) => page !== null)
895 const failedSlugs = new Set(
896 needed.filter((_, index) => pageLoads[index] === null),
897 )
898 // A model's own page takes precedence over another alias page that names
899 // it as a default snapshot. Listing order must not erase native controls.
900 const primaryIds = new Set(pages.map((loaded) => loaded.page.ids[0]))
901 const byId = new Map<string, OpenAiDocsFacts>()
902 for (const loaded of pages) {
903 const url = OPENAI_MODEL_PAGE(loaded.slug)
904 const withPricing: ModelFacts = {
905 ...loaded.page.facts,
906 pricing: loaded.page.pricing?.session
907 ? compileLiveSessionCard(loaded.page.pricing.session, {
908 url,
909 hash: loaded.page.hash,
910 extractedAt: loaded.page.extractedAt,
911 })
912 : loaded.page.pricing?.unit
913 ? compileUnitCard(loaded.page.pricing.unit, {
914 url,
915 hash: loaded.page.hash,
916 extractedAt: loaded.page.extractedAt,
917 })
918 : loaded.page.pricing
919 ? compileTokenCard(
920 loaded.page.pricing.rates,
921 loaded.page.pricing.tiers,
922 {
923 url,
924 hash: loaded.page.hash,
925 extractedAt: loaded.page.extractedAt,
926 ...(loaded.page.pricing.expiresAt && {
927 expiresAt: loaded.page.pricing.expiresAt,
928 }),
929 },
930 )
931 : null,
932 }
933 const facts: ModelFacts = {
934 ...withPricing,
935 factSources: {
936 ...tagDocsFacts(withPricing, url, loaded.page.hash),
937 ...(loaded.page.toolsSilent
938 ? { serverTools: serverToolsSilent(url) }
939 : {}),
940 ...(loaded.page.pricing?.cacheReadNotOffered &&
941 loaded.page.pricing.rates.cache_read_tokens === undefined
942 ? {
943 cacheRead: {
944 derivation: 'docs-derived' as const,
945 sourceUrl: url,
946 sourceHash: loaded.page.hash,
947 path: 'not-offered',
948 },
949 }
950 : {}),
951 },
952 }
953 const priced = new Set(loaded.page.pricedIds)
954 for (const id of loaded.page.ids) {
955 if (id !== loaded.page.ids[0] && primaryIds.has(id)) continue
956 if (priced.has(id)) {
957 byId.set(id, facts)
958 continue
959 }
960 // The family page prices the alias and the default snapshot only.
961 // An older snapshot (gpt-4o-2024-05-13) is not that price.
962 const sources = { ...facts.factSources }
963 delete sources.pricing
964 byId.set(id, { ...facts, pricing: null, factSources: sources })
965 }
966 }
967 const realtimeListed = rawIds.some(openaiRealtimeSelects)
968 const realtime = realtimeListed
969 ? await tryDocs(run, OPENAI_REALTIME_EFFORT_URL, (cached) =>
970 openaiRealtimeEfforts(rawIds, kv, cached, fetcher),
971 )
972 : null
973 if (realtime) {
974 const own = byId.get(realtime.rawId)
975 if (own?.reasoning?.mode === 'effort' && !own.reasoning.efforts?.length) {
976 byId.set(realtime.rawId, {
977 ...own,
978 reasoning: { ...own.reasoning, efforts: realtime.efforts },
979 factSources: {
980 ...own.factSources,
981 reasoning: {
982 derivation: 'docs-derived',
983 sourceUrl: OPENAI_REALTIME_EFFORT_URL,
984 sourceHash: realtime.hash,
985 path: 'Set reasoning effort',
986 },
987 },
988 })
989 }
990 }
991 const guides = rawIds.some(gpt5GuideSelects)
992 ? await Promise.all([
993 tryDocs(run, OPENAI_GPT5_GUIDE_URL, (cached) =>
994 loadGuide(
995 cached,
996 kv,
997 OPENAI_GPT5_GUIDE_URL,
998 parseGpt5FamilyGuide,
999 fetcher,
1000 ),
1001 ),
1002 tryDocs(run, OPENAI_GPT51_GUIDE_URL, (cached) =>
1003 loadGuide(
1004 cached,
1005 kv,
1006 OPENAI_GPT51_GUIDE_URL,
1007 parseGpt51NoneGuide,
1008 fetcher,
1009 ),
1010 ),
1011 tryDocs(run, OPENAI_GPT52_GUIDE_URL, (cached) =>
1012 loadGuide(
1013 cached,
1014 kv,
1015 OPENAI_GPT52_GUIDE_URL,
1016 parseGpt52SamplingGuide,
1017 fetcher,
1018 ),
1019 ),
1020 ])
1021 : null
1022 if (guides) {
1023 const [family, none, sampling] = guides
1024 const guideSource = (url: string, hash: string, path: string) =>
1025 ({
1026 derivation: 'docs-derived',
1027 sourceUrl: url,
1028 sourceHash: hash,
1029 path,
1030 }) satisfies FactSource
1031 for (const [id, own] of byId) {
1032 const flags: unknown = own.capabilities
1033 if (!Array.isArray(flags) || !flags.includes('reasoning')) continue
1034 const named = (ids: Array<string>) =>
1035 ids.includes(id) || ids.includes(undatedId(id))
1036 let facts: OpenAiDocsFacts = own
1037 if (family && named(family.parsed.rawIds) && !own.reasoning?.efforts) {
1038 facts = {
1039 ...facts,
1040 reasoning: {
1041 mode: 'effort',
1042 mandatory: null,
1043 efforts: family.parsed.efforts,
1044 },
1045 factSources: {
1046 ...facts.factSources,
1047 reasoning: guideSource(
1048 OPENAI_GPT5_GUIDE_URL,
1049 family.hash,
1050 'Model, API, and feature updates',
1051 ),
1052 },
1053 }
1054 }
1055 const reasoning = facts.reasoning
1056 if (
1057 family &&
1058 none &&
1059 named(family.parsed.rawIds) &&
1060 !family.parsed.efforts.includes('none') &&
1061 reasoning?.mandatory === null &&
1062 reasoning.efforts?.join() === family.parsed.efforts.join() &&
1063 reasoning.efforts[0] === none.parsed
1064 ) {
1065 facts = {
1066 ...facts,
1067 reasoning: { ...reasoning, mandatory: true },
1068 factSources: {
1069 ...facts.factSources,
1070 reasoning: guideSource(
1071 OPENAI_GPT51_GUIDE_URL,
1072 none.hash,
1073 'Using the "none" reasoning mode for improved efficiency',
1074 ),
1075 },
1076 }
1077 }
1078 if (sampling && named(sampling.parsed.rawIds)) {
1079 const source = guideSource(
1080 OPENAI_GPT52_GUIDE_URL,
1081 sampling.hash,
1082 'GPT-5.2 parameter compatibility',
1083 )
1084 facts = {
1085 ...facts,
1086 unsupportedCapabilities: sampling.parsed.flags,
1087 factSources: {
1088 ...facts.factSources,
1089 capabilities: {
1090 ...facts.factSources?.capabilities,
1091 ...Object.fromEntries(
1092 sampling.parsed.flags.map((flag) => [flag, source]),
1093 ),
1094 },
1095 },
1096 }
1097 }
1098 byId.set(id, facts)
1099 }
1100 }
1101 if (pages.length > 0) assertParsed(byId, 'openai model pages')
1102 const aliasLinks = openaiAliasFacts(
1103 pages.map(({ slug, page }) => ({
1104 url: OPENAI_MODEL_PAGE(slug),
1105 hash: page.hash,
1106 ids: page.ids,
1107 pricedIds: page.pricedIds,
1108 })),
1109 )
1110 const namedIds = new Set(pages.flatMap(({ page }) => page.ids))
1111 const familyIds = guides?.[0]?.parsed.rawIds ?? GPT5_GUIDE_FAMILY
1112 const guideGaps: OpenAiDocsFacts['absent'] = {}
1113 // The 5.1 sentence only upgrades mandatory. Its failure leaves the family
1114 // list in place with mandatory null, which is the unstated value.
1115 if (guides && !guides[0]) guideGaps.reasoning = 'unavailable'
1116 if (guides && !guides[2]) guideGaps.capabilities = 'unavailable'
1117 return (rawId) => {
1118 const facts = sourcedFacts(rawId)
1119 if (!guides || !guideNames(rawId, familyIds)) return facts
1120 const absent = { ...facts.absent }
1121 if (guideGaps.reasoning) absent.reasoning = 'unavailable'
1122 if (guideGaps.capabilities) absent.capabilities = 'unavailable'
1123 return guideGaps.reasoning || guideGaps.capabilities
1124 ? { ...facts, absent }
1125 : facts
1126 }
1127 /** `docsFacts`, with the facts a failed docs load feeds left unavailable. */
1128 function sourcedFacts(rawId: string): OpenAiDocsFacts {
1129 const slug = indexed ? pageSlugFor(rawId, slugs) : null
1130 // A failed page may also have been the alias page that seeds this id.
1131 const pageLost =
1132 !indexed ||
1133 (slug !== null && failedSlugs.has(slug)) ||
1134 (failedSlugs.size > 0 && !byId.has(rawId) && !byId.has(undatedId(rawId)))
1135 if (pageLost) return { ...NO_FACTS, ...unavailable(...PAGE_FACTS) }
1136 const facts = withAliases(rawId, docsFacts(rawId))
1137 const gaps: OpenAiDocsFacts['absent'] = { ...facts.absent }
1138 if (!searchDoc && !facts.pricing) gaps.pricing = 'unavailable'
1139 // The guide only fills efforts an effort-mode page left unlisted.
1140 const effortsUnlisted =
1141 facts.reasoning?.mode === 'effort' && !facts.reasoning.efforts?.length
1142 if (
1143 realtimeListed &&
1144 !realtime &&
1145 openaiRealtimeSelects(rawId) &&
1146 effortsUnlisted
1147 ) {
1148 gaps.reasoning = 'unavailable'
1149 }
1150 return Object.keys(gaps).length > 0 ? { ...facts, absent: gaps } : facts
1151 }
1152 /** A listed id no page names: the docs say nothing of its aliases. */
1153 function withAliases(rawId: string, facts: OpenAiDocsFacts): OpenAiDocsFacts {
1154 const link = aliasLinks.get(rawId)
1155 if (!link && namedIds.has(rawId)) return facts
1156 const slug = pageSlugFor(rawId, slugs)
1157 const unstated: ModelFactSources = {
1158 aliases: {
1159 derivation: 'docs-derived',
1160 sourceUrl: slug ? OPENAI_MODEL_PAGE(slug) : OPENAI_MODELS_INDEX_URL,
1161 path: 'unstated',
1162 },
1163 }
1164 const { factSources, ...linked } = link ?? { factSources: unstated }
1165 return {
1166 ...facts,
1167 ...linked,
1168 factSources: { ...facts.factSources, ...factSources },
1169 }
1170 }
1171 function docsFacts(rawId: string): OpenAiDocsFacts {
1172 const exact = byId.get(rawId)
1173 let facts: OpenAiDocsFacts
1174 if (exact) {
1175 facts = exact
1176 } else {
1177 const familyId = undatedId(rawId)
1178 const family = byId.get(familyId)
1179 if (!family || familyId === rawId) {
1180 facts = family ?? NO_FACTS
1181 } else {
1182 // The family page prices the alias and the default snapshot only.
1183 const sources = { ...family.factSources }
1184 delete sources.pricing
1185 facts = { ...family, pricing: null, factSources: sources }
1186 }
1187 }
1188 if (facts.pricing) return facts
1189 if (!searchDoc) return facts
1190 // Exact id only. A dated snapshot is not the undated search row.
1191 const rates = searchDoc.rates[rawId]
1192 if (!rates) return facts
1193 const pricing = compileTokenCard(rates, [], {
1194 url: OPENAI_PRICING_URL,
1195 hash: searchDoc.hash,
1196 extractedAt: searchDoc.extractedAt,
1197 })
1198 if (!pricing) return facts
1199 return {
1200 ...facts,
1201 pricing,
1202 factSources: {
1203 ...facts.factSources,
1204 ...tagDocsFacts({ pricing }, OPENAI_PRICING_URL, searchDoc.hash),
1205 ...(searchDoc.cacheReadNotOffered.includes(rawId) &&
1206 rates.cache_read_tokens === undefined
1207 ? {
1208 cacheRead: {
1209 derivation: 'docs-derived' as const,
1210 sourceUrl: OPENAI_PRICING_URL,
1211 sourceHash: searchDoc.hash,
1212 path: 'not-offered',
1213 },
1214 }
1215 : {}),
1216 },
1217 }
1218 }
1219}