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

openrouter.ts

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