Open History to see the last commit
1/**
2 * Chat models named by Jina's public OpenAPI, re-read on every poll.
3 * https://api.jina.ai/openapi.json `ChatCompletionRequest` is the only
4 * chat body. `factSources` has no request-map slot; that document is the
5 * source for `requestMap`.
6 */
7import type { ChatRequestMap } from './request-map.ts'
8
9export interface JinaChatContract {
10 /** Ids `ChatCompletionRequest.model` names (`const`, `enum`, or unions). */
11 modelIds: ReadonlySet<string>
12 requestMap: ChatRequestMap
13}
14
15const SCHEMA_REF = '#/components/schemas/'
16
17function isRecord(value: unknown): value is Record<string, unknown> {
18 return typeof value === 'object' && value !== null && !Array.isArray(value)
19}
20
21function schemaName(node: unknown): string | null {
22 if (!isRecord(node)) return null
23 const ref = node.$ref
24 if (typeof ref !== 'string' || !ref.startsWith(SCHEMA_REF)) return null
25 const name = ref.slice(SCHEMA_REF.length)
26 return name.length > 0 ? name : null
27}
28
29function deref(
30 schemas: Record<string, unknown>,
31 node: unknown,
32 depth = 0,
33): unknown {
34 const name = schemaName(node)
35 if (name === null || depth > 8) return node
36 const target = schemas[name]
37 if (!isRecord(target)) return node
38 return deref(schemas, target, depth + 1)
39}
40
41function mergedProperties(
42 schemas: Record<string, unknown>,
43 node: unknown,
44 depth = 0,
45): Record<string, unknown> {
46 if (depth > 8) return {}
47 const resolved = deref(schemas, node)
48 if (!isRecord(resolved)) return {}
49 const merged: Record<string, unknown> = {}
50 if (isRecord(resolved.properties)) Object.assign(merged, resolved.properties)
51 if (Array.isArray(resolved.allOf)) {
52 for (const part of resolved.allOf) {
53 Object.assign(merged, mergedProperties(schemas, part, depth + 1))
54 }
55 }
56 return merged
57}
58
59function stringIds(
60 schemas: Record<string, unknown>,
61 node: unknown,
62 depth = 0,
63): Array<string> {
64 if (depth > 8) return []
65 const resolved = deref(schemas, node)
66 if (!isRecord(resolved)) return []
67 const ids: Array<string> = []
68 if (typeof resolved.const === 'string' && resolved.const.length > 0) {
69 ids.push(resolved.const)
70 }
71 if (Array.isArray(resolved.enum)) {
72 for (const item of resolved.enum) {
73 if (typeof item === 'string' && item.length > 0) ids.push(item)
74 }
75 }
76 for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {
77 const branches = resolved[key]
78 if (!Array.isArray(branches)) continue
79 for (const branch of branches) {
80 ids.push(...stringIds(schemas, branch, depth + 1))
81 }
82 }
83 return ids
84}
85
86function enumStrings(
87 schemas: Record<string, unknown>,
88 node: unknown,
89 depth = 0,
90): Array<string> | null {
91 if (depth > 8) return null
92 const resolved = deref(schemas, node)
93 if (!isRecord(resolved)) return null
94 if (Array.isArray(resolved.enum)) {
95 const values = resolved.enum.filter(
96 (item): item is string => typeof item === 'string' && item.length > 0,
97 )
98 return values.length > 0 ? values : null
99 }
100 for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {
101 const branches = resolved[key]
102 if (!Array.isArray(branches)) continue
103 const values: Array<string> = []
104 for (const branch of branches) {
105 const found = enumStrings(schemas, branch, depth + 1)
106 if (found) values.push(...found)
107 }
108 if (values.length > 0) return [...new Set(values)]
109 }
110 return null
111}
112
113function roleValues(
114 schemas: Record<string, unknown>,
115 properties: Record<string, unknown>,
116): Array<string> | null {
117 const messages = deref(schemas, properties.messages)
118 if (!isRecord(messages)) return null
119 const items = deref(schemas, messages.items)
120 if (!isRecord(items) || !isRecord(items.properties)) return null
121 return enumStrings(schemas, items.properties.role)
122}
123
124/**
125 * A listing id matches when it is a named model, or its segment after the
126 * last `/` is (`jina-ai/jina-ocr-v1` is the const `jina-ocr-v1`).
127 */
128export function jinaChatModel(
129 rawId: string,
130 modelIds: ReadonlySet<string>,
131): boolean {
132 if (modelIds.has(rawId)) return true
133 const slash = rawId.lastIndexOf('/')
134 if (slash === -1) return false
135 return modelIds.has(rawId.slice(slash + 1))
136}
137
138/**
139 * Throws when the chat body is gone, names no model, or names both output
140 * caps. A missing role enum leaves `developerRole` null. `reasoning_effort`
141 * stays null when the body omits it: the operation accepts unknown fields
142 * and ignores them, so absence is not a rejection.
143 */
144export function parseJinaChatRequest(spec: unknown): JinaChatContract {
145 if (!isRecord(spec) || !isRecord(spec.components)) {
146 throw new Error('jina spec: ChatCompletionRequest missing')
147 }
148 const schemas = spec.components.schemas
149 if (!isRecord(schemas) || !isRecord(schemas.ChatCompletionRequest)) {
150 throw new Error('jina spec: ChatCompletionRequest missing')
151 }
152 const properties = mergedProperties(schemas, schemas.ChatCompletionRequest)
153 const modelIds = [...new Set(stringIds(schemas, properties.model))]
154 if (modelIds.length === 0) {
155 throw new Error('jina spec: ChatCompletionRequest names no model')
156 }
157 const hasCompletion = Object.hasOwn(properties, 'max_completion_tokens')
158 const hasMaxTokens = Object.hasOwn(properties, 'max_tokens')
159 if (hasCompletion && hasMaxTokens) {
160 throw new Error(
161 'jina spec: ChatCompletionRequest names both max_tokens and max_completion_tokens',
162 )
163 }
164 const roles = roleValues(schemas, properties)
165 const requestMap: ChatRequestMap = {
166 thinking: null,
167 maxTokensField: hasCompletion
168 ? 'max_completion_tokens'
169 : hasMaxTokens
170 ? 'max_tokens'
171 : null,
172 developerRole: roles === null ? null : roles.includes('developer'),
173 replayReasoningContent: null,
174 store: null,
175 strictTools: null,
176 sessionAffinity: null,
177 cacheControl: null,
178 toolStream: null,
179 reasoningEffort: Object.hasOwn(properties, 'reasoning_effort')
180 ? true
181 : null,
182 }
183 return { modelIds: new Set(modelIds), requestMap }
184}