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 | undefined {
535 const failed = runs.reduce((sum, run) => sum + run.failed, 0)
536 const skipped = runs.reduce((sum, run) => sum + run.skipped, 0)
537 if (failed + skipped === 0) return undefined
538 return {
539 failed,
540 skipped,
541 first: runs.flatMap((run) => run.first).slice(0, 5),
542 }
543}
544
545function markUnavailable(model: ModelInfo, facts: Array<ModelFact>): ModelInfo {
546 if (facts.length === 0) return model
547 return {
548 ...model,
549 absent: {
550 ...model.absent,
551 ...Object.fromEntries(facts.map((fact) => [fact, 'unavailable'])),
552 },
553 }
554}
555
556/**
557 * The card's labeled control stays when this model's schema agrees. An
558 * off value in the schema (`none`) replaces a card that did not state one.
559 * A card that says thinking is always on sets `mandatory` on the same
560 * effort list. Otherwise the schema is the request contract.
561 */
562function mergeReasoning(
563 card: ModelReasoning | undefined,
564 schema: ModelReasoning | undefined,
565): { reasoning: ModelReasoning; source: 'card' | 'schema' } | undefined {
566 if (schema && card) {
567 if (schema.mandatory === false && card.mandatory !== false) {
568 return { reasoning: schema, source: 'schema' }
569 }
570 if (
571 card.mandatory === true &&
572 schema.mode === card.mode &&
573 schema.mandatory == null
574 ) {
575 return {
576 reasoning: { ...schema, mandatory: true },
577 source: 'card',
578 }
579 }
580 if (card.mode === schema.mode) return { reasoning: card, source: 'card' }
581 return { reasoning: schema, source: 'schema' }
582 }
583 if (schema) return { reasoning: schema, source: 'schema' }
584 if (card) return { reasoning: card, source: 'card' }
585 return undefined
586}
587
588const SCHEMA_GAPS: Array<ModelFact> = [
589 'maxOutput',
590 'reasoning',
591 'schemaEndpointId',
592]
593
594function schemaGaps(model: ModelInfo): Array<ModelFact> {
595 return SCHEMA_GAPS.filter((fact) => model[fact] == null)
596}
597
598function clearAbsent(model: ModelInfo, facts: Array<ModelFact>): ModelInfo {
599 if (!model.absent) return model
600 const absent = { ...model.absent }
601 for (const fact of facts) delete absent[fact]
602 if (Object.keys(absent).length === 0) {
603 const { absent: _dropped, ...rest } = model
604 return rest
605 }
606 return { ...model, absent }
607}
608
609function applyInfer(
610 model: ModelInfo,
611 infer: NvidiaInferFacts,
612 inferUrl: string,
613 inferHash: string,
614): ModelInfo {
615 const nativeCapabilities =
616 model.capabilities == null ? [] : model.capabilities
617 if (
618 !Array.isArray(nativeCapabilities) ||
619 !nativeCapabilities.every((value) => typeof value === 'string')
620 )
621 throw new Error('nvidia: invalid native capability list')
622 if (infer.reasoning && model.unsupportedCapabilities?.includes('reasoning'))
623 throw new Error(
624 'nvidia: native card explicitly rejects reasoning but its schema publishes a reasoning control',
625 )
626 const reasoning = mergeReasoning(
627 model.reasoning ?? undefined,
628 infer.reasoning,
629 )
630 const maxFromSchema = infer.maxOutput !== undefined
631 const activity = model.activity ?? infer.activity
632 const bind =
633 infer.activity !== null &&
634 (model.activity == null || model.activity === infer.activity)
635 const factSources = { ...model.factSources }
636 const schemaSource = {
637 derivation: 'docs-derived' as const,
638 sourceUrl: inferUrl,
639 sourceHash: inferHash,
640 }
641 if (maxFromSchema)
642 factSources.maxOutput = { ...schemaSource, path: infer.maxOutputField }
643 if (reasoning?.source === 'schema') {
644 factSources.reasoning = { ...schemaSource, path: infer.reasoningField }
645 }
646 if (infer.reasoning)
647 factSources.capabilities = {
648 ...factSources.capabilities,
649 reasoning: { ...schemaSource, path: infer.reasoningField },
650 }
651 if (bind) factSources.schemaEndpointId = { ...schemaSource, path: 'paths' }
652 const wire = nvidiaWireFacts(infer.document)
653 const wireMap =
654 model.requestMap ??
655 (Object.keys(wire.fields).length
656 ? {
657 thinking: null,
658 maxTokensField: null,
659 developerRole: null,
660 replayReasoningContent: null,
661 store: null,
662 strictTools: null,
663 sessionAffinity: null,
664 cacheControl: null,
665 toolStream: null,
666 reasoningEffort: null,
667 }
668 : null)
669 if (Object.keys(wire.paths).length)
670 factSources.requestMapFields = {
671 ...factSources.requestMapFields,
672 ...Object.fromEntries(
673 Object.entries(wire.paths).map(([key, path]) => [
674 key,
675 { ...schemaSource, path },
676 ]),
677 ),
678 }
679 const filled: Array<ModelFact> = []
680 if (activity && model.activity == null) filled.push('activity')
681 if (maxFromSchema) filled.push('maxOutput')
682 if (reasoning) filled.push('reasoning')
683 if (bind) filled.push('schemaEndpointId')
684 return clearAbsent(
685 {
686 ...model,
687 ...(activity ? { activity } : {}),
688 requestMap: wireMap ? { ...wireMap, ...wire.fields } : null,
689 ...(infer.reasoning
690 ? {
691 capabilities: [...new Set([...nativeCapabilities, 'reasoning'])],
692 }
693 : {}),
694 ...(maxFromSchema ? { maxOutput: infer.maxOutput } : {}),
695 ...(reasoning ? { reasoning: reasoning.reasoning } : {}),
696 ...(bind ? { schemaEndpointId: model.rawId } : {}),
697 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
698 },
699 filled,
700 )
701}
702
703async function loadIndex(
704 kv: KVNamespace | undefined,
705 docs: DocsRun,
706): Promise<{ rows: Array<NvidiaIndexRow>; failed: boolean }> {
707 const loaded = await mapConcurrent(NVIDIA_REFERENCE_INDEXES, 1, async (url) =>
708 tryDocs(docs, url, (cached) => cached(kv, url, () => fetchNvidiaText(url))),
709 )
710 const rows: Array<NvidiaIndexRow> = []
711 const seen = new Set<string>()
712 let parsed = 0
713 for (const markdown of loaded) {
714 if (markdown === null) continue
715 parsed++
716 for (const row of parseNvidiaReferenceIndex(markdown)) {
717 if (seen.has(row.rawId)) continue
718 seen.add(row.rawId)
719 rows.push(row)
720 }
721 }
722 return { rows, failed: parsed !== NVIDIA_REFERENCE_INDEXES.length }
723}
724
725interface OwnedContract {
726 infer: NvidiaInferFacts
727 url: string
728 hash: string
729}
730/** ReadMe discovery uses actual published index/sitemap paths, never fabricated routes. */
731async function chooseNativeContracts(
732 models: ModelInfo[],
733 cardUrl: (rawId: string) => Promise<string | null>,
734 run: DocsRun,
735 kv?: KVNamespace,
736) {
737 const diagnostics: string[] = []
738 const index = await loadIndex(kv, run)
739 const indexed = new Map(index.rows.map((row) => [row.rawId, row.inferUrl]))
740 const missing = models.filter((row) => !indexed.has(row.rawId))
741 const sitemap = missing.length
742 ? await tryDocs(run, NVIDIA_SITEMAP_URL, (cached) =>
743 cached(kv, NVIDIA_SITEMAP_URL, async () =>
744 parseNvidiaInferSitemap(await fetchNvidiaText(NVIDIA_SITEMAP_URL)),
745 ),
746 )
747 : []
748 const selected = new Map<string, OwnedContract>()
749 const unavailableIds = new Set<string>()
750 await mapConcurrent(models, INFER_CONCURRENCY, async (model) => {
751 const linked = indexed.get(model.rawId)
752 if (!linked && sitemap === null) {
753 unavailableIds.add(model.rawId)
754 return
755 }
756 const candidates = linked
757 ? [linked]
758 : nvidiaSitemapCandidates(model.rawId, sitemap ?? [])
759 if (!candidates.length && index.failed) {
760 unavailableIds.add(model.rawId)
761 return
762 }
763 const conflicts: string[] = []
764 for (const candidate of candidates) {
765 const page = candidate + '.md'
766 const markdown = await tryDocs(run, page, (cached) =>
767 cached(kv, page, () => fetchNvidiaText(page)),
768 )
769 if (markdown === null) {
770 unavailableIds.add(model.rawId)
771 return
772 }
773 const infer = await tryDocs(run, page, async () => {
774 const facts = parseNvidiaInfer(markdown)
775 if (!facts)
776 throw new Error(
777 'nvidia: published reference infer page has no OpenAPI document readable: ' +
778 page,
779 )
780 return facts
781 })
782 if (infer === null) {
783 unavailableIds.add(model.rawId)
784 return
785 }
786 const ids = nvidiaStatedModelIds(infer.document)
787 const exact = ids.length === 1 && ids[0] === model.rawId
788 // An explicit native index row can bind a document that states no IDs.
789 if (exact || (linked && ids.length === 0)) {
790 selected.set(model.rawId, {
791 infer,
792 url: page,
793 hash: await sha256Text(markdown),
794 })
795 return
796 }
797 conflicts.push(
798 `nvidia: rejected competing reference identity conflict: ${page}; expected ${model.rawId}; stated ${ids.join(', ')}`,
799 )
800 }
801 diagnostics.push(...conflicts)
802 const url = await tryDocs(
803 run,
804 'nvidia Build card discovery: ' + model.rawId,
805 async () => cardUrl(model.rawId),
806 )
807 if (url === null) {
808 if (conflicts.length) {
809 await tryDocs(run, candidates[0] + '.md', async () => {
810 throw new Error(conflicts.join('; '))
811 })
812 unavailableIds.add(model.rawId)
813 }
814 return
815 }
816 const build = await loadBuildContract(kv, run, url, model.rawId)
817 if (build === null) {
818 unavailableIds.add(model.rawId)
819 return
820 }
821 if (build.infer)
822 selected.set(model.rawId, { ...build, infer: build.infer, url })
823 else if (conflicts.length) {
824 await tryDocs(run, candidates[0] + '.md', async () => {
825 throw new Error(conflicts.join('; '))
826 })
827 unavailableIds.add(model.rawId)
828 }
829 })
830 return { selected, unavailableIds, diagnostics }
831}
832
833async function listModels(
834 _env: ProviderSecrets,
835 kv?: KVNamespace,
836): Promise<ListModelsResult> {
837 const listed = parseNvidiaModels(await fetchJson(NVIDIA_MODELS_URL))
838 const cardDocs = docsRun()
839 const specDocs = docsRun()
840 const cardUrls = new Map<string, string>()
841 // A card takes about ten seconds to render. The six-hour cache per card
842 // (misses included) keeps that off most polls.
843 // A card that fails to load is that model's alone: its row keeps the
844 // stored card facts and the next poll retries.
845 const models = await mapConcurrent(
846 listed,
847 8,
848 async (model): Promise<ModelInfo> => {
849 const source = `${NVIDIA_CARD_BASE}${model.rawId}.md`
850 const card = await tryDocs(cardDocs, source, (cached) =>
851 cached(kv, source, () => fetchCard(model.rawId)),
852 )
853 // A throw keeps stored card facts. A missing card is not a failure.
854 if (card === null) return { ...model, ...unavailable(...CARD_FACTS) }
855 if (card.url === null) return model
856 cardUrls.set(model.rawId, card.url)
857 const facts = parseNvidiaCard(card.markdown)
858 const factSources = tagDocsFacts(facts, card.url, card.hash)
859 for (const flag of facts.unsupportedCapabilities ?? []) {
860 factSources.capabilities = {
861 ...factSources.capabilities,
862 [flag]: {
863 derivation: 'docs-derived',
864 sourceUrl: card.url,
865 sourceHash: card.hash,
866 path: `capabilities.${flag}`,
867 },
868 }
869 }
870 return {
871 ...model,
872 ...facts,
873 factSources,
874 }
875 },
876 )
877 const choices = await chooseNativeContracts(
878 models,
879 async (rawId) => cardUrls.get(rawId) ?? null,
880 specDocs,
881 kv,
882 )
883 const merged = await mapConcurrent(
884 models,
885 INFER_CONCURRENCY,
886 async (model) => {
887 if (choices.unavailableIds.has(model.rawId))
888 return markUnavailable(model, schemaGaps(model))
889 const own = choices.selected.get(model.rawId)
890 if (!own) return model
891 const applied = await tryDocs(specDocs, own.url, async () =>
892 applyInfer(model, own.infer, own.url, own.hash),
893 )
894 return applied ?? markUnavailable(model, schemaGaps(model))
895 },
896 )
897 const parsed = new Map(
898 merged.flatMap((model) => (model.activity ? [[model.rawId, model]] : [])),
899 )
900 // Zero rows with every card loaded is a reshaped site. With cards
901 // failing it is the outage `docsFailures` already reports.
902 if (parsed.size > 0 || cardDocs.failed + cardDocs.skipped === 0) {
903 assertParsed(parsed, 'nvidia model cards')
904 }
905 return { models: merged, docsFailures: mergeDocs([cardDocs, specDocs]) }
906}
907
908async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
909 const run = docsRun()
910 const listed = parseNvidiaModels(await fetchJson(NVIDIA_MODELS_URL))
911 const choices = await chooseNativeContracts(
912 listed,
913 async (rawId) => (await fetchCard(rawId)).url,
914 run,
915 )
916 const warnings = [
917 ...choices.diagnostics,
918 ...run.first.map((failure) => `${failure.source}: ${failure.error}`),
919 ]
920 const endpoints = [...choices.selected].flatMap(([rawId, own]) => {
921 const result = nvidiaOwnedEndpoint(rawId, own.infer, {
922 url: own.url,
923 hash: own.hash,
924 })
925 if (!result) return []
926 warnings.push(...result.warnings)
927 return [result.endpoint]
928 })
929 if (!endpoints.length)
930 throw new Error(
931 'nvidia: native per-model documents parsed 0 generation specs; ' +
932 warnings.join('; '),
933 )
934 return {
935 specs: [],
936 sources: [],
937 bundledEndpoints: endpoints,
938 outputStrategy: 'post-200',
939 ...(warnings.length ? { warnings } : {}),
940 }
941}
942
943export const provider: ProviderConfig = {
944 id: 'nvidia',
945 displayName: 'NVIDIA NIM',
946 specSourceUrl: 'https://docs.api.nvidia.com/nim/',
947 modelsEndpoint: NVIDIA_MODELS_URL,
948 defaultDerivation: 'upstream-spec',
949 // A poll can name a per-model route the spec sync has not stored yet.
950 bindSyncedRoutesOnly: true,
951 specGrain: 'model',
952 fetchSpec,
953 listModels,
954 classify: classifyNvidiaOperation,
955}