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