Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

openai-compat.ts

270 lines8.4 KB

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',
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>
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
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 }
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 }
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 /** fireworks: `HF_BASE_MODEL`, `EMBEDDING_MODEL`, `ROUTER`, `CUSTOM_MODEL`. */
137 kind?: string
138 supports_chat?: boolean
139 supports_image_input?: boolean
140 /** moonshot. */
141 supports_image_in?: boolean
142 supports_video_in?: boolean
143 /** novita: `chat`, `image`, … */
144 model_type?: string
145 is_tiered_billing?: boolean
146 /**
147 * novita prompt-size brackets (`min_tokens`, `pricing`). The summary
148 * `pricing` object on a tiered row is not the standard bracket.
149 */
150 tiered_billing_configs?: unknown
151 /** hyperbolic: USD per 1M tokens (a per-token reading is not a real rate). */
152 input_price?: number
153 output_price?: number
154 /** deepseek thinking levels, when the row publishes them. */
155 effort?: { supported_levels?: Array<string> }
156 /**
157 * Host-specific price object. Novita nests decimals per million;
158 * Jina and SambaNova quote per-token strings; Perplexity quotes per
159 * million with `unit: usd_per_1m_tokens`.
160 */
161 pricing?: Record<string, unknown>
163​
164const positive = (n: number | undefined) =>
165 typeof n === 'number' && n > 0 ? n : null
166​
167/**
168 * Catalog facts from whatever extension fields a compat row carries. Only
169 * facts the row states are returned, so bare `id`+`created` rows stay bare.
170 */
171export function openAiCompatModelFacts(
172 m: OpenAiCompatModelRow,
173): Partial<ModelFacts> {
174 const flags = m.capabilities ?? {}
175 const features = new Set(
176 [...(m.supported_features ?? []), ...(m.features ?? [])].map((f) =>
177 f.replace(/-/g, '_'),
178 ),
179 )
180 const sampling = new Set(m.supported_sampling_parameters ?? [])
181​
182 // Modalities only when the row lists them outright. A lone image/vision
183 // boolean does not say what else the model takes or emits.
184 const modalities: ModelFacts['modalities'] =
185 m.input_modalities || m.output_modalities
186 ? { input: m.input_modalities ?? [], output: m.output_modalities ?? [] }
187 : null
188​
189 const caps: Array<string> = []
190 if (
191 features.has('tools') ||
192 features.has('function_calling') ||
193 m.supports_tools ||
194 flags.function_calling
195 ) {
196 caps.push('tools')
197 }
198 if (features.has('tool_choice')) caps.push('tool_choice')
199 if (features.has('reasoning') || m.supports_reasoning || flags.reasoning) {
200 caps.push('reasoning')
201 }
202 for (const param of ['temperature', 'top_p', 'top_k']) {
203 if (sampling.has(param)) caps.push(param)
204 }
205 const structured =
206 features.has('structured_outputs') || features.has('json_schema')
207 if (structured) caps.push('structured_outputs')
208 if (structured || features.has('json_mode')) caps.push('response_format')
209​
210 const facts: Partial<ModelFacts> = {}
211 const contextWindow = positive(
212 m.context_window ??
213 m.context_length ??
214 m.max_context_length ??
215 m.context_size,
216 )
217 const maxOutput = positive(
218 m.max_completion_tokens ?? m.max_output_length ?? m.max_output_tokens,
219 )
220 if (contextWindow !== null) facts.contextWindow = contextWindow
221 if (maxOutput !== null) facts.maxOutput = maxOutput
222 if (modalities) facts.modalities = modalities
223 if (caps.length > 0) facts.capabilities = caps
224 return facts
226​
227interface OpenAiModelList {
228 data?: Array<OpenAiCompatModelRow>
230​
231export async function listOpenAiCompatibleModels(opts: {
232 providerId: string
233 url: string
234 env: ProviderSecrets
235 envVar: keyof ProviderSecrets
236 /**
237 * Extra headers (e.g. Deepgram Token, Cartesia-Version). Authorization
238 * is filled in as Bearer unless `authorization` is set.
239 */
240 headers?: Record<string, string>
241 authorization?: string
242 /** Per-row activity when the listing states it (issue #72). */
243 activity?: (m: OpenAiCompatModelRow) => Activity | null
244 /** Extra catalog fields the row itself states (issue #109). */
245 extend?: (m: OpenAiCompatModelRow) => Promise<Partial<ModelInfo>>
246}): Promise<ListModelsResult> {
247 const key = opts.env[opts.envVar]
248 if (!key) {
249 return { models: [], ...skippedResult(opts.providerId, opts.envVar) }
250 }
251 const headers: Record<string, string> = {
252 Authorization: opts.authorization ?? `Bearer ${key}`,
253 ...opts.headers,
254 }
255 const body = (await fetchJson(opts.url, { headers })) as OpenAiModelList
256 const rows = (body.data ?? []).filter(
257 (m) => typeof m.id === 'string' && m.id.length > 0,
258 )
259 const models: Array<ModelInfo> = []
260 for (const m of rows) {
261 models.push({
262 rawId: m.id,
263 releasedAt: m.created ?? null,
264 ...(opts.activity ? { activity: opts.activity(m) } : {}),
265 ...openAiCompatModelFacts(m),
266 ...(await opts.extend?.(m)),
267 })
268 }
269 return { models }