Open History to see the last commit
1/**
2 * Per-model OpenAPI documents NVIDIA publishes on docs.api.nvidia.com.
3 * Each reference index row names a listing id and its infer page. The
4 * infer page embeds one OpenAPI document for that model. A shared
5 * `/chat/completions` path would keep only the last model's schema, so
6 * the public endpoint identity is the model's own id; the wire path remains native. A document that names a different
7 * model is not that row's schema.
8 */
9import type { ChatRequestMap } from './request-map.ts'
10import type { Activity } from '#/db/schema.ts'
11
12import type {
13 ModelReasoning,
14 OpenApiDocument,
15 OpenApiOperation,
16} from './types.ts'
17
18export const NVIDIA_REFERENCE_INDEXES = [
19 'https://docs.api.nvidia.com/nim/reference/llm-apis.md',
20 'https://docs.api.nvidia.com/nim/reference/retrieval-apis.md',
21 'https://docs.api.nvidia.com/nim/reference/multimodal-apis.md',
22 'https://docs.api.nvidia.com/nim/reference/visual-models-apis.md',
23]
24
25/** Set on the copied operation so classify still sees the real route. */
26export const NVIDIA_ACTIVITY_MARKER = 'x-modelschemas-activity'
27
28const DOC_TIMEOUT_MS = 60_000
29const MAX_OUTPUT_CAP = 10_000_000
30
31export interface NvidiaIndexRow {
32 rawId: string
33 inferUrl: string
34}
35
36export interface NvidiaInferFacts {
37 document: OpenApiDocument
38 activity: Activity | null
39 maxOutput?: number
40 reasoning?: ModelReasoning
41 reasoningField?: string
42 maxOutputField?: string
43}
44
45function isRecord(value: unknown): value is Record<string, unknown> {
46 return typeof value === 'object' && value !== null && !Array.isArray(value)
47}
48
49function delay(ms: number): Promise<void> {
50 return new Promise((resolve) => setTimeout(resolve, ms))
51}
52
53function isChallenge(text: string): boolean {
54 return (
55 text.includes('Just a moment') ||
56 text.includes('cf-browser-verification') ||
57 text.includes('Attention Required')
58 )
59}
60
61/** A docs page answered with an HTTP error. A 404 is that page missing. */
62export class NvidiaFetchError extends Error {
63 readonly status: number
64 constructor(url: string, status: number, statusText: string) {
65 super(`fetch failed: ${url} → ${String(status)} ${statusText}`)
66 this.name = 'NvidiaFetchError'
67 this.status = status
68 }
69}
70
71/** Fetch one NVIDIA docs page. A 429 is retried; a challenge is not a spec. */
72export async function fetchNvidiaText(url: string): Promise<string> {
73 let last = 'no response'
74 for (let attempt = 0; attempt < 4; attempt++) {
75 if (attempt > 0) await delay(800 * 2 ** (attempt - 1))
76 const response = await fetch(url, {
77 headers: {
78 accept: 'text/markdown,application/json;q=0.9,*/*;q=0.8',
79 'user-agent': 'modelschemas',
80 },
81 signal: AbortSignal.timeout(DOC_TIMEOUT_MS),
82 })
83 // 429 and a challenge page are the same Cloudflare throttle. A 503
84 // is that document failing; retrying it stalls the rest of the poll.
85 if (response.status === 429) {
86 last = String(response.status)
87 continue
88 }
89 const text = await response.text()
90 if (!response.ok) {
91 throw new NvidiaFetchError(url, response.status, response.statusText)
92 }
93 if (isChallenge(text)) {
94 last = 'cloudflare challenge'
95 continue
96 }
97 return text
98 }
99 throw new Error(`nvidia: ${url} rate limited (${last})`)
100}
101
102function absoluteReference(href: string): string | null {
103 if (href.startsWith('ref:')) {
104 return `https://docs.api.nvidia.com/nim/reference/${href.slice('ref:'.length)}`
105 }
106 if (href.startsWith('https://docs.api.nvidia.com/nim/reference/')) return href
107 return null
108}
109
110/** Infer or invoke page for an index endpoint cell. Status polls are not specs. */
111function inferUrlFromCell(cell: string): string | null {
112 const links = [...cell.matchAll(/\[[^\]]*]\(([^)]+)\)/g)].map((match) =>
113 absoluteReference(match[1] ?? ''),
114 )
115 const direct = links.find(
116 (href) => href?.endsWith('-infer') || href?.endsWith('-invoke'),
117 )
118 if (direct) return direct
119 const page = links.find((href) => href && !href.endsWith('-statuspolling'))
120 return page ? `${page}-infer` : null
121}
122
123/**
124 * Rows of one reference index. Link text `publisher / id` is the listing
125 * id once the spaces NVIDIA inserts are removed (`moonshot ai / kimi-k2.6`).
126 * A markdown page whose model table yields nothing throws.
127 */
128export function parseNvidiaReferenceIndex(
129 markdown: string,
130): Array<NvidiaIndexRow> {
131 if (!markdown.startsWith('---\n')) {
132 throw new Error('nvidia: reference index is not markdown')
133 }
134 const rows: Array<NvidiaIndexRow> = []
135 const seen = new Set<string>()
136 let tableRows = 0
137 for (const line of markdown.split('\n')) {
138 if (!line.startsWith('|')) continue
139 const cells = line.split('|').slice(1, -1)
140 if (cells.length < 2) continue
141 const modelCell = cells[0] ?? ''
142 const endpointCell = cells[1] ?? ''
143 if (/^\s*:?-+/.test(modelCell)) continue
144 const label = modelCell.match(/\[([^\]]+)]\([^)]+\)/)?.[1]
145 if (!label || label.trim().toLowerCase() === 'model') continue
146 tableRows++
147 const rawId = label.replace(/\s*\/\s*/, '/').replace(/\s+/g, '')
148 const inferUrl = inferUrlFromCell(endpointCell)
149 if (!inferUrl || seen.has(rawId)) continue
150 seen.add(rawId)
151 rows.push({ rawId, inferUrl })
152 }
153 if (tableRows > 0 && rows.length === 0) {
154 throw new Error('nvidia: reference index table parsed no models')
155 }
156 return rows
157}
158
159function isOpenApiDocument(value: unknown): value is OpenApiDocument {
160 if (!isRecord(value) || typeof value.openapi !== 'string') return false
161 if (!isRecord(value.paths)) return false
162 return Object.values(value.paths).every(
163 (operations) =>
164 isRecord(operations) &&
165 Object.values(operations).every((operation) => isRecord(operation)),
166 )
167}
168
169function extractOpenApi(markdown: string): OpenApiDocument | null {
170 const section = markdown.split('# OpenAPI definition')[1] ?? markdown
171 for (const match of section.matchAll(/```json\s*/g)) {
172 try {
173 const start = match.index + match[0].length
174 let depth = 0,
175 quoted = false,
176 escaped = false
177 for (let end = start; end < section.length; end++) {
178 const char = section[end]
179 if (quoted) {
180 if (escaped) escaped = false
181 else if (char === '\\') escaped = true
182 else if (char === '"') quoted = false
183 } else if (char === '"') quoted = true
184 else if (char === '{') depth++
185 else if (char === '}' && --depth === 0) {
186 const parsed: unknown = JSON.parse(section.slice(start, end + 1))
187 if (isOpenApiDocument(parsed)) return parsed
188 break
189 }
190 }
191 } catch {
192 // An example fence is not the document.
193 }
194 }
195 return null
196}
197
198function deref(
199 doc: OpenApiDocument,
200 node: unknown,
201 depth: number,
202): Record<string, unknown> | null {
203 if (depth > 8 || !isRecord(node)) return null
204 const ref = node.$ref
205 if (typeof ref !== 'string' || !ref.startsWith('#/components/schemas/')) {
206 return node
207 }
208 const schemas = doc.components?.schemas
209 if (!isRecord(schemas)) return node
210 const target = schemas[ref.slice('#/components/schemas/'.length)]
211 return deref(doc, target, depth + 1)
212}
213
214function requestProperties(doc: OpenApiDocument): Record<string, unknown> {
215 const collect = (node: unknown, depth: number): Record<string, unknown> => {
216 const resolved = deref(doc, node, depth)
217 if (!resolved) return {}
218 const own = isRecord(resolved.properties) ? resolved.properties : {}
219 const out: Record<string, unknown> = { ...own }
220 for (const key of ['allOf', 'anyOf', 'oneOf']) {
221 const list = resolved[key]
222 if (!Array.isArray(list)) continue
223 for (const item of list) Object.assign(out, collect(item, depth + 1))
224 }
225 return out
226 }
227 const out: Record<string, unknown> = {}
228 for (const operations of Object.values(doc.paths ?? {})) {
229 if (!isRecord(operations) || !isRecord(operations.post)) continue
230 const requestBody = operations.post.requestBody
231 if (!isRecord(requestBody) || !isRecord(requestBody.content)) continue
232 const json = requestBody.content['application/json']
233 if (!isRecord(json)) continue
234 Object.assign(out, collect(json.schema, 0))
235 }
236 return out
237}
238
239function integerMaximum(node: unknown): number | null {
240 if (!isRecord(node)) return null
241 if (
242 typeof node.maximum === 'number' &&
243 Number.isInteger(node.maximum) &&
244 node.maximum >= 1 &&
245 node.maximum <= MAX_OUTPUT_CAP &&
246 node.type !== 'number'
247 ) {
248 return node.maximum
249 }
250 for (const key of ['anyOf', 'oneOf', 'allOf']) {
251 const list = node[key]
252 if (!Array.isArray(list)) continue
253 for (const item of list) {
254 const found = integerMaximum(item)
255 if (found !== null) return found
256 }
257 }
258 return null
259}
260
261/** `max_tokens` / `max_completion_tokens` maximum: tokens to generate. */
262export function nvidiaMaxOutput(doc: OpenApiDocument): number | undefined {
263 const props = requestProperties(doc)
264 for (const name of ['max_tokens', 'max_completion_tokens']) {
265 const cap = integerMaximum(props[name])
266 if (cap !== null) return cap
267 }
268 return undefined
269}
270
271function enumStrings(node: unknown): Array<string> | null {
272 if (!isRecord(node)) return null
273 if (Array.isArray(node.enum)) {
274 const values = node.enum.flatMap((item) =>
275 typeof item === 'string' ? [item] : [],
276 )
277 if (values.length > 0 && values.length === node.enum.length) return values
278 }
279 for (const key of ['anyOf', 'oneOf', 'allOf']) {
280 const list = node[key]
281 if (!Array.isArray(list)) continue
282 const strings = list.flatMap((item) => enumStrings(item) ?? [])
283 if (strings.length > 0) return strings
284 }
285 return null
286}
287
288function isBooleanSchema(node: unknown): boolean {
289 if (!isRecord(node)) return false
290 if (node.type === 'boolean') return true
291 for (const key of ['anyOf', 'oneOf', 'allOf']) {
292 const list = node[key]
293 if (Array.isArray(list) && list.some((item) => isBooleanSchema(item)))
294 return true
295 }
296 return false
297}
298
299function statesOnAndOff(node: unknown): boolean {
300 if (!isRecord(node) || typeof node.description !== 'string') return false
301 const text = node.description
302 return (
303 /enable_thinking|\bthinking\b/i.test(text) &&
304 /true/i.test(text) &&
305 /false/i.test(text)
306 )
307}
308
309/** An enum label alone does not establish the model's disabling semantics. */
310function nativeEffortDisablesReasoning(
311 node: unknown,
312 efforts: string[],
313): boolean {
314 if (!isRecord(node) || typeof node.description !== 'string') return false
315 const prose = node.description.replace(/```[\s\S]*?```/g, '')
316 if (/\b(?:not|no|never|cannot|without|doesn't)\b/i.test(prose)) return false
317 return efforts.some(
318 (level) =>
319 /^(none|off|disabled)$/i.test(level) &&
320 new RegExp(
321 '(?:^|\\W)' +
322 level +
323 '[`"\']?\\s+(?:explicitly\\s+)?(?:disables?|turns?\\s+off)\\s+(?:reasoning|thinking)\\b',
324 'i',
325 ).test(prose),
326 )
327}
328
329/**
330 * Reasoning control on this model's own request schema. An effort enum
331 * wins over a budget, and a budget wins over an on/off switch. An enum
332 * requires native disabling semantics before mandatory becomes false. A boolean states both positions, so
333 * the toggle is not mandatory.
334 */
335export function nvidiaReasoning(
336 doc: OpenApiDocument,
337): ModelReasoning | undefined {
338 const props = requestProperties(doc)
339 const efforts = enumStrings(props.reasoning_effort)
340 if (efforts && efforts.length > 0) {
341 return {
342 mode: 'effort',
343 mandatory: nativeEffortDisablesReasoning(props.reasoning_effort, efforts)
344 ? false
345 : null,
346 efforts,
347 }
348 }
349 if (props.reasoning_budget !== undefined) {
350 return { mode: 'budget', mandatory: null }
351 }
352 const template = deref(doc, props.chat_template_kwargs, 0)
353 const templateProperties = isRecord(template?.properties)
354 ? template.properties
355 : {}
356 const toggle =
357 isBooleanSchema(props.enable_thinking) ||
358 isBooleanSchema(templateProperties.enable_thinking) ||
359 statesOnAndOff(props.chat_template_kwargs) ||
360 statesOnAndOff(props.enable_thinking)
361 if (toggle) return { mode: 'toggle', mandatory: false }
362 return undefined
363}
364
365function activityForPath(path: string): Activity | null {
366 if (path.includes('chat/completions')) return 'chat'
367 if (path.includes('/embeddings')) return 'embeddings'
368 if (/(^|\/)completions$/.test(path)) return 'chat'
369 return null
370}
371
372/**
373 * Native request selectors identify the serving model. OpenAPI info.title
374 * names the API, so it is only identity evidence when no selector is published.
375 * Every literal selector must agree; no aliases are normalized.
376 */
377export function nvidiaStatedModelIds(doc: OpenApiDocument): Array<string> {
378 const ids = new Set<string>()
379 const selectors = (node: unknown, depth: number): void => {
380 const model = deref(doc, node, depth)
381 if (!model) return
382 const add = (value: unknown) => {
383 if (typeof value === 'string' && value.trim()) ids.add(value.trim())
384 }
385 add(model.const)
386 add(model.default)
387 if (Array.isArray(model.enum)) for (const value of model.enum) add(value)
388 for (const key of ['allOf', 'anyOf', 'oneOf']) {
389 if (Array.isArray(model[key]))
390 for (const value of model[key]) selectors(value, depth + 1)
391 }
392 }
393 const request = (node: unknown, depth: number): void => {
394 const schema = deref(doc, node, depth)
395 if (!schema) return
396 if (isRecord(schema.properties))
397 selectors(schema.properties.model, depth + 1)
398 for (const key of ['allOf', 'anyOf', 'oneOf']) {
399 if (Array.isArray(schema[key]))
400 for (const value of schema[key]) request(value, depth + 1)
401 }
402 }
403 for (const operations of Object.values(doc.paths ?? {})) {
404 if (!isRecord(operations) || !isRecord(operations.post)) continue
405 const body = operations.post.requestBody
406 if (!isRecord(body) || !isRecord(body.content)) continue
407 const json = body.content['application/json']
408 if (isRecord(json)) request(json.schema, 0)
409 }
410 if (ids.size) return [...ids]
411 const title = doc.info?.title
412 const named =
413 typeof title === 'string'
414 ? title
415 .trim()
416 .match(
417 /^(?:NVIDIA NIM API for )?([a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*)$/i,
418 )?.[1]
419 : undefined
420 return named ? [named] : []
421}
422
423/** True when every stated id is this listing id, or the document names none. */
424export function nvidiaInferNamesModel(
425 rawId: string,
426 doc: OpenApiDocument,
427): boolean {
428 const stated = nvidiaStatedModelIds(doc)
429 return stated.every((id) => id === rawId)
430}
431
432export function parseNvidiaInfer(markdown: string): NvidiaInferFacts | null {
433 const document = extractOpenApi(markdown)
434 return nvidiaFactsFromDocument(document)
435}
436
437/** Parse native JSON directly; descriptions may themselves contain Markdown fences. */
438export function nvidiaFactsFromDocument(
439 value: unknown,
440): NvidiaInferFacts | null {
441 if (!isOpenApiDocument(value)) return null
442 const document = value
443 const paths = Object.keys(document.paths ?? {})
444 const activity =
445 paths.map(activityForPath).find((item) => item !== null) ?? null
446 const maxOutput = nvidiaMaxOutput(document)
447 const reasoning = nvidiaReasoning(document)
448 const props = requestProperties(document)
449 const maxOutputField = ['max_tokens', 'max_completion_tokens'].find(
450 (key) => integerMaximum(props[key]) !== null,
451 )
452 const template = deref(document, props.chat_template_kwargs, 0)
453 const templateProperties = isRecord(template?.properties)
454 ? template.properties
455 : {}
456 const reasoningField =
457 reasoning?.mode === 'effort'
458 ? 'reasoning_effort'
459 : reasoning?.mode === 'budget'
460 ? 'reasoning_budget'
461 : reasoning?.mode === 'toggle'
462 ? props.enable_thinking
463 ? 'enable_thinking'
464 : templateProperties.enable_thinking
465 ? 'chat_template_kwargs.enable_thinking'
466 : 'chat_template_kwargs.description'
467 : undefined
468 return {
469 document,
470 activity,
471 ...(maxOutput !== undefined ? { maxOutput } : {}),
472 ...(reasoning ? { reasoning, reasoningField } : {}),
473 ...(maxOutputField ? { maxOutputField } : {}),
474 }
475}
476
477/** Only published per-model request members can supply caller wire facts. */
478export function nvidiaWireFacts(doc: OpenApiDocument): {
479 fields: Partial<ChatRequestMap>
480 paths: Partial<Record<keyof ChatRequestMap, string>>
481} {
482 const props = requestProperties(doc)
483 const fields: Partial<ChatRequestMap> = {}
484 const paths: Partial<Record<keyof ChatRequestMap, string>> = {}
485 const tokenField = ['max_completion_tokens', 'max_tokens'].find(
486 (key) => props[key] !== undefined,
487 )
488 if (tokenField === 'max_tokens' || tokenField === 'max_completion_tokens') {
489 fields.maxTokensField = tokenField
490 paths.maxTokensField = tokenField
491 }
492 const roles = (node: unknown, depth = 0): string[] | null => {
493 const resolved = deref(doc, node, depth)
494 if (!resolved) return null
495 if (Array.isArray(resolved.enum)) {
496 if (
497 !resolved.enum.length ||
498 !resolved.enum.every((item) => typeof item === 'string')
499 )
500 throw new Error('nvidia: unreadable native role enum')
501 return resolved.enum
502 }
503 if (typeof resolved.const === 'string') return [resolved.const]
504 if (Array.isArray(resolved.allOf)) {
505 const results = resolved.allOf.map((item) => roles(item, depth + 1))
506 if (!results.length || !results.every((item) => item !== null))
507 return null
508 return results[0]!.filter((value) =>
509 results.every((list) => list.includes(value)),
510 )
511 }
512 for (const key of ['anyOf', 'oneOf']) {
513 const alternatives = resolved[key]
514 if (!Array.isArray(alternatives)) continue
515 const results = alternatives
516 .filter((item) => !isRecord(item) || item.type !== 'null')
517 .map((item) => roles(item, depth + 1))
518 return results.length && results.every((item) => item !== null)
519 ? results.flatMap((item) => item)
520 : null
521 }
522 return null
523 }
524 const messageRoles = (node: unknown, depth = 0): string[] | null => {
525 const message = deref(doc, node, depth)
526 if (!message) return null
527 if (isRecord(message.properties) && message.properties.role !== undefined)
528 return roles(message.properties.role, depth + 1)
529 for (const key of ['anyOf', 'oneOf']) {
530 const alternatives = message[key]
531 if (!Array.isArray(alternatives)) continue
532 const results = alternatives.map((item) => messageRoles(item, depth + 1))
533 return results.length && results.every((item) => item !== null)
534 ? results.flatMap((item) => item)
535 : null
536 }
537 return null
538 }
539 const messages = deref(doc, props.messages, 0)
540 const acceptedRoles = messages ? messageRoles(messages.items) : null
541 if (acceptedRoles) {
542 fields.developerRole = acceptedRoles.includes('developer')
543 paths.developerRole = 'messages.items.role'
544 }
545 if (props.reasoning_effort !== undefined) {
546 fields.reasoningEffort = true
547 paths.reasoningEffort = 'reasoning_effort'
548 const high = enumStrings(props.reasoning_effort)?.find(
549 (value) => value === 'high',
550 )
551 if (high) {
552 fields.thinking = {
553 on: { reasoning_effort: high },
554 off: null,
555 levels: null,
556 }
557 paths.thinking = 'reasoning_effort'
558 }
559 }
560 const template = deref(doc, props.chat_template_kwargs, 0)
561 const nested = isRecord(template?.properties) ? template.properties : {}
562 if (!fields.thinking && isBooleanSchema(props.enable_thinking)) {
563 fields.thinking = {
564 on: { enable_thinking: true },
565 off: { enable_thinking: false },
566 levels: null,
567 }
568 paths.thinking = 'enable_thinking'
569 } else if (!fields.thinking && isBooleanSchema(nested.enable_thinking)) {
570 fields.thinking = {
571 on: { chat_template_kwargs: { enable_thinking: true } },
572 off: { chat_template_kwargs: { enable_thinking: false } },
573 levels: null,
574 }
575 paths.thinking = 'chat_template_kwargs.enable_thinking'
576 }
577 return { fields, paths }
578}
579
580/**
581 * Preserve the native generation path and request/response document.
582 * Logical model identity belongs to the bundled endpoint publicId.
583 */
584export function nvidiaModelSpec(
585 _rawId: string,
586 facts: NvidiaInferFacts,
587): OpenApiDocument | null {
588 if (!facts.activity) return null
589 for (const [path, operations] of Object.entries(facts.document.paths ?? {})) {
590 if (activityForPath(path) !== facts.activity) continue
591 const post = operations.post
592 if (!post) continue
593 return {
594 ...facts.document,
595 paths: {
596 [path]: {
597 post: {
598 ...post,
599 [NVIDIA_ACTIVITY_MARKER]: facts.activity,
600 },
601 },
602 },
603 }
604 }
605 return null
606}
607
608export function classifyNvidiaOperation(
609 path: string,
610 operation: OpenApiOperation,
611): Activity | null {
612 const marked = operation[NVIDIA_ACTIVITY_MARKER]
613 if (
614 marked === 'chat' ||
615 marked === 'embeddings' ||
616 marked === 'image' ||
617 marked === 'video' ||
618 marked === 'audio' ||
619 marked === 'moderation'
620 ) {
621 return marked
622 }
623 return activityForPath(path)
624}