Open History to see the last commit
1/**
2 * Helpers for OpenAI-compatible providers that do not publish their own
3 * spec. fetchSpec pulls the canonical OpenAI document, keeps only the
4 * requested generation paths, and rewrites `servers` to the provider host.
5 *
6 * Derivation is `generated`: the schemas come from OpenAI's spec, not a
7 * document the provider itself publishes.
8 */
9import type { Activity } from '#/db/schema.ts'
10import type { ModelFacts } from './model-facts.ts'
11import { OPENAI_SPEC_URL } from './openai.ts'
12import { fetchJson, fetchOpenApi, skippedResult } from './types.ts'
13import type {
14 ListModelsResult,
15 ModelInfo,
16 OpenApiDocument,
17 ProviderSecrets,
18} from './types.ts'
19
20export { OPENAI_SPEC_URL as OPENAI_OPENAPI_URL }
21
22export const OPENAI_COMPAT_PATHS = [
23 '/chat/completions',
24 '/completions',
25 '/responses',
26 '/embeddings',
27 '/audio/speech',
28 '/audio/transcriptions',
29 '/audio/translations',
30 '/images/generations',
31 '/images/edits',
32 '/images/variations',
33 '/videos',
34 '/moderations',
35] as const
36
37export type OpenAiCompatPath = (typeof OPENAI_COMPAT_PATHS)[number]
38
39const PATH_ACTIVITIES: Record<OpenAiCompatPath, Activity> = {
40 '/chat/completions': 'chat',
41 '/completions': 'chat',
42 '/responses': 'chat',
43 '/embeddings': 'embeddings',
44 '/audio/speech': 'audio',
45 '/audio/transcriptions': 'audio',
46 '/audio/translations': 'audio',
47 '/images/generations': 'image',
48 '/images/edits': 'image',
49 '/images/variations': 'image',
50 '/videos': 'video',
51 '/moderations': 'moderation',
52}
53
54export interface OpenAiCompatSpecOptions {
55 title: string
56 /** Origin + version prefix the provider actually serves, e.g. https://api.groq.com/openai/v1 */
57 serverUrl: string
58 include: ReadonlyArray<OpenAiCompatPath>
59}
60
61export function classifyOpenAiCompat(path: string): Activity | null {
62 const bare = path.startsWith('/v1/') ? path.slice(3) : path
63 if (bare in PATH_ACTIVITIES) {
64 return PATH_ACTIVITIES[bare as OpenAiCompatPath]
65 }
66 return null
67}
68
69export function filterOpenAiSpec(
70 spec: OpenApiDocument,
71 opts: OpenAiCompatSpecOptions,
72): OpenApiDocument {
73 const paths: NonNullable<OpenApiDocument['paths']> = {}
74 for (const path of opts.include) {
75 const operations = spec.paths?.[path]
76 if (operations) paths[path] = operations
77 }
78 return {
79 ...spec,
80 info: { ...spec.info, title: opts.title },
81 servers: [{ url: opts.serverUrl }],
82 paths,
83 }
84}
85
86export async function fetchOpenAiCompatibleSpec(
87 opts: OpenAiCompatSpecOptions,
88): Promise<{
89 spec: OpenApiDocument
90 url: string
91 hash: string
92}> {
93 const { spec, hash } = await fetchOpenApi(OPENAI_SPEC_URL)
94 return {
95 spec: filterOpenAiSpec(spec, opts),
96 url: OPENAI_SPEC_URL,
97 hash,
98 }
99}
100
101/**
102 * Extension fields OpenAI-compatible providers put on their `/models` rows
103 * (issue #53). Names vary per host; this is the union seen across groq,
104 * jina, fireworks, moonshot, sambanova, hyperbolic, mistral, novita and
105 * cohere. Absent fields are omitted — nothing is inferred beyond what the
106 * row says.
107 */
108export interface OpenAiCompatModelRow {
109 id: string
110 created?: number
111 context_window?: number
112 context_length?: number
113 max_context_length?: number
114 context_size?: number
115 max_completion_tokens?: number
116 max_output_length?: number
117 max_output_tokens?: number
118 input_modalities?: Array<string>
119 output_modalities?: Array<string>
120 supports_tools?: boolean
121 supports_reasoning?: boolean
122 /** groq/jina: `tools`, `json_mode`, `structured_outputs`, `reasoning`. */
123 supported_features?: Array<string>
124 /**
125 * novita: `function-calling`, `structured-outputs`, `reasoning`;
126 * cohere: `tools`, `tool_choice`, `json_mode`, `json_schema`,
127 * `reasoning`, `vision`.
128 */
129 features?: Array<string>
130 /** groq/jina: `temperature`, `top_p`, `stop`, `seed`, `max_tokens`. */
131 supported_sampling_parameters?: Array<string>
132 /** mistral: `{ function_calling, reasoning, vision, … }`. */
133 capabilities?: Record<string, boolean | undefined>
134 /** mistral: other ids that resolve to this same row. */
135 aliases?: Array<string>
136 /** groq: the maker's name (`OpenAI`, `Alibaba Cloud`). */
137 owned_by?: string
138 /** fireworks: `HF_BASE_MODEL`, `EMBEDDING_MODEL`, `ROUTER`, `CUSTOM_MODEL`. */
139 kind?: string
140 supports_chat?: boolean
141 supports_image_input?: boolean
142 /** moonshot. */
143 supports_image_in?: boolean
144 supports_video_in?: boolean
145 /** novita: `chat`, `image`, … */
146 model_type?: string
147 is_tiered_billing?: boolean
148 /**
149 * novita prompt-size brackets (`min_tokens`, `pricing`). The summary
150 * `pricing` object on a tiered row is not the standard bracket.
151 */
152 tiered_billing_configs?: unknown
153 /** hyperbolic: USD per 1M tokens (a per-token reading is not a real rate). */
154 input_price?: number
155 output_price?: number
156 /** deepseek thinking levels, when the row publishes them. */
157 effort?: { supported_levels?: Array<string> }
158 /**
159 * Host-specific price object. Novita nests decimals per million;
160 * Jina and SambaNova quote per-token strings; Perplexity quotes per
161 * million with `unit: usd_per_1m_tokens`.
162 */
163 pricing?: Record<string, unknown>
164}
165
166const positive = (n: number | undefined) =>
167 typeof n === 'number' && n > 0 ? n : null
168
169/**
170 * Catalog facts from whatever extension fields a compat row carries. Only
171 * facts the row states are returned, so bare `id`+`created` rows stay bare.
172 */
173export function openAiCompatModelFacts(
174 m: OpenAiCompatModelRow,
175): Partial<ModelFacts> {
176 const flags = m.capabilities ?? {}
177 const features = new Set(
178 [...(m.supported_features ?? []), ...(m.features ?? [])].map((f) =>
179 f.replace(/-/g, '_'),
180 ),
181 )
182 const sampling = new Set(m.supported_sampling_parameters ?? [])
183
184 // Modalities only when the row lists them outright. A lone image/vision
185 // boolean does not say what else the model takes or emits.
186 const modalities: ModelFacts['modalities'] =
187 m.input_modalities || m.output_modalities
188 ? { input: m.input_modalities ?? [], output: m.output_modalities ?? [] }
189 : null
190
191 const caps: Array<string> = []
192 if (
193 features.has('tools') ||
194 features.has('function_calling') ||
195 m.supports_tools ||
196 flags.function_calling
197 ) {
198 caps.push('tools')
199 }
200 if (features.has('tool_choice')) caps.push('tool_choice')
201 if (features.has('reasoning') || m.supports_reasoning || flags.reasoning) {
202 caps.push('reasoning')
203 }
204 for (const param of ['temperature', 'top_p', 'top_k']) {
205 if (sampling.has(param)) caps.push(param)
206 }
207 const structured =
208 features.has('structured_outputs') || features.has('json_schema')
209 if (structured) caps.push('structured_outputs')
210 if (structured || features.has('json_mode')) caps.push('response_format')
211
212 const facts: Partial<ModelFacts> = {}
213 const contextWindow = positive(
214 m.context_window ??
215 m.context_length ??
216 m.max_context_length ??
217 m.context_size,
218 )
219 const maxOutput = positive(
220 m.max_completion_tokens ?? m.max_output_length ?? m.max_output_tokens,
221 )
222 if (contextWindow !== null) facts.contextWindow = contextWindow
223 if (maxOutput !== null) facts.maxOutput = maxOutput
224 if (modalities) facts.modalities = modalities
225 if (caps.length > 0) facts.capabilities = caps
226 return facts
227}
228
229interface OpenAiModelList {
230 data?: Array<OpenAiCompatModelRow>
231}
232
233export async function listOpenAiCompatibleModels(opts: {
234 providerId: string
235 url: string
236 env: ProviderSecrets
237 envVar: keyof ProviderSecrets
238 /**
239 * Extra headers (e.g. Deepgram Token, Cartesia-Version). Authorization
240 * is filled in as Bearer unless `authorization` is set.
241 */
242 headers?: Record<string, string>
243 authorization?: string
244 /** Per-row activity when the listing states it (issue #72). */
245 activity?: (m: OpenAiCompatModelRow) => Activity | null
246 /** Extra catalog fields the row itself states (issue #109). */
247 extend?: (m: OpenAiCompatModelRow) => Promise<Partial<ModelInfo>>
248}): Promise<ListModelsResult> {
249 const key = opts.env[opts.envVar]
250 if (!key) {
251 return { models: [], ...skippedResult(opts.providerId, opts.envVar) }
252 }
253 const headers: Record<string, string> = {
254 Authorization: opts.authorization ?? `Bearer ${key}`,
255 ...opts.headers,
256 }
257 const body = (await fetchJson(opts.url, { headers })) as OpenAiModelList
258 const rows = (body.data ?? []).filter(
259 (m) => typeof m.id === 'string' && m.id.length > 0,
260 )
261 const models: Array<ModelInfo> = []
262 for (const m of rows) {
263 models.push({
264 rawId: m.id,
265 releasedAt: m.created ?? null,
266 ...(opts.activity ? { activity: opts.activity(m) } : {}),
267 ...openAiCompatModelFacts(m),
268 ...(await opts.extend?.(m)),
269 })
270 }
271 return { models }
272}