Open History to see the last commit
1/**
2 * NVIDIA NIM — ids from the provider's public models list, facts from each
3 * model's card on build.nvidia.com, and the per-model OpenAPI document on
4 * docs.api.nvidia.com when that model has a reference-index row.
5 *
6 * The list publishes id and created only. A card's markdown twin
7 * (`build.nvidia.com/<id>.md`) names the route in its Prototype section.
8 * Specifications and Capabilities are bullet lists on newer cards. Older
9 * cards use the same labels (`Input Type`, `Context length`, `Max Output
10 * Tokens`, a Reasoning Mode table) outside those lists. A reasoning object
11 * is stored only when a label or the model's own request schema states the
12 * control. NVIDIA publishes no per-token price for the hosted trial API.
13 */
14import { getJson, putJson } from '#/server/kv.ts'
15import { explicitCardReplay, replayRequestMap } from '../provider-replay.ts'
16import {
17 NVIDIA_SITEMAP_URL,
18 parseNvidiaInferSitemap,
19 nvidiaSitemapCandidates,
20} from '../nvidia-sitemap.ts'
21import type { Activity } from '#/db/schema.ts'
22
23import { tagDocsFacts } from '../fact-sources.ts'
24import {
25 assertParsed,
26 docsRun,
27 mapConcurrent,
28 markdownSection,
29 markdownTableRows,
30 tokenCount,
31 tryDocs,
32 unavailable,
33} from '../model-facts.ts'
34import type { DocsRun } from '../model-facts.ts'
35import { fetchJson, sha256Text } from '../types.ts'
36import type {
37 DocsFailures,
38 ListModelsResult,
39 ModelFact,
40 ModelInfo,
41 ModelReasoning,
42 ProviderConfig,
43 ProviderSecrets,
44 SpecFetchResult,
45} from '../types.ts'
46import {
47 classifyNvidiaOperation,
48 fetchNvidiaText,
49 nvidiaStatedModelIds,
50 NVIDIA_REFERENCE_INDEXES,
51 parseNvidiaInfer,
52 nvidiaWireFacts,
53 parseNvidiaReferenceIndex,
54} from '../nvidia-openapi.ts'
55import type { NvidiaIndexRow, NvidiaInferFacts } from '../nvidia-openapi.ts'
56
57import {
58 parseNvidiaBuildSpec,
59 nvidiaOwnedEndpoint,
60 validateNvidiaBuildFacts,
61} from '../nvidia-build-spec.ts'
62
63export const NVIDIA_MODELS_URL = 'https://integrate.api.nvidia.com/v1/models'
64export const NVIDIA_CARD_BASE = 'https://build.nvidia.com/'
65
66// A card renders in about ten seconds.
67const CARD_TIMEOUT_MS = 60_000
68const INFER_CONCURRENCY = 3
69
70const CAPABILITY_FLAGS: Record<string, string> = {
71 'Function Calling': 'tools',
72 'Structured Output': 'structured_outputs',
73 Reasoning: 'reasoning',
74}
75
76const MODALITY_WORDS = new Set(['text', 'image', 'video', 'audio'])
77
78const CARD_FACTS: Array<ModelFact> = [
79 'activity',
80 'contextWindow',
81 'maxOutput',
82 'modalities',
83 'capabilities',
84 'reasoning',
85]
86
87function isRecord(value: unknown): value is Record<string, unknown> {
88 return typeof value === 'object' && value !== null && !Array.isArray(value)
89}
90
91export function parseNvidiaModels(payload: unknown): Array<ModelInfo> {
92 if (!isRecord(payload) || !Array.isArray(payload.data)) {
93 throw new Error('nvidia: models payload has no data array')
94 }
95 const models: Array<ModelInfo> = []
96 for (const row of payload.data) {
97 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
98 continue
99 }
100 models.push({
101 rawId: row.id,
102 releasedAt:
103 typeof row.created === 'number' && row.created > 0 ? row.created : null,
104 pricing: null,
105 requestMap: null,
106 })
107 }
108 if (models.length === 0) {
109 throw new Error('nvidia: models payload listed no ids')
110 }
111 return models
112}
113
114type CardFacts = Pick<
115 ModelInfo,
116 | 'activity'
117 | 'contextWindow'
118 | 'maxOutput'
119 | 'modalities'
120 | 'capabilities'
121 | 'exactCapabilities'
122 | 'unsupportedCapabilities'
123 | 'reasoning'
124 | 'requestMap'
125>
126
127/** `- **Label:** value` lines of one card section. */
128function bullets(markdown: string, heading: string): Map<string, string> {
129 return new Map(
130 [
131 ...markdownSection(markdown, heading).matchAll(
132 /^- \*\*(.+?):\*\* (.+)$/gm,
133 ),
134 ].map((match) => [match[1] ?? '', (match[2] ?? '').trim()]),
135 )
136}
137
138/**
139 * `##` or `###` section. The heading is exactly that word (`Input(s):`),
140 * unless `loose` is set for a title that carries a parenthetical
141 * (`Reasoning Mode (`enable_thinking`)`).
142 */
143function cardSection(markdown: string, heading: string, loose = false): string {
144 const text = `\n${markdown}`
145 const tail = loose ? '[^\\n]*' : '(?:\\(s\\))?:?\\s*'
146 const headingMatch = new RegExp(
147 `(?:^|\\n)#{2,3} ${heading}${tail}\\n`,
148 'i',
149 ).exec(text)
150 if (headingMatch) {
151 const rest = text.slice(headingMatch.index + headingMatch[0].length)
152 const end = rest.search(/\n#{2,3} /)
153 return end < 0 ? rest : rest.slice(0, end)
154 }
155 // Older cards use a bold title (`**Input**`) instead of a heading.
156 if (loose) return ''
157 const boldMatch = new RegExp(
158 `(?:^|\\n)\\*\\*${heading}\\*\\*\\s*\\n`,
159 'i',
160 ).exec(text)
161 if (!boldMatch) return ''
162 const rest = text.slice(boldMatch.index + boldMatch[0].length)
163 const end = rest.search(/\n\*\*[A-Za-z][^*\n]*\*\*\s*(?:\n|$)/)
164 return end < 0 ? rest : rest.slice(0, end)
165}
166
167function labeledValue(
168 section: string,
169 labels: Array<string>,
170): string | undefined {
171 for (const label of labels) {
172 const match = new RegExp(
173 `(?:^|\\n)\\s*[-*]*\\s*\\*{0,2}${label}\\*{0,2}\\s*:\\s*\\*{0,2}\\s*([^\\n]+)`,
174 'i',
175 ).exec(section)
176 const value = match?.[1]?.replace(/<br\s*\/?>/gi, ' ').trim()
177 if (value) return value
178 }
179 return undefined
180}
181
182function modalityWords(cell: string | undefined): Array<string> {
183 if (!cell) return []
184 const cleaned = cell
185 .replace(/<br\s*\/?>/gi, ' ')
186 .replace(/\([^)]*\)/g, ' ')
187 .replace(/\[[^\]]*]/g, (item) => item.slice(1, -1))
188 const out: Array<string> = []
189 for (const part of cleaned.split(/[,/|+]|\band\b/i)) {
190 const word = part
191 .trim()
192 .toLowerCase()
193 .replace(/[^a-z]/g, '')
194 .replace(/s$/, '')
195 if (MODALITY_WORDS.has(word) && !out.includes(word)) out.push(word)
196 }
197 return out
198}
199
200function effortWords(text: string | undefined): Array<string> {
201 if (!text) return []
202 const out: Array<string> = []
203 for (const match of text
204 .toLowerCase()
205 .matchAll(/\b(none|off|disabled|minimal|low|medium|high|xhigh|max)\b/g)) {
206 const word = match[1]
207 if (word && !out.includes(word)) out.push(word)
208 }
209 return out
210}
211
212function contextWindowOf(markdown: string): number | undefined {
213 const specs = bullets(markdown, 'Specifications')
214 const fromSpecs = tokenCount(
215 specs.get('Context Length') ?? specs.get('Context window'),
216 )
217 if (fromSpecs) return fromSpecs
218 const input = cardSection(markdown, 'Input')
219 const labeled = [
220 tokenCount(labeledValue(input, ['Max Input Tokens'])),
221 tokenCount(
222 markdown.match(
223 /Input Context Length \(ISL\):\**\s*([\d,.]+\s*[kKmM]?)/,
224 )?.[1],
225 ),
226 tokenCount(labeledValue(markdown, ['Max Sequence Length'])),
227 tokenCount(
228 markdownTableRows(markdown).find((row) =>
229 /^context length$/i.test((row[0] ?? '').replace(/\*/g, '').trim()),
230 )?.[1],
231 ),
232 tokenCount(markdown.match(/\*\*Context window:\*\*\s*([^\n]+)/i)?.[1]),
233 tokenCount(
234 input.match(
235 /(?:^|\n)\s*[-*]\s+\*{0,2}Context length:\*{0,2}\s*([^\n]+)/i,
236 )?.[1],
237 ),
238 tokenCount(input.match(/Context length up to\s+([\d,.]+\s*[kKmM]?)/i)?.[1]),
239 tokenCount(
240 markdown.match(/context length of up to\s+([\d,.]+\s*[kKmM]?)/i)?.[1],
241 ),
242 ]
243 return labeled.find((value) => value !== null)
244}
245
246/** A format cell is a modality list only when every word is one. */
247function modalityCell(cell: string | undefined): Array<string> {
248 const words = modalityWords(cell)
249 if (!cell || words.length === 0) return []
250 const tokens = cell
251 .replace(/<br\s*\/?>/gi, ' ')
252 .replace(/\([^)]*\)/g, ' ')
253 .replace(/\[[^\]]*]/g, ' ')
254 .toLowerCase()
255 .split(/[^a-z]+/)
256 .filter((token) => token.length > 0)
257 .map((token) => token.replace(/s$/, ''))
258 if (tokens.some((token) => !MODALITY_WORDS.has(token))) return []
259 return words
260}
261
262const INPUT_TYPE_LABELS = ['Input Type\\(s\\)', 'Input Types', 'Input Type']
263const OUTPUT_TYPE_LABELS = ['Output Type\\(s\\)', 'Output Types', 'Output Type']
264const INPUT_FORMAT_LABELS = [
265 'Input Format\\(s\\)',
266 'Input Formats',
267 'Input Format',
268]
269const OUTPUT_FORMAT_LABELS = [
270 'Output Format\\(s\\)',
271 'Output Formats',
272 'Output Format',
273]
274
275function sideModalities(
276 specs: Map<string, string>,
277 specKey: string,
278 section: string,
279 typeLabels: Array<string>,
280 formatLabels: Array<string>,
281): Array<string> {
282 const fromSpecs = modalityWords(specs.get(specKey))
283 if (fromSpecs.length > 0) return fromSpecs
284 const typed = modalityWords(labeledValue(section, typeLabels))
285 if (typed.length > 0) return typed
286 // `String` and `RGB` are not modalities. A cell that is only
287 // text/image/video/audio is the older cards' type line.
288 return modalityCell(labeledValue(section, formatLabels))
289}
290
291function modalitiesOf(
292 markdown: string,
293): { input: Array<string>; output: Array<string> } | undefined {
294 const specs = bullets(markdown, 'Specifications')
295 const input = sideModalities(
296 specs,
297 'Input',
298 cardSection(markdown, 'Input'),
299 INPUT_TYPE_LABELS,
300 INPUT_FORMAT_LABELS,
301 )
302 const output = sideModalities(
303 specs,
304 'Output',
305 cardSection(markdown, 'Output'),
306 OUTPUT_TYPE_LABELS,
307 OUTPUT_FORMAT_LABELS,
308 )
309 if (input.length === 0 || output.length === 0) return undefined
310 return { input, output }
311}
312
313function maxOutputOf(markdown: string): number | undefined {
314 const match = cardSection(markdown, 'Output').match(
315 /\*\*Max Output Tokens:\*\*\s*([\d,]+(?:\.\d+)?\s*[kKmM]?)/,
316 )
317 return tokenCount(match?.[1]) ?? undefined
318}
319
320function reasoningFromCard(markdown: string): ModelReasoning | undefined {
321 for (const row of markdownTableRows(markdown)) {
322 const label = (row[0] ?? '').replace(/\*/g, '').trim()
323 const value = row[1] ?? ''
324 if (
325 /^reasoning mode$/i.test(label) &&
326 /enable_thinking/i.test(value) &&
327 /true/i.test(value) &&
328 /false/i.test(value)
329 ) {
330 return { mode: 'toggle', mandatory: false }
331 }
332 }
333 const prose = markdown.replace(/```[\s\S]*?```/g, '')
334 const modeSection = cardSection(prose, 'Reasoning Mode', true)
335 if (
336 /enable_thinking/i.test(modeSection) &&
337 /false/i.test(modeSection) &&
338 /true|on/i.test(modeSection)
339 ) {
340 return { mode: 'toggle', mandatory: false }
341 }
342 const listed =
343 effortWords(
344 prose.match(
345 /reasoning_effort`, which accepts ([\s\S]{0,200}?)(?:\.|and defaults)/,
346 )?.[1],
347 ).length > 0
348 ? effortWords(
349 prose.match(
350 /reasoning_effort`, which accepts ([\s\S]{0,200}?)(?:\.|and defaults)/,
351 )?.[1],
352 )
353 : effortWords(
354 prose.match(
355 /configurable\s+([^.\n]{0,80}?)\s+reasoning effort/i,
356 )?.[1],
357 ).length > 0
358 ? effortWords(
359 prose.match(
360 /configurable\s+([^.\n]{0,80}?)\s+reasoning effort/i,
361 )?.[1],
362 )
363 : effortWords(
364 prose.match(
365 /\*\*Configurable reasoning effort:\*\*[^\n]*\(([^)]+)\)/i,
366 )?.[1],
367 )
368 if (listed.length === 0) return undefined
369 const always =
370 /(?:^|[.!?]\s+)Thinking is always enabled(?:[.!:,]|\s+(?:for|when|in)\b)/im.test(
371 prose,
372 )
373 return {
374 mode: 'effort',
375 mandatory: always ? true : null,
376 efforts: listed,
377 }
378}
379
380function activityFromCard(markdown: string): Activity | null {
381 const prototype = markdownSection(`\n${markdown}`, 'Prototype')
382 if (prototype.includes('integrate.api.nvidia.com/v1/chat/completions')) {
383 return 'chat'
384 }
385 if (/api\.nvidia\.com\/v1\/\S*embeddings/.test(prototype)) return 'embeddings'
386 if (/integrate\.api\.nvidia\.com\/v1\/completions\b/.test(prototype)) {
387 return 'chat'
388 }
389 if (
390 /ai\.api\.nvidia\.com\/v1\/vlm\//.test(prototype) &&
391 /"role"\s*:\s*"user"/.test(prototype)
392 ) {
393 return 'chat'
394 }
395 const output = labeledValue(cardSection(markdown, 'Output'), [
396 'Output Type\\(s\\)',
397 'Output Types',
398 'Output Type',
399 ])
400 if (
401 output !== undefined &&
402 /\bfloat/i.test(output) &&
403 markdown.slice(0, 1500).toLowerCase().includes('embedding')
404 ) {
405 return 'embeddings'
406 }
407 return null
408}
409
410/** The facts one model card states. Absent sections leave their facts out. */
411export function parseNvidiaCard(markdown: string): CardFacts {
412 const capabilities = bullets(markdown, 'Capabilities')
413 const contextWindow = contextWindowOf(markdown)
414 const modalities = modalitiesOf(markdown)
415 const maxOutput = maxOutputOf(markdown)
416 const reasoning = reasoningFromCard(markdown)
417 return {
418 activity: activityFromCard(markdown),
419 ...(contextWindow !== undefined ? { contextWindow } : {}),
420 ...(maxOutput !== undefined ? { maxOutput } : {}),
421 ...(modalities ? { modalities } : {}),
422 ...(capabilities.size > 0
423 ? {
424 unsupportedCapabilities: [...capabilities].flatMap(
425 ([label, value]) => {
426 const flag = CAPABILITY_FLAGS[label]
427 return flag && /^(?:not supported|unsupported)$/i.test(value)
428 ? [flag]
429 : []
430 },
431 ),
432 capabilities: [...capabilities].flatMap(([label, value]) => {
433 const flag = CAPABILITY_FLAGS[label]
434 return flag && /^supported$/i.test(value) ? [flag] : []
435 }),
436 }
437 : {}),
438 ...(reasoning ? { reasoning } : {}),
439 ...(explicitCardReplay(markdown) ? { requestMap: replayRequestMap() } : {}),
440 }
441}
442
443/**
444 * Card slugs keep the id, or write its dots as `_` or `-`
445 * (`z-ai/glm-5.3` is at `z-ai/glm-5-3`). NVIDIA publishes no id-to-slug
446 * map, so try each; a listed id with no card gets no facts.
447 */
448function cardSlugs(rawId: string): Array<string> {
449 return [
450 ...new Set([rawId, rawId.replaceAll('.', '_'), rawId.replaceAll('.', '-')]),
451 ]
452}
453
454async function fetchCard(
455 rawId: string,
456): Promise<{ url: string; markdown: string; hash: string } | { url: null }> {
457 for (const slug of cardSlugs(rawId)) {
458 const url = `${NVIDIA_CARD_BASE}${slug}`
459 // Providers poll in sequence; a hung card must not stall the rest.
460 const response = await fetch(`${url}.md`, {
461 signal: AbortSignal.timeout(CARD_TIMEOUT_MS),
462 })
463 if (response.status === 404) continue
464 if (!response.ok) {
465 throw new Error(
466 `fetch failed: ${url}.md → ${String(response.status)} ${response.statusText}`,
467 )
468 }
469 const markdown = await response.text()
470 if (!markdown.startsWith('---\n')) {
471 // Some cards have no markdown twin: the site answers 200 with its
472 // HTML not-found page. Any other body is a failed load, never a card.
473 if (markdown.includes('NEXT_HTTP_ERROR_FALLBACK;404')) continue
474 throw new Error(`nvidia: ${url}.md is not a markdown card`)
475 }
476 // The slug is a guess, so the card must name itself as that page.
477 if (!markdown.includes(`\ncanonical: "${url}"\n`)) continue
478 return { url, markdown, hash: await sha256Text(markdown) }
479 }
480 return { url: null }
481}
482
483async function readBuildPage(url: string) {
484 const response = await fetch(url, {
485 headers: { accept: 'text/html' },
486 signal: AbortSignal.timeout(CARD_TIMEOUT_MS),
487 })
488 const html = await response.text()
489 if (!response.ok && response.status !== 404)
490 throw new Error(
491 `fetch failed: ${url} → ${String(response.status)} ${response.statusText}`,
492 )
493 return { html, absent: response.status === 404 }
494}
495function buildContract(page: { html: string; absent: boolean }, rawId: string) {
496 return page.absent ? null : parseNvidiaBuildSpec(page.html, rawId)
497}
498/** Only network failures consume the host failure budget; rejected content remains visible. */
499async function loadBuildContract(
500 kv: KVNamespace | undefined,
501 run: DocsRun,
502 url: string,
503 rawId: string,
504) {
505 const key = `nvidia-build-contract:v1:${url}`
506 const hit = kv
507 ? await getJson<{ infer: NvidiaInferFacts | null; hash: string }>(kv, key)
508 : null
509 if (hit !== null)
510 return tryDocs(run, url, async () => {
511 if (typeof hit.hash !== 'string' || !/^[a-f0-9]{64}$/.test(hit.hash))
512 throw new Error('nvidia Build: cached source hash missing')
513 return {
514 infer:
515 hit.infer === null
516 ? null
517 : validateNvidiaBuildFacts(hit.infer, rawId),
518 hash: hit.hash,
519 }
520 })
521 const page = await tryDocs(run, url, (cached) =>
522 cached(undefined, key, () => readBuildPage(url)),
523 )
524 if (page === null) return null
525 const contract = await tryDocs(run, url, async () => ({
526 infer: buildContract(page, rawId),
527 hash: await sha256Text(page.html),
528 }))
529 if (contract !== null && kv)
530 await putJson(kv, key, contract, { expirationTtl: 6 * 60 * 60 })
531 return contract
532}
533
534function mergeDocs(runs: Array<DocsRun>): DocsFailures {
535 const failed = runs.reduce((sum, run) => sum + run.failed, 0)
536 const skipped = runs.reduce((sum, run) => sum + run.skipped, 0)
537 return {
538 failed,
539 skipped,
540 first: runs.flatMap((run) => run.first).slice(0, 5),
541 }
542}
543
544function markUnavailable(model: ModelInfo, facts: Array<ModelFact>): ModelInfo {
545 if (facts.length === 0) return model
546 return {
547 ...model,
548 absent: {
549 ...model.absent,
550 ...Object.fromEntries(facts.map((fact) => [fact, 'unavailable'])),
551 },
552 }
553}
554
555/**
556 * The card's labeled control stays when this model's schema agrees. An
557 * off value in the schema (`none`) replaces a card that did not state one.
558 * A card that says thinking is always on sets `mandatory` on the same
559 * effort list. Otherwise the schema is the request contract.
560 */
561function mergeReasoning(
562 card: ModelReasoning | undefined,
563 schema: ModelReasoning | undefined,
564): { reasoning: ModelReasoning; source: 'card' | 'schema' } | undefined {
565 if (schema && card) {
566 if (schema.mandatory === false && card.mandatory !== false) {
567 return { reasoning: schema, source: 'schema' }
568 }
569 if (
570 card.mandatory === true &&
571 schema.mode === card.mode &&
572 schema.mandatory == null
573 ) {
574 return {
575 reasoning: { ...schema, mandatory: true },
576 source: 'card',
577 }
578 }
579 if (card.mode === schema.mode) return { reasoning: card, source: 'card' }
580 return { reasoning: schema, source: 'schema' }
581 }
582 if (schema) return { reasoning: schema, source: 'schema' }
583 if (card) return { reasoning: card, source: 'card' }
584 return undefined
585}
586
587const SCHEMA_GAPS: Array<ModelFact> = [
588 'maxOutput',
589 'reasoning',
590 'schemaEndpointId',
591]
592
593function schemaGaps(model: ModelInfo): Array<ModelFact> {
594 return SCHEMA_GAPS.filter((fact) => model[fact] == null)
595}
596
597function clearAbsent(model: ModelInfo, facts: Array<ModelFact>): ModelInfo {
598 if (!model.absent) return model
599 const absent = { ...model.absent }
600 for (const fact of facts) delete absent[fact]
601 if (Object.keys(absent).length === 0) {
602 const { absent: _dropped, ...rest } = model
603 return rest
604 }
605 return { ...model, absent }
606}
607
608function applyInfer(
609 model: ModelInfo,
610 infer: NvidiaInferFacts,
611 inferUrl: string,
612 inferHash: string,
613): ModelInfo {
614 const nativeCapabilities =
615 model.capabilities == null ? [] : model.capabilities
616 if (
617 !Array.isArray(nativeCapabilities) ||
618 !nativeCapabilities.every((value) => typeof value === 'string')
619 )
620 throw new Error('nvidia: invalid native capability list')
621 if (infer.reasoning && model.unsupportedCapabilities?.includes('reasoning'))
622 throw new Error(
623 'nvidia: native card explicitly rejects reasoning but its schema publishes a reasoning control',
624 )
625 const reasoning = mergeReasoning(
626 model.reasoning ?? undefined,
627 infer.reasoning,
628 )
629 const maxFromSchema = infer.maxOutput !== undefined
630 const activity = model.activity ?? infer.activity
631 const bind =
632 infer.activity !== null &&
633 (model.activity == null || model.activity === infer.activity)
634 const factSources = { ...model.factSources }
635 const schemaSource = {
636 derivation: 'docs-derived' as const,
637 sourceUrl: inferUrl,
638 sourceHash: inferHash,
639 }
640 if (maxFromSchema)
641 factSources.maxOutput = { ...schemaSource, path: infer.maxOutputField }
642 if (reasoning?.source === 'schema') {
643 factSources.reasoning = { ...schemaSource, path: infer.reasoningField }
644 }
645 if (infer.reasoning)
646 factSources.capabilities = {
647 ...factSources.capabilities,
648 reasoning: { ...schemaSource, path: infer.reasoningField },
649 }
650 if (bind) factSources.schemaEndpointId = { ...schemaSource, path: 'paths' }
651 const wire = nvidiaWireFacts(infer.document)
652 const wireMap =
653 model.requestMap ??
654 (Object.keys(wire.fields).length
655 ? {
656 thinking: null,
657 maxTokensField: null,
658 developerRole: null,
659 replayReasoningContent: null,
660 store: null,
661 strictTools: null,
662 sessionAffinity: null,
663 cacheControl: null,
664 toolStream: null,
665 reasoningEffort: null,
666 }
667 : null)
668 if (Object.keys(wire.paths).length)
669 factSources.requestMapFields = {
670 ...factSources.requestMapFields,
671 ...Object.fromEntries(
672 Object.entries(wire.paths).map(([key, path]) => [
673 key,
674 { ...schemaSource, path },
675 ]),
676 ),
677 }
678 const filled: Array<ModelFact> = []
679 if (activity && model.activity == null) filled.push('activity')
680 if (maxFromSchema) filled.push('maxOutput')
681 if (reasoning) filled.push('reasoning')
682 if (bind) filled.push('schemaEndpointId')
683 return clearAbsent(
684 {
685 ...model,
686 ...(activity ? { activity } : {}),
687 requestMap: wireMap ? { ...wireMap, ...wire.fields } : null,
688 ...(infer.reasoning
689 ? {
690 capabilities: [...new Set([...nativeCapabilities, 'reasoning'])],
691 }
692 : {}),
693 ...(maxFromSchema ? { maxOutput: infer.maxOutput } : {}),
694 ...(reasoning ? { reasoning: reasoning.reasoning } : {}),
695 ...(bind ? { schemaEndpointId: model.rawId } : {}),
696 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
697 },
698 filled,
699 )
700}
701
702async function loadIndex(
703 kv: KVNamespace | undefined,
704 docs: DocsRun,
705): Promise<{ rows: Array<NvidiaIndexRow>; failed: boolean }> {
706 const loaded = await mapConcurrent(NVIDIA_REFERENCE_INDEXES, 1, async (url) =>
707 tryDocs(docs, url, (cached) => cached(kv, url, () => fetchNvidiaText(url))),
708 )
709 const rows: Array<NvidiaIndexRow> = []
710 const seen = new Set<string>()
711 let parsed = 0
712 for (const markdown of loaded) {
713 if (markdown === null) continue
714 parsed++
715 for (const row of parseNvidiaReferenceIndex(markdown)) {
716 if (seen.has(row.rawId)) continue
717 seen.add(row.rawId)
718 rows.push(row)
719 }
720 }
721 return { rows, failed: parsed !== NVIDIA_REFERENCE_INDEXES.length }
722}
723
724interface OwnedContract {
725 infer: NvidiaInferFacts
726 url: string
727 hash: string
728}
729/** ReadMe discovery uses actual published index/sitemap paths, never fabricated routes. */
730async function chooseNativeContracts(
731 models: ModelInfo[],
732 cardUrl: (rawId: string) => Promise<string | null>,
733 run: DocsRun,
734 kv?: KVNamespace,
735) {
736 const diagnostics: string[] = []
737 const index = await loadIndex(kv, run)
738 const indexed = new Map(index.rows.map((row) => [row.rawId, row.inferUrl]))
739 const missing = models.filter((row) => !indexed.has(row.rawId))
740 const sitemap = missing.length
741 ? await tryDocs(run, NVIDIA_SITEMAP_URL, (cached) =>
742 cached(kv, NVIDIA_SITEMAP_URL, async () =>
743 parseNvidiaInferSitemap(await fetchNvidiaText(NVIDIA_SITEMAP_URL)),
744 ),
745 )
746 : []
747 const selected = new Map<string, OwnedContract>()
748 const unavailableIds = new Set<string>()
749 await mapConcurrent(models, INFER_CONCURRENCY, async (model) => {
750 const linked = indexed.get(model.rawId)
751 if (!linked && sitemap === null) {
752 unavailableIds.add(model.rawId)
753 return
754 }
755 const candidates = linked
756 ? [linked]
757 : nvidiaSitemapCandidates(model.rawId, sitemap ?? [])
758 if (!candidates.length && index.failed) {
759 unavailableIds.add(model.rawId)
760 return
761 }
762 const conflicts: string[] = []
763 for (const candidate of candidates) {
764 const page = candidate + '.md'
765 const markdown = await tryDocs(run, page, (cached) =>
766 cached(kv, page, () => fetchNvidiaText(page)),
767 )
768 if (markdown === null) {
769 unavailableIds.add(model.rawId)
770 return
771 }
772 const infer = await tryDocs(run, page, async () => {
773 const facts = parseNvidiaInfer(markdown)
774 if (!facts)
775 throw new Error(
776 'nvidia: published reference infer page has no OpenAPI document readable: ' +
777 page,
778 )
779 return facts
780 })
781 if (infer === null) {
782 unavailableIds.add(model.rawId)
783 return
784 }
785 const ids = nvidiaStatedModelIds(infer.document)
786 const exact = ids.length === 1 && ids[0] === model.rawId
787 // An explicit native index row can bind a document that states no IDs.
788 if (exact || (linked && ids.length === 0)) {
789 selected.set(model.rawId, {
790 infer,
791 url: page,
792 hash: await sha256Text(markdown),
793 })
794 return
795 }
796 conflicts.push(
797 `nvidia: rejected competing reference identity conflict: ${page}; expected ${model.rawId}; stated ${ids.join(', ')}`,
798 )
799 }
800 diagnostics.push(...conflicts)
801 const url = await tryDocs(
802 run,
803 'nvidia Build card discovery: ' + model.rawId,
804 async () => cardUrl(model.rawId),
805 )
806 if (url === null) {
807 if (conflicts.length) {
808 await tryDocs(run, candidates[0] + '.md', async () => {
809 throw new Error(conflicts.join('; '))
810 })
811 unavailableIds.add(model.rawId)
812 }
813 return
814 }
815 const build = await loadBuildContract(kv, run, url, model.rawId)
816 if (build === null) {
817 unavailableIds.add(model.rawId)
818 return
819 }
820 if (build.infer)
821 selected.set(model.rawId, { ...build, infer: build.infer, url })
822 else if (conflicts.length) {
823 await tryDocs(run, candidates[0] + '.md', async () => {
824 throw new Error(conflicts.join('; '))
825 })
826 unavailableIds.add(model.rawId)
827 }
828 })
829 return { selected, unavailableIds, diagnostics }
830}
831
832async function listModels(
833 _env: ProviderSecrets,
834 kv?: KVNamespace,
835): Promise<ListModelsResult> {
836 const listed = parseNvidiaModels(await fetchJson(NVIDIA_MODELS_URL))
837 const cardDocs = docsRun()
838 const specDocs = docsRun()
839 const cardUrls = new Map<string, string>()
840 // A card takes about ten seconds to render. The six-hour cache per card
841 // (misses included) keeps that off most polls.
842 // A card that fails to load is that model's alone: its row keeps the
843 // stored card facts and the next poll retries.
844 const models = await mapConcurrent(
845 listed,
846 8,
847 async (model): Promise<ModelInfo> => {
848 const source = `${NVIDIA_CARD_BASE}${model.rawId}.md`
849 const card = await tryDocs(cardDocs, source, (cached) =>
850 cached(kv, source, () => fetchCard(model.rawId)),
851 )
852 // A throw keeps stored card facts. A missing card is not a failure.
853 if (card === null) return { ...model, ...unavailable(...CARD_FACTS) }
854 if (card.url === null) return model
855 cardUrls.set(model.rawId, card.url)
856 const facts = parseNvidiaCard(card.markdown)
857 const factSources = tagDocsFacts(facts, card.url, card.hash)
858 for (const flag of facts.unsupportedCapabilities ?? []) {
859 factSources.capabilities = {
860 ...factSources.capabilities,
861 [flag]: {
862 derivation: 'docs-derived',
863 sourceUrl: card.url,
864 sourceHash: card.hash,
865 path: `capabilities.${flag}`,
866 },
867 }
868 }
869 return {
870 ...model,
871 ...facts,
872 factSources,
873 }
874 },
875 )
876 const choices = await chooseNativeContracts(
877 models,
878 async (rawId) => cardUrls.get(rawId) ?? null,
879 specDocs,
880 kv,
881 )
882 const merged = await mapConcurrent(
883 models,
884 INFER_CONCURRENCY,
885 async (model) => {
886 if (choices.unavailableIds.has(model.rawId))
887 return markUnavailable(model, schemaGaps(model))
888 const own = choices.selected.get(model.rawId)
889 if (!own) return model
890 const applied = await tryDocs(specDocs, own.url, async () =>
891 applyInfer(model, own.infer, own.url, own.hash),
892 )
893 return applied ?? markUnavailable(model, schemaGaps(model))
894 },
895 )
896 const parsed = new Map(
897 merged.flatMap((model) => (model.activity ? [[model.rawId, model]] : [])),
898 )
899 // Zero rows with every card loaded is a reshaped site. With cards
900 // failing it is the outage `docsFailures` already reports.
901 if (parsed.size > 0 || cardDocs.failed + cardDocs.skipped === 0) {
902 assertParsed(parsed, 'nvidia model cards')
903 }
904 return { models: merged, docsFailures: mergeDocs([cardDocs, specDocs]) }
905}
906
907async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
908 const run = docsRun()
909 const listed = parseNvidiaModels(await fetchJson(NVIDIA_MODELS_URL))
910 const choices = await chooseNativeContracts(
911 listed,
912 async (rawId) => (await fetchCard(rawId)).url,
913 run,
914 )
915 const warnings = [
916 ...choices.diagnostics,
917 ...run.first.map((failure) => `${failure.source}: ${failure.error}`),
918 ]
919 const endpoints = [...choices.selected].flatMap(([rawId, own]) => {
920 const result = nvidiaOwnedEndpoint(rawId, own.infer, {
921 url: own.url,
922 hash: own.hash,
923 })
924 if (!result) return []
925 warnings.push(...result.warnings)
926 return [result.endpoint]
927 })
928 if (!endpoints.length)
929 throw new Error(
930 'nvidia: native per-model documents parsed 0 generation specs; ' +
931 warnings.join('; '),
932 )
933 return {
934 specs: [],
935 sources: [],
936 bundledEndpoints: endpoints,
937 outputStrategy: 'post-200',
938 ...(warnings.length ? { warnings } : {}),
939 }
940}
941
942export const provider: ProviderConfig = {
943 id: 'nvidia',
944 displayName: 'NVIDIA NIM',
945 specSourceUrl: 'https://docs.api.nvidia.com/nim/',
946 modelsEndpoint: NVIDIA_MODELS_URL,
947 defaultDerivation: 'upstream-spec',
948 // A poll can name a per-model route the spec sync has not stored yet.
949 bindSyncedRoutesOnly: true,
950 specGrain: 'model',
951 fetchSpec,
952 listModels,
953 classify: classifyNvidiaOperation,
954}