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

openai-model-docs.ts

896 lines31.3 KB

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