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