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 synced path is the model's own id. A document that names a different
7 * model is not that row's schema.
8 */
9import type { Activity } from '#/db/schema.ts'
10
11import type {
12 ModelReasoning,
13 OpenApiDocument,
14 OpenApiOperation,
15} from './types.ts'
16
17export const NVIDIA_REFERENCE_INDEXES = [
18 'https://docs.api.nvidia.com/nim/reference/llm-apis.md',
19 'https://docs.api.nvidia.com/nim/reference/retrieval-apis.md',
20 'https://docs.api.nvidia.com/nim/reference/multimodal-apis.md',
21 'https://docs.api.nvidia.com/nim/reference/visual-models-apis.md',
22]
23
24/** Set on the copied operation so classify still sees the real route. */
25export const NVIDIA_ACTIVITY_MARKER = 'x-modelschemas-activity'
26
27const DOC_TIMEOUT_MS = 60_000
28const MAX_OUTPUT_CAP = 10_000_000
29
30export interface NvidiaIndexRow {
31 rawId: string
32 inferUrl: string
33}
34
35export interface NvidiaInferFacts {
36 document: OpenApiDocument
37 activity: Activity | null
38 maxOutput?: number
39 reasoning?: ModelReasoning
40}
41
42function isRecord(value: unknown): value is Record<string, unknown> {
43 return typeof value === 'object' && value !== null && !Array.isArray(value)
44}
45
46function delay(ms: number): Promise<void> {
47 return new Promise((resolve) => setTimeout(resolve, ms))
48}
49
50function isChallenge(text: string): boolean {
51 return (
52 text.includes('Just a moment') ||
53 text.includes('cf-browser-verification') ||
54 text.includes('Attention Required')
55 )
56}
57
58/** Fetch one NVIDIA docs page. A 429 is retried; a challenge is not a spec. */
59export async function fetchNvidiaText(url: string): Promise<string> {
60 let last = 'no response'
61 for (let attempt = 0; attempt < 4; attempt++) {
62 if (attempt > 0) await delay(800 * 2 ** (attempt - 1))
63 const response = await fetch(url, {
64 headers: {
65 accept: 'text/markdown,application/json;q=0.9,*/*;q=0.8',
66 'user-agent': 'modelschemas',
67 },
68 signal: AbortSignal.timeout(DOC_TIMEOUT_MS),
69 })
70 // 429 and a challenge page are the same Cloudflare throttle. A 503
71 // is that document failing; retrying it stalls the rest of the poll.
72 if (response.status === 429) {
73 last = String(response.status)
74 continue
75 }
76 const text = await response.text()
77 if (!response.ok) {
78 throw new Error(
79 `fetch failed: ${url} → ${String(response.status)} ${response.statusText}`,
80 )
81 }
82 if (isChallenge(text)) {
83 last = 'cloudflare challenge'
84 continue
85 }
86 return text
87 }
88 throw new Error(`nvidia: ${url} rate limited (${last})`)
89}
90
91function absoluteReference(href: string): string | null {
92 if (href.startsWith('ref:')) {
93 return `https://docs.api.nvidia.com/nim/reference/${href.slice('ref:'.length)}`
94 }
95 if (href.startsWith('https://docs.api.nvidia.com/nim/reference/')) return href
96 return null
97}
98
99/** Infer or invoke page for an index endpoint cell. Status polls are not specs. */
100function inferUrlFromCell(cell: string): string | null {
101 const links = [...cell.matchAll(/\[[^\]]*]\(([^)]+)\)/g)].map((match) =>
102 absoluteReference(match[1] ?? ''),
103 )
104 const direct = links.find(
105 (href) => href?.endsWith('-infer') || href?.endsWith('-invoke'),
106 )
107 if (direct) return direct
108 const page = links.find((href) => href && !href.endsWith('-statuspolling'))
109 return page ? `${page}-infer` : null
110}
111
112/**
113 * Rows of one reference index. Link text `publisher / id` is the listing
114 * id once the spaces NVIDIA inserts are removed (`moonshot ai / kimi-k2.6`).
115 * A markdown page whose model table yields nothing throws.
116 */
117export function parseNvidiaReferenceIndex(
118 markdown: string,
119): Array<NvidiaIndexRow> {
120 if (!markdown.startsWith('---\n')) {
121 throw new Error('nvidia: reference index is not markdown')
122 }
123 const rows: Array<NvidiaIndexRow> = []
124 const seen = new Set<string>()
125 let tableRows = 0
126 for (const line of markdown.split('\n')) {
127 if (!line.startsWith('|')) continue
128 const cells = line.split('|').slice(1, -1)
129 if (cells.length < 2) continue
130 const modelCell = cells[0] ?? ''
131 const endpointCell = cells[1] ?? ''
132 if (/^\s*:?-+/.test(modelCell)) continue
133 const label = modelCell.match(/\[([^\]]+)]\([^)]+\)/)?.[1]
134 if (!label || label.trim().toLowerCase() === 'model') continue
135 tableRows++
136 const rawId = label.replace(/\s*\/\s*/, '/').replace(/\s+/g, '')
137 const inferUrl = inferUrlFromCell(endpointCell)
138 if (!inferUrl || seen.has(rawId)) continue
139 seen.add(rawId)
140 rows.push({ rawId, inferUrl })
141 }
142 if (tableRows > 0 && rows.length === 0) {
143 throw new Error('nvidia: reference index table parsed no models')
144 }
145 return rows
146}
147
148function isOpenApiDocument(value: unknown): value is OpenApiDocument {
149 if (!isRecord(value) || typeof value.openapi !== 'string') return false
150 if (!isRecord(value.paths)) return false
151 return Object.values(value.paths).every(
152 (operations) =>
153 isRecord(operations) &&
154 Object.values(operations).every((operation) => isRecord(operation)),
155 )
156}
157
158function extractOpenApi(markdown: string): OpenApiDocument | null {
159 const section = markdown.split('# OpenAPI definition')[1] ?? markdown
160 for (const match of section.matchAll(/```json\s*([\s\S]*?)```/g)) {
161 try {
162 const parsed: unknown = JSON.parse(match[1] ?? '')
163 if (isOpenApiDocument(parsed)) return parsed
164 } catch {
165 // An example fence is not the document.
166 }
167 }
168 return null
169}
170
171function deref(
172 doc: OpenApiDocument,
173 node: unknown,
174 depth: number,
175): Record<string, unknown> | null {
176 if (depth > 8 || !isRecord(node)) return null
177 const ref = node.$ref
178 if (typeof ref !== 'string' || !ref.startsWith('#/components/schemas/')) {
179 return node
180 }
181 const schemas = doc.components?.schemas
182 if (!isRecord(schemas)) return node
183 const target = schemas[ref.slice('#/components/schemas/'.length)]
184 return deref(doc, target, depth + 1)
185}
186
187function requestProperties(doc: OpenApiDocument): Record<string, unknown> {
188 const collect = (node: unknown, depth: number): Record<string, unknown> => {
189 const resolved = deref(doc, node, depth)
190 if (!resolved) return {}
191 const own = isRecord(resolved.properties) ? resolved.properties : {}
192 const out: Record<string, unknown> = { ...own }
193 for (const key of ['allOf', 'anyOf', 'oneOf']) {
194 const list = resolved[key]
195 if (!Array.isArray(list)) continue
196 for (const item of list) Object.assign(out, collect(item, depth + 1))
197 }
198 return out
199 }
200 const out: Record<string, unknown> = {}
201 for (const operations of Object.values(doc.paths ?? {})) {
202 if (!isRecord(operations) || !isRecord(operations.post)) continue
203 const requestBody = operations.post.requestBody
204 if (!isRecord(requestBody) || !isRecord(requestBody.content)) continue
205 const json = requestBody.content['application/json']
206 if (!isRecord(json)) continue
207 Object.assign(out, collect(json.schema, 0))
208 }
209 return out
210}
211
212function integerMaximum(node: unknown): number | null {
213 if (!isRecord(node)) return null
214 if (
215 typeof node.maximum === 'number' &&
216 Number.isInteger(node.maximum) &&
217 node.maximum >= 1 &&
218 node.maximum <= MAX_OUTPUT_CAP &&
219 node.type !== 'number'
220 ) {
221 return node.maximum
222 }
223 for (const key of ['anyOf', 'oneOf', 'allOf']) {
224 const list = node[key]
225 if (!Array.isArray(list)) continue
226 for (const item of list) {
227 const found = integerMaximum(item)
228 if (found !== null) return found
229 }
230 }
231 return null
232}
233
234/** `max_tokens` / `max_completion_tokens` maximum: tokens to generate. */
235export function nvidiaMaxOutput(doc: OpenApiDocument): number | undefined {
236 const props = requestProperties(doc)
237 for (const name of ['max_tokens', 'max_completion_tokens']) {
238 const cap = integerMaximum(props[name])
239 if (cap !== null) return cap
240 }
241 return undefined
242}
243
244function enumStrings(node: unknown): Array<string> | null {
245 if (!isRecord(node)) return null
246 if (Array.isArray(node.enum)) {
247 const values = node.enum.flatMap((item) =>
248 typeof item === 'string' ? [item] : [],
249 )
250 if (values.length > 0 && values.length === node.enum.length) return values
251 }
252 for (const key of ['anyOf', 'oneOf', 'allOf']) {
253 const list = node[key]
254 if (!Array.isArray(list)) continue
255 const strings = list.flatMap((item) => enumStrings(item) ?? [])
256 if (strings.length > 0) return strings
257 }
258 return null
259}
260
261function isBooleanSchema(node: unknown): boolean {
262 if (!isRecord(node)) return false
263 if (node.type === 'boolean') return true
264 for (const key of ['anyOf', 'oneOf', 'allOf']) {
265 const list = node[key]
266 if (Array.isArray(list) && list.some((item) => isBooleanSchema(item)))
267 return true
268 }
269 return false
270}
271
272function statesOnAndOff(node: unknown): boolean {
273 if (!isRecord(node) || typeof node.description !== 'string') return false
274 const text = node.description
275 return (
276 /enable_thinking|\bthinking\b/i.test(text) &&
277 /true/i.test(text) &&
278 /false/i.test(text)
279 )
280}
281
282/** An enum label alone does not establish the model's disabling semantics. */
283function nativeEffortDisablesReasoning(
284 node: unknown,
285 efforts: string[],
286): boolean {
287 if (!isRecord(node) || typeof node.description !== 'string') return false
288 const prose = node.description.replace(/```[\s\S]*?```/g, '')
289 if (/\b(?:not|no|never|cannot|without|doesn't)\b/i.test(prose)) return false
290 return efforts.some(
291 (level) =>
292 /^(none|off|disabled)$/i.test(level) &&
293 new RegExp(
294 '(?:^|\\W)' +
295 level +
296 '[`"\']?\\s+(?:explicitly\\s+)?(?:disables?|turns?\\s+off)\\s+(?:reasoning|thinking)\\b',
297 'i',
298 ).test(prose),
299 )
300}
301
302/**
303 * Reasoning control on this model's own request schema. An effort enum
304 * wins over a budget, and a budget wins over an on/off switch. An enum
305 * requires native disabling semantics before mandatory becomes false. A boolean states both positions, so
306 * the toggle is not mandatory.
307 */
308export function nvidiaReasoning(
309 doc: OpenApiDocument,
310): ModelReasoning | undefined {
311 const props = requestProperties(doc)
312 const efforts = enumStrings(props.reasoning_effort)
313 if (efforts && efforts.length > 0) {
314 return {
315 mode: 'effort',
316 mandatory: nativeEffortDisablesReasoning(props.reasoning_effort, efforts)
317 ? false
318 : null,
319 efforts,
320 }
321 }
322 if (props.reasoning_budget !== undefined) {
323 return { mode: 'budget', mandatory: null }
324 }
325 const toggle =
326 isBooleanSchema(props.enable_thinking) ||
327 statesOnAndOff(props.chat_template_kwargs) ||
328 statesOnAndOff(props.enable_thinking)
329 if (toggle) return { mode: 'toggle', mandatory: false }
330 return undefined
331}
332
333function activityForPath(path: string): Activity | null {
334 if (path.includes('chat/completions')) return 'chat'
335 if (path.includes('/embeddings')) return 'embeddings'
336 if (/(^|\/)completions$/.test(path)) return 'chat'
337 return null
338}
339
340/**
341 * Model ids the document itself names. A title with no slash is the API
342 * name. No stated id means the reference-index join is the only link.
343 */
344export function nvidiaStatedModelIds(doc: OpenApiDocument): Array<string> {
345 const ids = new Set<string>()
346 const title = doc.info?.title
347 const named =
348 typeof title === 'string'
349 ? title
350 .trim()
351 .match(
352 /^(?:NVIDIA NIM API for )?([a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*)$/i,
353 )?.[1]
354 : undefined
355 if (named) ids.add(named)
356 const model = requestProperties(doc).model
357 if (isRecord(model)) {
358 const add = (value: unknown) => {
359 if (typeof value === 'string' && value.includes('/'))
360 ids.add(value.trim())
361 }
362 add(model.default)
363 if (Array.isArray(model.enum)) {
364 for (const item of model.enum) add(item)
365 }
366 }
367 return [...ids]
368}
369
370/** True when every stated id is this listing id, or the document names none. */
371export function nvidiaInferNamesModel(
372 rawId: string,
373 doc: OpenApiDocument,
374): boolean {
375 const stated = nvidiaStatedModelIds(doc)
376 return stated.length === 0 || stated.every((id) => id === rawId)
377}
378
379export function parseNvidiaInfer(markdown: string): NvidiaInferFacts | null {
380 const document = extractOpenApi(markdown)
381 if (!document) return null
382 const paths = Object.keys(document.paths ?? {})
383 const activity =
384 paths.map(activityForPath).find((item) => item !== null) ?? null
385 const maxOutput = nvidiaMaxOutput(document)
386 const reasoning = nvidiaReasoning(document)
387 return {
388 document,
389 activity,
390 ...(maxOutput !== undefined ? { maxOutput } : {}),
391 ...(reasoning ? { reasoning } : {}),
392 }
393}
394
395/**
396 * One document whose only generation path is `/${rawId}`. The operation
397 * is the model's real POST, including its request schema.
398 */
399export function nvidiaModelSpec(
400 rawId: string,
401 facts: NvidiaInferFacts,
402): OpenApiDocument | null {
403 if (!facts.activity) return null
404 for (const [path, operations] of Object.entries(facts.document.paths ?? {})) {
405 if (activityForPath(path) !== facts.activity) continue
406 const post = operations.post
407 if (!post) continue
408 return {
409 ...facts.document,
410 paths: {
411 [`/${rawId}`]: {
412 post: {
413 ...post,
414 [NVIDIA_ACTIVITY_MARKER]: facts.activity,
415 },
416 },
417 },
418 }
419 }
420 return null
421}
422
423export function classifyNvidiaOperation(
424 path: string,
425 operation: OpenApiOperation,
426): Activity | null {
427 const marked = operation[NVIDIA_ACTIVITY_MARKER]
428 if (
429 marked === 'chat' ||
430 marked === 'embeddings' ||
431 marked === 'image' ||
432 marked === 'video' ||
433 marked === 'audio' ||
434 marked === 'moderation'
435 ) {
436 return marked
437 }
438 return activityForPath(path)
439}