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