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