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

openrouter.ts

463 lines15.7 KB

1/**
2 * OpenRouter — public OpenAPI 3.1 spec at openrouter.ai/openapi.json, plus
3 * the public GET /api/v1/videos/models metadata API. The fetcher synthesises
4 * one constrained VideoGenerationRequest variant per video model (PR #622),
5 * mounted at `/videos/{model-id}` so the rest of the pipeline treats each
6 * model like any other endpoint. Fully keyless.
7 */
8import type { Activity } from '#/db/schema.ts'
9import { bearerConnect } from './connect.ts'
10import {
11 openrouterGenerationEndpointId,
12 openrouterModelActivity,
13} from './model-meta.ts'
14import { cachedDocs } from './model-facts.ts'
15import {
16 openRouterGatewayEfforts,
17 openRouterGatewayToggle,
18 openRouterGatewayEffortWire,
19 OPENROUTER_REASONING_URL,
20} from './openrouter-reasoning.ts'
21import { openRouterReasoning } from './reasoning-config.ts'
22import { namespacedUpstreamIdentity } from './upstream-model.ts'
23import { fetchJson, fetchText, sha256Text } from './types.ts'
24import type {
25 ListModelsResult,
26 OpenApiDocument,
27 OpenApiOperation,
28 ProviderConfig,
29 ProviderSecrets,
30 SpecFetchResult,
31} from './types.ts'
32​
33const OPENROUTER_OPENAPI_URL = 'https://openrouter.ai/openapi.json'
34const OPENROUTER_VIDEO_MODELS_URL = 'https://openrouter.ai/api/v1/videos/models'
35const OPENROUTER_MODELS_URL = 'https://openrouter.ai/api/v1/models'
36​
37export const SYNTHETIC_VIDEO_MARKER = 'x-modelschemas-synthetic-video-model'
38​
39interface VideoModel {
40 id: string
41 name: string
42 description?: string | null
43 supported_resolutions?: Array<string> | null
44 supported_aspect_ratios?: Array<string> | null
45 supported_sizes?: Array<string> | null
46 supported_durations?: Array<number> | null
47 supported_frame_images?: Array<string> | null
48 generate_audio?: boolean | null
49 seed?: boolean | null
50 allowed_passthrough_parameters?: Array<string> | null
52​
53/**
54 * Path rules — OpenRouter's generation surface spans the OpenAI-compatible
55 * endpoints and the Anthropic-compatible /messages. Account management
56 * (auth/keys, byok, credits, guardrails, workspaces, observability),
57 * preset-scoped variants, and rerank classify to null. Synthetic per-model
58 * video paths carry SYNTHETIC_VIDEO_MARKER on their POST operation — that,
59 * not the path shape, routes them to `video`, so real upstream additions
60 * under /videos/* never classify by accident.
61 */
62function classify(path: string, op: OpenApiOperation): Activity | null {
63 if (
64 path === '/chat/completions' ||
65 path === '/messages' ||
66 path === '/responses'
67 ) {
68 return 'chat'
69 }
70 if (path.startsWith('/audio/')) return 'audio'
71 if (path === '/videos' || SYNTHETIC_VIDEO_MARKER in op) return 'video'
72 if (path === '/embeddings') return 'embeddings'
73 return null
75​
76/**
77 * OpenRouter declares the /embeddings request/response schemas inline rather
78 * than via $ref; lift them into components.schemas under stable names so the
79 * bundler can treat them like every other endpoint body.
80 */
81export function liftEmbeddingsSchemas(spec: OpenApiDocument): void {
82 const post = spec.paths?.['/embeddings']?.post as
83 | {
84 requestBody?: {
85 content?: Record<string, { schema?: Record<string, unknown> }>
86 }
87 responses?: Record<
88 string,
89 { content?: Record<string, { schema?: Record<string, unknown> }> }
90 >
91 }
92 | undefined
93 const schemas = spec.components?.schemas
94 if (!post || !schemas) return
95​
96 const requestContent = post.requestBody?.content?.['application/json']
97 if (requestContent?.schema && !('$ref' in requestContent.schema)) {
98 schemas.EmbeddingsRequest = requestContent.schema
99 requestContent.schema = { $ref: '#/components/schemas/EmbeddingsRequest' }
100 }
101​
102 const responseContent = post.responses?.['200']?.content?.['application/json']
103 if (responseContent?.schema && !('$ref' in responseContent.schema)) {
104 schemas.EmbeddingsResponse = responseContent.schema
105 responseContent.schema = {
106 $ref: '#/components/schemas/EmbeddingsResponse',
107 }
108 }
110​
111function toPascal(id: string): string {
112 return id
113 .split(/[^a-zA-Z0-9]+/)
114 .filter(Boolean)
115 .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
116 .join('')
118​
119/**
120 * Synthesise one constrained VideoGenerationRequest variant per video model.
121 * Field-level constraints (durations, resolutions, aspect ratios, sizes)
122 * become enums; capabilities a model lacks (generate_audio, seed,
123 * frame_images) drop out of its variant; cross-field rules the metadata
124 * can't express structurally land in field descriptions.
125 */
126export function synthesizeVideoModelEndpoints(
127 spec: OpenApiDocument,
128 models: Array<VideoModel>,
129): void {
130 const basePost = spec.paths?.['/videos']?.post as
131 | { responses?: unknown }
132 | undefined
133 const baseRequest = spec.components?.schemas?.VideoGenerationRequest
134 if (!basePost || !baseRequest || !spec.paths) return
135​
136 for (const model of models) {
137 const schemaName = `VideoGenerationRequest${toPascal(model.id)}`
138 const schema = structuredClone(baseRequest) as {
139 description?: string
140 properties: Record<string, Record<string, unknown>>
141 }
142 const props = schema.properties
143​
144 schema.description = [
145 `${model.name} (${model.id}) — model-constrained video generation request.`,
146 model.description?.trim(),
147 ]
148 .filter(Boolean)
149 .join(' ')
150​
151 props.model = {
152 type: 'string',
153 enum: [model.id],
154 description: 'Model id (fixed for this model-constrained schema)',
155 }
156 if (model.supported_durations?.length) {
157 props.duration = { ...props.duration, enum: model.supported_durations }
158 }
159 if (model.supported_resolutions?.length) {
160 props.resolution = {
161 ...props.resolution,
162 enum: model.supported_resolutions,
163 }
164 }
165 if (model.supported_aspect_ratios?.length) {
166 props.aspect_ratio = {
167 ...props.aspect_ratio,
168 enum: model.supported_aspect_ratios,
169 }
170 }
171 if (model.supported_sizes?.length) {
172 props.size = { ...props.size, enum: model.supported_sizes }
173 }
174 if (model.generate_audio !== true) delete props.generate_audio
175 if (model.seed !== true) delete props.seed
176 if (model.supported_frame_images?.length) {
177 props.frame_images = {
178 ...props.frame_images,
179 description:
180 `${String(props.frame_images?.description ?? '')} Frame types supported by this model: ${model.supported_frame_images.join(', ')}.`.trim(),
181 }
182 } else {
183 delete props.frame_images
184 }
185 if (model.allowed_passthrough_parameters?.length && props.provider) {
186 props.provider = {
187 ...props.provider,
188 description:
189 `${String(props.provider.description ?? '')} Passthrough parameters allowed for this model: ${model.allowed_passthrough_parameters.join(', ')}.`.trim(),
190 }
191 }
192​
193 spec.components ??= { schemas: {} }
194 spec.components.schemas ??= {}
195 spec.components.schemas[schemaName] = schema
196 spec.paths[`/videos/${model.id}`] = {
197 post: {
198 [SYNTHETIC_VIDEO_MARKER]: model.id,
199 operationId: `createVideo${toPascal(model.id)}`,
200 summary: `Generate a video with ${model.name}`,
201 requestBody: {
202 content: {
203 'application/json': {
204 schema: { $ref: `#/components/schemas/${schemaName}` },
205 },
206 },
207 required: true,
208 },
209 responses: structuredClone(basePost.responses),
210 },
211 }
212 }
214​
215async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
216 const rawText = await fetchText(OPENROUTER_OPENAPI_URL)
217 // Provenance hashes the bytes as served (curl-reproducible) — before the
218 // redaction below.
219 const source = {
220 url: OPENROUTER_OPENAPI_URL,
221 hash: await sha256Text(rawText),
222 }
223 // The spec's key-management examples embed realistic-looking `sk-or-v1-…`
224 // keys; redact them (they only appear in platform endpoints that classify
225 // to null anyway).
226 const text = rawText.replace(/sk-or-v1-[0-9a-f]{16,}/g, 'sk-or-v1-REDACTED')
227 const spec = JSON.parse(text) as OpenApiDocument
228​
229 liftEmbeddingsSchemas(spec)
230​
231 let videoModels: Array<VideoModel> = []
232 try {
233 videoModels = (
234 (await fetchJson(OPENROUTER_VIDEO_MODELS_URL)) as {
235 data: Array<VideoModel>
236 }
237 ).data
238 videoModels.sort((a, b) => a.id.localeCompare(b.id))
239 } catch {
240 // Metadata fetch failed — the generic /videos endpoint still works;
241 // only the per-model variants are skipped this sync.
242 }
243 synthesizeVideoModelEndpoints(spec, videoModels)
244​
245 return { specs: [spec], sources: [source], outputStrategy: 'post-200' }
247​
248interface OpenRouterModelList {
249 data?: Array<{
250 id: string
251 name?: string
252 created?: number
253 context_length?: number
254 pricing?: unknown
255 architecture?: {
256 input_modalities?: Array<string>
257 output_modalities?: Array<string>
258 }
259 supported_parameters?: Array<string>
260 top_provider?: { max_completion_tokens?: number | null }
261 reasoning?: {
262 supported_efforts?: Array<string | null> | null
263 mandatory?: boolean
264 supports_max_tokens?: boolean
265 } | null
266 }>
268​
269/**
270 * Tool type ids are router-level. `supported_parameters` includes `tools`
271 * for client function calling and is not a hosted tool id. A listing that
272 * does not name per-model type ids stays null (issue #123).
273 */
274export function openrouterServerTools(_model: {
275 supported_parameters?: Array<string>
276}): null {
277 return null
279​
280/** Validate native metadata before deriving capability independently of mode. */
281export function openrouterCapabilities(model: {
282 supported_parameters?: unknown
283 reasoning?: unknown
284}): Array<string> | undefined {
285 const parameters = model.supported_parameters
286 if (
287 parameters !== undefined &&
288 (!Array.isArray(parameters) ||
289 !parameters.every(
290 (value) => typeof value === 'string' && value.length > 0,
291 ))
292 )
293 throw new Error('openrouter: unreadable supported_parameters')
294 const reasoning = model.reasoning
295 if (
296 reasoning !== undefined &&
297 reasoning !== null &&
298 (typeof reasoning !== 'object' || Array.isArray(reasoning))
299 )
300 throw new Error('openrouter: unreadable native reasoning metadata')
301 return reasoning && typeof reasoning === 'object'
302 ? [
303 ...new Set([
304 ...((parameters as Array<string> | undefined) ?? []),
305 'reasoning',
306 ]),
307 ]
308 : (parameters as Array<string> | undefined)
310​
311async function listModels(
312 _env: ProviderSecrets,
313 kv?: KVNamespace,
314): Promise<ListModelsResult> {
315 const body = (await fetchJson(OPENROUTER_MODELS_URL)) as OpenRouterModelList
316 if (!Array.isArray(body.data) || !body.data.length)
317 throw new Error('openrouter: missing or empty native model catalog')
318 const needsToggle = body.data.some((m) => m.reasoning?.mandatory === false)
319 const needsEffortWire = body.data.some(
320 (m) =>
321 typeof m.reasoning?.mandatory === 'boolean' &&
322 Array.isArray(m.reasoning.supported_efforts) &&
323 m.reasoning.supported_efforts.includes('high'),
324 )
325 const gateway =
326 needsToggle ||
327 needsEffortWire ||
328 body.data.some(
329 (m) =>
330 m.reasoning?.supported_efforts === null &&
331 typeof m.reasoning.mandatory === 'boolean',
332 )
333 ? await cachedDocs(
334 kv,
335 `${OPENROUTER_REASONING_URL}#${needsToggle ? 'gateway-efforts-and-toggle-wire-v1' : 'gateway-efforts-wire-v1'}`,
336 async () => {
337 const text = await fetchText(OPENROUTER_REASONING_URL, {
338 signal: AbortSignal.timeout(30_000),
339 })
340 return {
341 efforts: openRouterGatewayEfforts(text),
342 effortWire: openRouterGatewayEffortWire(text),
343 toggle: needsToggle ? openRouterGatewayToggle(text) : undefined,
344 hash: await sha256Text(text),
345 }
346 },
347 )
348 : null
349 const ownThinking = (m: NonNullable<OpenRouterModelList['data']>[number]) => {
350 const reason = openRouterReasoning(
351 m,
352 gateway?.efforts,
353 gateway?.toggle !== undefined,
354 )
355 if (reason?.mode === 'toggle') return gateway?.toggle ?? null
356 const high = reason?.efforts?.find((e) => e === 'high')
357 if (reason?.mode === 'effort' && high && gateway?.effortWire)
358 return {
359 on: {
360 [gateway.effortWire.outer]: { [gateway.effortWire.field]: high },
361 },
362 off: reason.mandatory === false ? (gateway.toggle?.off ?? null) : null,
363 levels: null,
364 }
365 return null
366 }
367 return {
368 models: body.data.map((m) => ({
369 rawId: m.id,
370 displayName: m.name ?? null,
371 activity: openrouterModelActivity(m.architecture?.output_modalities),
372 releasedAt: m.created ?? null,
373 contextWindow: m.context_length ?? null,
374 maxOutput: m.top_provider?.max_completion_tokens ?? null,
375 pricing: m.pricing,
376 modalities: m.architecture
377 ? {
378 input: m.architecture.input_modalities,
379 output: m.architecture.output_modalities,
380 }
381 : undefined,
382 capabilities: openrouterCapabilities(m),
383 requestMap: null,
384 reasoning: openRouterReasoning(
385 m,
386 gateway?.efforts,
387 gateway?.toggle !== undefined,
388 ),
389 ...(ownThinking(m)
390 ? {
391 requestMap: {
392 thinking: ownThinking(m),
393 maxTokensField: null,
394 developerRole: null,
395 replayReasoningContent: null,
396 store: null,
397 strictTools: null,
398 sessionAffinity: null,
399 cacheControl: null,
400 toolStream: null,
401 reasoningEffort: null,
402 },
403 }
404 : {}),
405 ...(gateway &&
406 (m.reasoning?.supported_efforts === null || ownThinking(m) !== null) &&
407 typeof m.reasoning?.mandatory === 'boolean'
408 ? {
409 factSources: {
410 ...(ownThinking(m)
411 ? {
412 requestMapFields: {
413 thinking: {
414 derivation: 'docs-derived' as const,
415 sourceUrl: OPENROUTER_REASONING_URL,
416 sourceHash: gateway.hash,
417 path: 'native accepted effort values or nonmandatory toggle; normative universal normalized reasoning effort/enabled fields',
418 },
419 },
420 }
421 : {}),
422 reasoning: {
423 derivation: 'docs-derived' as const,
424 sourceUrl: OPENROUTER_REASONING_URL,
425 sourceHash: gateway.hash,
426 path:
427 m.reasoning.supported_efforts === null
428 ? 'supported_efforts:null; normative gateway effort bullets; listing mandatory'
429 : openRouterReasoning(
430 m,
431 gateway.efforts,
432 gateway.toggle !== undefined,
433 )?.mode === 'toggle'
434 ? 'native mandatory:false; Messages API normalized reasoning.enabled accepted on every reasoning model; explicit disables prose'
435 : 'native per-model accepted efforts and mandatory metadata; universal normalized reasoning.effort field',
436 },
437 },
438 }
439 : {}),
440 })),
441 }
443​
444export const openrouterProvider: ProviderConfig = {
445 id: 'openrouter',
446 upstreamModelIdentity: (rawId) =>
447 namespacedUpstreamIdentity(rawId, {
448 derivation: 'listing',
449 sourceUrl: OPENROUTER_MODELS_URL,
450 path: 'data[].id',
451 }),
452 displayName: 'OpenRouter',
453 defaultDerivation: 'upstream-spec',
454 specGrain: 'provider',
455 // The shared gateway schema describes an available parameter, not support by every model.
456 perModelSchemaFlags: ['reasoning'],
457 connect: bearerConnect('https://openrouter.ai/api/v1'),
458 fetchSpec,
459 listModels,
460 classify,
461 generationEndpointId: ({ rawId, activity }) =>
462 openrouterGenerationEndpointId(rawId, activity),