Open History to see the last commit
1import {
2 OPENAI_REALTIME_EFFORT_URL,
3 openaiRealtimeEfforts,
4} from './openai-realtime-efforts.ts'
5/**
6 * OpenAI model facts from OpenAI's own docs. `GET /v1/models` is `id` +
7 * `created` only; developers.openai.com serves every model page as
8 * markdown (`/api/docs/models/{slug}.md`) with a fixed "Model details"
9 * bullet list, a "Supported features" list, and the page's snapshot ids. The index (`/api/docs/models.md`) is the
10 * slug list. Only pages the listed ids resolve to are fetched (~65 of the
11 * ~130 listed ids share a page), bounded-concurrency, memoised six hours.
12 */
13import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
14import type { TokenRateTier, UnitCardSpec } from '@modelschemas/rate-card'
15
16import { tagDocsFacts } from './fact-sources.ts'
17import {
18 NO_FACTS,
19 assertParsed,
20 cachedDocs,
21 mapConcurrent,
22 markdownSection,
23 markdownTableRows,
24 parseDay,
25 tokenCount,
26 undatedId,
27} from './model-facts.ts'
28import type { ModelFacts } from './model-facts.ts'
29import { fetchText, sha256Text } from './types.ts'
30import type { ModelReasoning } from './types.ts'
31
32export const OPENAI_MODELS_INDEX_URL =
33 'https://developers.openai.com/api/docs/models.md'
34export const OPENAI_PRICING_URL =
35 'https://developers.openai.com/api/docs/pricing.md'
36const OPENAI_MODEL_PAGE = (slug: string) =>
37 `https://developers.openai.com/api/docs/models/${slug}.md`
38
39/** Page slugs linked from the models index. */
40export function parseModelIndex(markdown: string): Set<string> {
41 return new Set(
42 [
43 ...markdown.matchAll(/\]\(\/api\/docs\/models\/([^)\s]+?)\.md\)/g),
44 ].flatMap((m) => (m[1] ? [m[1]] : [])),
45 )
46}
47
48export interface OpenAiModelPage {
49 /** Every id the page speaks for: `Model ID`, default snapshot, snapshots. */
50 ids: Array<string>
51 /**
52 * Ids the page's price belongs to: the model id and its default snapshot.
53 * An older dated snapshot keeps the page's other facts but not this price.
54 */
55 pricedIds: Array<string>
56 facts: ModelFacts
57 /** Token rates and tiers, or null when the page prices otherwise. */
58 pricing: DocsPricing | null
59}
60
61/**
62 * Pricing subsection → the lever each `Metric` row prices. Every other
63 * subsection (image/video generation, audio duration, a per-call tool fee)
64 * refuses the whole model: a card quoting only its token rows would
65 * understate the bill. Unknown means null, never a partial card.
66 */
67const PRICING_LEVERS: Record<string, Record<string, string>> = {
68 'Text tokens': {
69 Input: 'input_tokens',
70 'Cached input': 'cache_read_tokens',
71 'Cache writes': 'cache_write_tokens',
72 Output: 'output_tokens',
73 },
74 'Audio tokens': {
75 Input: 'audio_tokens',
76 'Cached input': 'audio_cache_tokens',
77 Output: 'audio_output_tokens',
78 },
79 'Image tokens': {
80 Input: 'image_tokens',
81 'Cached input': 'image_cache_tokens',
82 Output: 'image_output_tokens',
83 },
84 Embeddings: { Cost: 'input_tokens' },
85}
86
87/**
88 * Sections priced per unit rather than per token. `Pricing` is the legacy
89 * tts/whisper table, whose `Cost` row carries the unit.
90 */
91const UNIT_SECTIONS = new Set([
92 'Realtime audio duration',
93 'Transcription audio duration',
94 'Live session duration',
95 'Video generation',
96 'Pricing',
97])
98
99/**
100 * Sections that restate a token price per unit rather than adding a cost.
101 * OpenAI's image models bill by tokens ("Prices per 1M tokens" on the
102 * pricing page); the per-image table is the equivalent cost of one image at
103 * a quality and size, already covered by the Image tokens rows.
104 */
105const DERIVED_SECTIONS = new Set(['Image generation'])
106
107const DAY_MS = 86_400_000
108
109/** `$1.25` → 1.25; null for anything that is not a plain dollar amount. */
110function usd(cell: string | undefined): number | null {
111 const amount = cell?.match(/^\$([\d,]+(?:\.\d+)?)$/)?.[1]
112 return amount === undefined ? null : Number(amount.replace(/,/g, ''))
113}
114
115/**
116 * Prose under the tables that changes the price. A bullet naming a
117 * non-default service tier, an opt-in endpoint or nothing billable is
118 * prose; anything else that quotes a multiplier or an amount refuses the
119 * model, so a new kind of surcharge cannot slip past as prose.
120 */
121const PROSE_BULLETS =
122 /\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
123
124/** Levers a "…x input and cache rates" multiplier re-quotes. */
125const INPUT_LEVERS = [
126 'input_tokens',
127 'cache_read_tokens',
128 'cache_write_tokens',
129 'image_tokens',
130 'image_cache_tokens',
131 'audio_tokens',
132 'audio_cache_tokens',
133]
134const OUTPUT_LEVERS = [
135 'output_tokens',
136 'image_output_tokens',
137 'audio_output_tokens',
138]
139
140export interface DocsPricing {
141 rates: Record<string, number>
142 tiers: Array<TokenRateTier>
143 /** Promo end the page names, as an ISO instant. */
144 expiresAt?: string
145 /** Set instead of `rates` when the model is billed per unit. */
146 unit?: UnitCardSpec
147}
148
149/** Unit a price is quoted in → the lever it bills, and units per quote. */
150const UNITS: Record<string, { param: string; per: number }> = {
151 minute: { param: 'audio_seconds', per: 60 },
152 second: { param: 'seconds', per: 1 },
153 '1M characters': { param: 'characters', per: 1e6 },
154}
155
156/**
157 * A per-unit section: one rate, or one per output size. The metric cell of
158 * a video row names the sizes the rate covers ("Portrait: 720x1280
159 * Landscape: 1280x720"), which are `size` values on the request.
160 */
161function parseUnitSection(block: string): UnitCardSpec | null {
162 const rates: Record<string, number> = {}
163 let flat: number | null = null
164 let unit: { param: string; per: number } | undefined
165 for (const [metric = '', price, cell] of markdownTableRows(block)) {
166 if (metric === 'Metric') continue
167 const rate = usd(price)
168 const found = cell === undefined ? undefined : UNITS[cell]
169 // "Use case | Speech generation | 1M tokens" labels the table, and a
170 // row this parser cannot price at all refuses the model.
171 if (rate === null) {
172 if (metric === 'Use case' || metric === 'Quality') continue
173 return null
174 }
175 if (!found) return null
176 if (unit && unit.param !== found.param) return null
177 unit = found
178 const sizes = [...metric.matchAll(/(\d{3,4}x\d{3,4})/g)].map(
179 ([size]) => size,
180 )
181 if (sizes.length === 0) {
182 if (flat !== null) return null
183 flat = rate / found.per
184 continue
185 }
186 for (const size of sizes) rates[size] = rate / found.per
187 }
188 if (!unit) return null
189 const sized = Object.keys(rates).length > 0
190 if (sized && flat !== null) return null
191 if (!sized && flat === null) return null
192 // Duration and characters are measured after the call; a video's length
193 // and size are fields of the request that asked for it.
194 const bound = unit.param === 'seconds' ? 'request' : 'usage'
195 return {
196 quantity: { param: unit.param, bound },
197 ...(sized && {
198 keys: [{ param: 'size', values: Object.keys(rates) }],
199 }),
200 rates: sized ? rates : (flat ?? 0),
201 }
202}
203
204/**
205 * Search rows on the pricing page's Specialized models Standard table
206 * (issue #111). `gpt-5-search-api` has no model page. Embeddings,
207 * moderation, and other categories are not read here. The Fast table
208 * further down is a different tier, so it is not part of this card.
209 * A dash cached-input cell is an unpublished lever, not $0.
210 */
211export function parseOpenAiSearchPricing(
212 markdown: string,
213): Map<string, Record<string, number>> {
214 const start = markdown.indexOf('Specialized models')
215 const out = new Map<string, Record<string, number>>()
216 if (start < 0) return out
217 const rest = markdown.slice(start)
218 const fastAt = rest.search(/\nFast\b/)
219 const standard = fastAt < 0 ? rest : rest.slice(0, fastAt)
220 for (const [
221 category = '',
222 model = '',
223 input,
224 cached,
225 output,
226 ] of markdownTableRows(standard)) {
227 if (category !== 'Search' || model === '' || out.has(model)) continue
228 const inputUsd = usd(input)
229 const outputUsd = usd(output)
230 if (inputUsd === null || outputUsd === null) continue
231 const rates: Record<string, number> = {
232 input_tokens: inputUsd / 1e6,
233 output_tokens: outputUsd / 1e6,
234 }
235 if (cached !== undefined && cached !== '-' && cached !== '') {
236 const cachedUsd = usd(cached)
237 if (cachedUsd === null) continue
238 rates.cache_read_tokens = cachedUsd / 1e6
239 }
240 out.set(model, rates)
241 }
242 return out
243}
244
245/**
246 * Per-token rates, long-prompt tiers and promo end from a model page's
247 * `## Pricing` section.
248 */
249export function parseModelPricing(markdown: string): DocsPricing | null {
250 const pricing = markdownSection(markdown, 'Pricing')
251 const rates: Record<string, number> = {}
252 const blocks = pricing.split('\n### ').slice(1)
253 // o3.md repeats `### Text tokens`: the first table is standard, the second
254 // is the half-price batch/flex table with no heading of its own. A later
255 // copy of a heading already priced is not the base rate, so it is dropped
256 // rather than overwriting it. Prompt-length tiers stay a separate shape.
257 const pricedHeadings = new Set<string>()
258 for (const block of blocks) {
259 const heading = block.split('\n')[0]?.trim() ?? ''
260 if (DERIVED_SECTIONS.has(heading)) continue
261 if (pricedHeadings.has(heading)) continue
262 pricedHeadings.add(heading)
263 if (UNIT_SECTIONS.has(heading)) {
264 // A model is billed one way: a page mixing token tables with a
265 // per-unit one is a shape this parser does not know.
266 if (blocks.length !== 1) return null
267 const unit = parseUnitSection(block)
268 return unit ? { rates: {}, tiers: [], unit } : null
269 }
270 const levers = PRICING_LEVERS[heading]
271 if (!levers) return null
272 for (const [metric = '', price, unit] of markdownTableRows(block)) {
273 if (metric === 'Metric') continue
274 const lever = levers[metric]
275 const rate = usd(price)
276 if (!lever || rate === null || unit !== '1M tokens') return null
277 rates[lever] = rate / 1e6
278 }
279 }
280 if (Object.keys(rates).length === 0) return null
281
282 const bullets = [...pricing.matchAll(/^- (.+)$/gm)].map(
283 ([, bullet = '']) => bullet,
284 )
285 const out: DocsPricing = { rates, tiers: [] }
286
287 // Rate-adding bullets first: a tier re-quotes whatever levers exist.
288 for (const bullet of bullets) {
289 // "Cache writes are billed at 1.25x the uncached input token rate."
290 const cacheWrite = bullet.match(
291 /cache writes are billed at ([\d.]+)x the uncached input token rate/i,
292 )
293 const input = rates.input_tokens
294 if (
295 cacheWrite?.[1] &&
296 input !== undefined &&
297 !('cache_write_tokens' in rates)
298 ) {
299 rates.cache_write_tokens = input * Number(cacheWrite[1])
300 }
301 // "…promotional pricing is available at least through November 21, 2026."
302 const promo = bullet.match(
303 /promotional pricing[^.]*through ([a-z]+ \d{1,2}, \d{4})/i,
304 )
305 if (promo?.[1]) {
306 const day = parseDay(promo[1])
307 if (day === null) return null
308 out.expiresAt = new Date(day + DAY_MS).toISOString()
309 }
310 }
311
312 for (const bullet of bullets) {
313 if (/cache writes are billed at|promotional pricing/i.test(bullet)) continue
314 // "Cached input tokens are priced at 10% of the uncached input token
315 // rate." GPT-6 Luna and Sol restate the Cached input row. A percentage
316 // that does not match that row is a different price, so the page refuses.
317 const cacheRead = bullet.match(
318 /cached input tokens are priced at ([\d.]+)% of the uncached input token rate/i,
319 )
320 if (cacheRead?.[1]) {
321 const input = rates.input_tokens
322 const factor = Number(cacheRead[1]) / 100
323 if (input === undefined || !Number.isFinite(factor)) return null
324 const expected = input * factor
325 const cached = rates.cache_read_tokens
326 if (cached === undefined) {
327 rates.cache_read_tokens = expected
328 } else if (Math.abs(cached - expected) > Math.abs(expected) * 1e-9) {
329 return null
330 }
331 continue
332 }
333 // "Prompts with >272K input tokens are priced at 2x input and 1.5x
334 // output for the full request" — a whole-request re-quote of every
335 // rate, which is exactly a tier.
336 const long = bullet.match(
337 /prompts with (?:more than |>)([\d,.]+\s*[km]?) input tokens are priced at ([\d.]+)x input(?: and cache rates)? and ([\d.]+)x output/i,
338 )
339 if (long) {
340 const threshold = tokenCount(long[1])
341 if (threshold === null) return null
342 const tier: Record<string, number> = {}
343 for (const [lever, rate] of Object.entries(rates)) {
344 const factor = INPUT_LEVERS.includes(lever)
345 ? Number(long[2])
346 : OUTPUT_LEVERS.includes(lever)
347 ? Number(long[3])
348 : null
349 // A lever the sentence does not cover would be quoted at the base
350 // rate inside the tier, which is a guess.
351 if (factor === null) return null
352 tier[lever] = rate * factor
353 }
354 out.tiers.push({ minPromptTokens: threshold, rates: tier })
355 continue
356 }
357 if (PROSE_BULLETS.test(bullet)) continue
358 // An unrecognised bullet that quotes money, a multiplier or a
359 // percentage may be a surcharge this card would drop.
360 if (/\$|\b\d+(\.\d+)?x\b|%/.test(bullet)) return null
361 }
362 return out
363}
364
365function listValues(block: string, label: string): Array<string> {
366 const match = block.match(new RegExp(`^- ${label}: (.+)$`, 'm'))
367 return match?.[1]
368 ? match[1].split(',').map((s) => s.trim().toLowerCase())
369 : []
370}
371
372/** Parse one model page's details, features and snapshot ids. */
373export function parseModelPage(markdown: string): OpenAiModelPage | null {
374 const modelId = markdown.match(/^Model ID: `([^`]+)`/m)?.[1]
375 if (!modelId) return null
376 const details = markdownSection(markdown, 'Model details')
377 const ids = new Set<string>([modelId])
378 const pricedIds = new Set<string>([modelId])
379 const snapshot = details.match(/^- Default snapshot: `([^`]+)`/m)?.[1]
380 if (snapshot) {
381 ids.add(snapshot)
382 pricedIds.add(snapshot)
383 }
384 for (const m of markdownSection(markdown, 'Snapshots').matchAll(
385 /^- `([^`]+)`/gm,
386 )) {
387 if (m[1]) ids.add(m[1])
388 }
389
390 const input = listValues(details, 'Input modalities')
391 const output = listValues(details, 'Output modalities')
392 const contextWindow = tokenCount(
393 details.match(/^- ([\d,]+) context window/m)?.[1],
394 )
395 const maxOutput = tokenCount(
396 details.match(/^- ([\d,]+) max output tokens/m)?.[1],
397 )
398
399 const features = new Set(
400 [
401 ...markdownSection(markdown, 'Supported features').matchAll(/^- (\S+)/gm),
402 ].map((m) => m[1] ?? ''),
403 )
404 const reasoning = /^- Reasoning token support/m.test(details)
405 const capabilities: Array<string> = []
406 if (features.has('function_calling')) capabilities.push('tools')
407 if (reasoning) capabilities.push('reasoning')
408 // Effort levels and sampling-param support appear only in prose on the
409 // page; neither is a field, so neither is asserted here.
410 if (features.has('structured_outputs')) {
411 capabilities.push('structured_outputs', 'response_format')
412 }
413
414 const serverTools = [
415 ...markdownSection(markdown, 'Supported tools').matchAll(/^- (\S+)/gm),
416 ].flatMap((m) => {
417 const type = RESPONSES_TOOL_TYPES[m[1] ?? '']
418 return type ? [type] : []
419 })
420
421 return {
422 ids: [...ids],
423 pricedIds: [...pricedIds],
424 pricing: parseModelPricing(markdown),
425 facts: {
426 contextWindow,
427 maxOutput,
428 modalities:
429 input.length > 0 || output.length > 0 ? { input, output } : null,
430 capabilities: capabilities.length > 0 ? capabilities : null,
431 reasoning: reasoning ? parseReasoningEffort(markdown) : null,
432 serverTools: serverTools.length > 0 ? serverTools : null,
433 },
434 }
435}
436
437/**
438 * "Supported tools" names → Responses API `tools[].type`. `function_calling`
439 * is a client tool and `skills` rides on `shell`; neither is a type.
440 */
441const RESPONSES_TOOL_TYPES: Record<string, string> = {
442 web_search: 'web_search',
443 file_search: 'file_search',
444 tool_search: 'tool_search',
445 image_generation: 'image_generation',
446 code_interpreter: 'code_interpreter',
447 hosted_shell: 'shell',
448 apply_patch: 'apply_patch',
449 computer_use: 'computer',
450 mcp: 'mcp',
451}
452
453const EFFORTS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']
454
455/**
456 * Effort levels from the page's prose: "Reasoning.effort supports: none
457 * (default), low, …" or "defaults to (and only supports) `reasoning.effort:
458 * high`". Reasoning is optional only when `none` is accepted. Without a
459 * native control declaration, its mode stays unknown; capability is separate.
460 */
461export function parseReasoningEffort(markdown: string): ModelReasoning | null {
462 const prose = markdown.replace(/```[\s\S]*?```/g, '')
463 const only = prose.match(
464 /only supports\)?\s*`reasoning\.effort:\s*([a-z]+)`/i,
465 )?.[1]
466 const list =
467 prose.match(
468 /(?:reasoning\.effort`?\s+supports:?|supports\s+`?reasoning\.effort`?:?)\s*([^.!]+?)(?=\.(?:\s|$)|\n\s*\n|$)/i,
469 ) ??
470 prose.match(
471 /supports\s+((?:`[a-z]+`[^.!]*?)+)\s+reasoning effort settings/i,
472 ) ??
473 prose.match(/Configurable reasoning effort:[^\n]*?\(([^)]+)\)/i)
474 const words = only
475 ? [only.toLowerCase()]
476 : (list?.[1]?.toLowerCase().match(/[a-z]+/g) ?? [])
477 const efforts = EFFORTS.filter((level) => words.includes(level))
478 if (!efforts.length) {
479 const explicitControl = prose.split('\n').some((line) => {
480 const declaration = line.match(
481 /^(.*?)\bsupports configurable reasoning effort\b/i,
482 )
483 return (
484 declaration !== null &&
485 !/\b(?:not|never|cannot|no)\b|doesn't/i.test(declaration[1] ?? '')
486 )
487 })
488 return explicitControl ? { mode: 'effort', mandatory: null } : null
489 }
490 return {
491 mode: 'effort',
492 mandatory: efforts.includes('none')
493 ? false
494 : /(?:reasoning|thinking)\s+(?:is\s+)?(?:cannot be disabled|always on|cannot be turned off)/i.test(
495 prose,
496 )
497 ? true
498 : null,
499 ...(efforts.length > 0 ? { efforts } : {}),
500 }
501}
502
503/**
504 * Model pages the models index no longer links, which still publish a price.
505 * Dated snapshots resolve to that page; `pricedIds` decides whether the
506 * price applies. A family page is never used for an id that is not that
507 * page's model id or its dated form (`tts-1-1106` is not `tts-1`).
508 */
509const UNINDEXED_MODEL_PAGES = new Set(['sora-2', 'sora-2-pro'])
510
511/** Page slug a listed id resolves to, or null when the docs have no page. */
512export function pageSlugFor(rawId: string, slugs: Set<string>): string | null {
513 if (slugs.has(rawId)) return rawId
514 const undated = undatedId(rawId)
515 if (slugs.has(undated)) return undated
516 if (UNINDEXED_MODEL_PAGES.has(rawId)) return rawId
517 if (UNINDEXED_MODEL_PAGES.has(undated)) return undated
518 return null
519}
520
521/**
522 * Facts for the listed ids. Pages are fetched once per slug and memoised;
523 * a page's snapshot list also seeds ids the index alone couldn't resolve.
524 */
525export async function openaiModelFacts(
526 rawIds: Array<string>,
527 kv?: KVNamespace,
528): Promise<(rawId: string) => ModelFacts> {
529 const slugs = new Set(
530 await cachedDocs(kv, OPENAI_MODELS_INDEX_URL, async () => {
531 const parsed = [
532 ...parseModelIndex(await fetchText(OPENAI_MODELS_INDEX_URL)),
533 ]
534 if (parsed.length === 0) {
535 throw new Error('openai models index: parsed 0 page slugs')
536 }
537 return parsed
538 }),
539 )
540 const needed = [
541 ...new Set(
542 rawIds
543 .map((id) => pageSlugFor(id, slugs))
544 .filter((slug): slug is string => slug !== null),
545 ),
546 ]
547 const searchDoc = await cachedDocs(kv, OPENAI_PRICING_URL, async () => {
548 const markdown = await fetchText(OPENAI_PRICING_URL)
549 const parsed = parseOpenAiSearchPricing(markdown)
550 assertParsed(parsed, 'openai pricing page search rows')
551 return {
552 rates: Object.fromEntries(parsed),
553 hash: await sha256Text(markdown),
554 extractedAt: new Date().toISOString(),
555 }
556 })
557 const pages = await mapConcurrent(needed, 8, async (slug) => {
558 const page = await cachedDocs(kv, OPENAI_MODEL_PAGE(slug), async () => {
559 const markdown = await fetchText(OPENAI_MODEL_PAGE(slug))
560 const parsed = parseModelPage(markdown)
561 if (!parsed) {
562 throw new Error(`openai model page ${slug}: no Model ID`)
563 }
564 // The card's provenance hashes the page as served, so an unchanged
565 // page keeps the stored card (and its `extractedAt`) on re-parse.
566 return {
567 ...parsed,
568 hash: await sha256Text(markdown),
569 extractedAt: new Date().toISOString(),
570 }
571 })
572 return { slug, page }
573 })
574 // A model's own page takes precedence over another alias page that names
575 // it as a default snapshot. Listing order must not erase native controls.
576 const primaryIds = new Set(pages.map((loaded) => loaded.page.ids[0]))
577 const byId = new Map<string, ModelFacts>()
578 for (const loaded of pages) {
579 const url = OPENAI_MODEL_PAGE(loaded.slug)
580 const withPricing: ModelFacts = {
581 ...loaded.page.facts,
582 pricing: loaded.page.pricing?.unit
583 ? compileUnitCard(loaded.page.pricing.unit, {
584 url,
585 hash: loaded.page.hash,
586 extractedAt: loaded.page.extractedAt,
587 })
588 : loaded.page.pricing
589 ? compileTokenCard(
590 loaded.page.pricing.rates,
591 loaded.page.pricing.tiers,
592 {
593 url,
594 hash: loaded.page.hash,
595 extractedAt: loaded.page.extractedAt,
596 ...(loaded.page.pricing.expiresAt && {
597 expiresAt: loaded.page.pricing.expiresAt,
598 }),
599 },
600 )
601 : null,
602 }
603 const facts: ModelFacts = {
604 ...withPricing,
605 factSources: tagDocsFacts(withPricing, url, loaded.page.hash),
606 }
607 const priced = new Set(loaded.page.pricedIds)
608 for (const id of loaded.page.ids) {
609 if (id !== loaded.page.ids[0] && primaryIds.has(id)) continue
610 if (priced.has(id)) {
611 byId.set(id, facts)
612 continue
613 }
614 // The family page prices the alias and the default snapshot only.
615 // An older snapshot (gpt-4o-2024-05-13) is not that price.
616 const sources = { ...facts.factSources }
617 delete sources.pricing
618 byId.set(id, { ...facts, pricing: null, factSources: sources })
619 }
620 }
621 const realtime = await openaiRealtimeEfforts(rawIds, kv)
622 if (realtime) {
623 const own = byId.get(realtime.rawId)
624 if (own?.reasoning?.mode === 'effort' && !own.reasoning.efforts?.length) {
625 byId.set(realtime.rawId, {
626 ...own,
627 reasoning: { ...own.reasoning, efforts: realtime.efforts },
628 factSources: {
629 ...own.factSources,
630 reasoning: {
631 derivation: 'docs-derived',
632 sourceUrl: OPENAI_REALTIME_EFFORT_URL,
633 sourceHash: realtime.hash,
634 path: 'Set reasoning effort',
635 },
636 },
637 })
638 }
639 }
640 if (needed.length > 0) assertParsed(byId, 'openai model pages')
641 return (rawId) => {
642 const exact = byId.get(rawId)
643 let facts: ModelFacts
644 if (exact) {
645 facts = exact
646 } else {
647 const familyId = undatedId(rawId)
648 const family = byId.get(familyId)
649 if (!family || familyId === rawId) {
650 facts = family ?? NO_FACTS
651 } else {
652 // The family page prices the alias and the default snapshot only.
653 const sources = { ...family.factSources }
654 delete sources.pricing
655 facts = { ...family, pricing: null, factSources: sources }
656 }
657 }
658 if (facts.pricing) return facts
659 // Exact id only. A dated snapshot is not the undated search row.
660 const rates = searchDoc.rates[rawId]
661 if (!rates) return facts
662 const pricing = compileTokenCard(rates, [], {
663 url: OPENAI_PRICING_URL,
664 hash: searchDoc.hash,
665 extractedAt: searchDoc.extractedAt,
666 })
667 if (!pricing) return facts
668 return {
669 ...facts,
670 pricing,
671 factSources: {
672 ...facts.factSources,
673 ...tagDocsFacts({ pricing }, OPENAI_PRICING_URL, searchDoc.hash),
674 },
675 }
676 }
677}