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