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

convert-openrouter-models.ts

493 lines16.6 KB

1/**
2 * Script to convert OpenRouter model objects to ModelMeta format
3 *
4 * Usage:
5 * 1. Paste your OpenRouter models array into the `models` variable below
6 * 2. Run: npx ts-node scripts/convert-openrouter-models.ts
7 * 3. Copy the output into your model-meta.ts file
8 */
9​
10import { writeFile } from 'node:fs/promises'
11import { models } from './openrouter.models'
12import { videoModels as videoApiModels } from './openrouter.video-models'
13import type { OpenRouterModel } from './openrouter.models'
14import type { OpenRouterVideoApiModel } from './openrouter.video-models'
15import { toModelConstName } from './model-sync/ids'
16import {
17 reasoningShapeName,
18 reasoningShapeTable,
19} from './model-sync/reasoning-shapes'
20import type { ModelReasoning } from '@tanstack/ai'
21import type { ReasoningShape } from './model-sync/reasoning-shapes'
22​
23/**
24 * Each model's `chat({ reasoning })` data comes from models.dev, which this
25 * script does not read. Keep the entries that the current model-meta.ts has,
26 * so a sync does not drop them.
27 */
28// ponytail: preserved, not generated. The models.dev generator comes with the model catalog.
29const existingReasoning: Readonly<Record<string, ModelReasoning>> =
30 (
31 (await import('../packages/ai-openrouter/src/model-meta')) as {
32 OPENROUTER_MODEL_REASONING?: Readonly<Record<string, ModelReasoning>>
33 }
34 ).OPENROUTER_MODEL_REASONING ?? {}
35​
36type InputModality = 'text' | 'image' | 'audio' | 'video' | 'document'
37​
38function mapInputModality(modality: string): InputModality | null {
39 const mapping: Record<string, InputModality> = {
40 text: 'text',
41 image: 'image',
42 audio: 'audio',
43 video: 'video',
44 file: 'document',
45 document: 'document',
46 }
47 return mapping[modality.toLowerCase()] || null
49​
50const perModelProviderOptions: Record<string, string> = {}
51const perModelInputModalities: Record<string, string> = {}
52​
53const imageModels = new Set<string>([])
54const chatModels = new Set<string>([])
55const combinedToolsAndSchemaModels = new Set<string>([])
56const jsonObjectOnlyModels = new Set<string>([])
57const videoModels = new Set<string>([])
58const reasoningModels = new Set<string>([])
59const reasoningShapes: Array<ReasoningShape> = []
60​
61/**
62 * Catalog ids whose `supported_parameters` include `structured_outputs`, `tools`
63 * and `tool_choice` — OpenRouter can run strict json_schema output together with
64 * tools in one request ("combined mode", #836). Derived from the catalog on every
65 * sync; never hand-edit (#1163).
66 */
67function generateCombinedToolsAndSchemaModelsSet(): string {
68 return `/**
69 * Generated: chat models whose catalog \`supported_parameters\` include
70 * \`structured_outputs\`, \`tools\` and \`tool_choice\` (combined tools + outputSchema mode).
71 */
72export const OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS: ReadonlySet<string> =
73 new Set<string>([\n${Array.from(combinedToolsAndSchemaModels)
74 .map((id) => ` ${id},`)
75 .join('\n')}\n ])`
77​
78/**
79 * Catalog ids whose `supported_parameters` include `response_format` and not
80 * `structured_outputs`. Structured output sends JSON mode for these.
81 */
82function generateJsonObjectOnlyModelsSet(): string {
83 return `/**
84 * Generated: chat models whose catalog \`supported_parameters\` include
85 * \`response_format\` and do not include \`structured_outputs\`.
86 * Structured output sends JSON mode for these ids.
87 */
88export const OPENROUTER_JSON_OBJECT_ONLY_MODELS: ReadonlySet<string> =
89 new Set<string>([\n${Array.from(jsonObjectOnlyModels)
90 .map((id) => ` ${id},`)
91 .join('\n')}\n ])`
93​
94function generateChatModelsArray(): string {
95 const modelIds = Array.from(chatModels)
96 if (modelIds.length === 0) {
97 return ''
98 }
99 if (
100 !modelIds.some(
101 (id) => id.includes('openrouter/auto') || id === 'OPENROUTER_AUTO.id',
102 )
103 ) {
104 modelIds.push(`"openrouter/auto"`)
105 }
106 return `export const OPENROUTER_CHAT_MODELS = [\n${modelIds
107 .map((id) => ` ${id},`)
108 .join('\n')}\n] as const`
110​
111/**
112 * Runtime twin of OpenRouterModelInputModalitiesByName for the chat models,
113 * read by the text adapters' `inputModalities`. The `satisfies` clause makes a
114 * missing, extra, or different entry a type error.
115 */
116function generateChatModelInputModalitiesMap(): string {
117 const idRefs = Array.from(chatModels)
118 if (idRefs.length === 0) {
119 return ''
120 }
121 const entries = idRefs.map(
122 (idRef) => ` [${idRef}]: ${idRef.replace(/\.id$/, '.supports.input')},`,
123 )
124 if (
125 !idRefs.some(
126 (id) => id.includes('openrouter/auto') || id === 'OPENROUTER_AUTO.id',
127 )
128 ) {
129 entries.push(
130 ` 'openrouter/auto': ['text', 'image', 'audio', 'video', 'document'],`,
131 )
132 }
133 return `/**
134 * Generated: runtime map from chat model id to its input modalities, read by
135 * the text adapters' \`inputModalities\`. \`satisfies\` ties it to
136 * \`OpenRouterModelInputModalitiesByName\`, so the two cannot drift.
137 */
138export const OPENROUTER_MODEL_INPUT_MODALITIES: Readonly<Record<string, ReadonlyArray<Modality>>> = {\n${entries.join(
139 '\n',
140 )}\n} satisfies { [K in (typeof OPENROUTER_CHAT_MODELS)[number]]: OpenRouterModelInputModalitiesByName[K] }`
142​
143/**
144 * The reasoning type map and its runtime twin, from the `reasoning` field of
145 * each model. `openrouter/auto` has no constant, so its entry is a literal.
146 */
147function generateReasoningMaps(): string {
148 const entries = Array.from(reasoningModels).map(
149 (constName) => ` [${constName}.id]: ${constName}.reasoning,`,
150 )
151 const auto = existingReasoning['openrouter/auto']
152 if (auto) {
153 entries.push(` 'openrouter/auto': ${reasoningShapeName(auto)},`)
154 reasoningShapes.push(auto)
155 }
156 if (entries.length === 0) return ''
157 return `// Reasoning
158//
159// Each model's \`reasoning\` field holds its data for \`chat({ reasoning })\`:
160// the levels it has, with the provider value for each, and whether it takes
161// a thinking token budget. The data comes from models.dev. The generator
162// that writes it comes with the model catalog later. Until then,
163// scripts/convert-openrouter-models.ts keeps the entries of the current file.
164​
165const OPENROUTER_REASONING = {
166${entries.join('\n')}
168​
169/**
170 * Generated: each chat model's reasoning levels, and whether it takes a token
171 * budget, for \`chat({ reasoning })\`. A model that is not here does not reason.
172 */
173export type OpenRouterModelReasoningByName = {
174 [K in keyof typeof OPENROUTER_REASONING]: ModelReasoningCapability<
175 (typeof OPENROUTER_REASONING)[K]
176 >
178​
179/**
180 * Generated: runtime map from chat model id to its reasoning data, for the
181 * text adapters.
182 */
183export const OPENROUTER_MODEL_REASONING: Readonly<
184 Record<string, ModelReasoning>
185> = OPENROUTER_REASONING`
187​
188/** One constant per distinct reasoning shape. Models point at them. */
189function generateReasoningShapes(): string {
190 if (reasoningShapes.length === 0) return ''
191 return `// Reasoning shapes: the levels a model has for \`chat({ reasoning })\`, and
192// the provider value to send for each. Each model points at one of them.
193${reasoningShapeTable(reasoningShapes).code}`
195​
196/**
197 * OpenRouter's web_search and web_fetch plugins work across all chat models via
198 * the gateway, so the tool-capability map is structural and identical for every
199 * chat model. Emitted as a mapped type to stay in sync with
200 * OPENROUTER_CHAT_MODELS without touching each model constant.
201 */
202function generateChatToolCapabilitiesType(): string {
203 if (chatModels.size === 0) {
204 return ''
205 }
206 return `export type OpenRouterChatModelToolCapabilitiesByName = {\n [K in (typeof OPENROUTER_CHAT_MODELS)[number]]: readonly ['web_search', 'web_fetch']\n}`
208​
209function generateImageModelsArray(): string {
210 const modelIds = Array.from(imageModels)
211 if (modelIds.length === 0) {
212 return ''
213 }
214 return `export const OPENROUTER_IMAGE_MODELS = [\n${modelIds
215 .map((id) => ` ${id},`)
216 .join('\n')}\n] as const`
218​
219function generateVideoModelsArray(): string {
220 // Video generation models come from the dedicated `GET /api/v1/videos/models`
221 // endpoint (openrouter.video-models.json) — they don't appear in the plain
222 // models listing. Models the main listing reports with a `video` output
223 // modality (none today) are merged in for completeness.
224 const ids = new Set(videoApiModels.map((m) => `'${m.id}'`))
225 for (const constRef of videoModels) ids.add(constRef)
226 if (ids.size === 0) {
227 return ''
228 }
229 return `export const OPENROUTER_VIDEO_MODELS = [\n${Array.from(ids)
230 .map((id) => ` ${id},`)
231 .join('\n')}\n] as const`
233​
234function videoMetaLiteral(value: Array<number | string> | null): string {
235 if (value === null) return 'null'
236 return `[${value
237 .map((v) => (typeof v === 'number' ? `${v}` : `'${v}'`))
238 .join(', ')}]`
240​
241/**
242 * Per-model capability metadata for the dedicated video generation API.
243 * `@tanstack/ai-openrouter/src/video/video-provider-options.ts` derives the
244 * per-model provider-option and size types from this const, and the video
245 * adapter validates sizes / durations / frame roles against it at runtime.
246 */
247function generateVideoModelMeta(): string {
248 if (videoApiModels.length === 0) {
249 return ''
250 }
251 const entries = videoApiModels.map((m: OpenRouterVideoApiModel) => {
252 const lines = [
253 ` '${m.id}': {`,
254 ` name: '${m.name.replace(/'/g, "\\'")}',`,
255 ` durations: ${videoMetaLiteral(m.supported_durations)},`,
256 ` resolutions: ${videoMetaLiteral(m.supported_resolutions)},`,
257 ` aspectRatios: ${videoMetaLiteral(m.supported_aspect_ratios)},`,
258 ` frameImages: ${videoMetaLiteral(m.supported_frame_images)},`,
259 ` sizes: ${videoMetaLiteral(m.supported_sizes)},`,
260 ` generateAudio: ${m.generate_audio},`,
261 ` seed: ${m.seed},`,
262 ` },`,
263 ]
264 return lines.join('\n')
265 })
266 return `export const OPENROUTER_VIDEO_MODEL_META = {\n${entries.join(
267 '\n',
268 )}\n} as const`
270​
271function createPerModelModelOptions(): string {
272 const entries = Object.entries(perModelProviderOptions).map(
273 ([modelId, typeStr]) => ` [${modelId}]: ${typeStr};`,
274 )
275 if (
276 !Object.keys(perModelProviderOptions).some((k) =>
277 k.includes('OPENROUTER_AUTO'),
278 )
279 ) {
280 entries.push(
281 ` "openrouter/auto": OpenRouterCommonOptions & OpenRouterBaseOptions;`,
282 )
283 }
284​
285 return `\nexport type OpenRouterModelOptionsByName = {\n${entries.join(
286 '\n',
287 )}\n}`
289​
290function createPerModelInputModalities(): string {
291 const entries = Object.entries(perModelInputModalities).map(
292 ([modelId, modalitiesStr]) =>
293 ` [${modelId}]: ReadonlyArray<${modalitiesStr}>;`,
294 )
295​
296 if (
297 !Object.keys(perModelInputModalities).some((k) =>
298 k.includes('OPENROUTER_AUTO'),
299 )
300 ) {
301 entries.push(
302 ` "openrouter/auto": ReadonlyArray<'text' | 'image' | 'audio' | 'video' | 'document'>;`,
303 )
304 }
305 return `\nexport type OpenRouterModelInputModalitiesByName = {\n${entries.join(
306 '\n',
307 )}\n}`
309​
310function generateModelMetaString(model: OpenRouterModel): string {
311 const inputModalities = model.architecture.input_modalities
312 .map(mapInputModality)
313 .filter((m): m is InputModality => m !== null)
314 const outputModalities = model.architecture.output_modalities
315 .map(mapInputModality)
316 .filter((m): m is InputModality => m !== null)
317 const constName = toModelConstName(model.id)
318 // Ensure at least 'text' is present
319 if (!inputModalities.includes('text')) {
320 inputModalities.unshift('text')
321 }
322 const nonChatFamilies = ['lyria', 'veo', 'imagen', 'sora', 'dall-e', 'tts']
323 const isNonChat = nonChatFamilies.some((f) =>
324 model.id.toLowerCase().includes(f),
325 )
326 if (outputModalities.includes('text') && !isNonChat) {
327 chatModels.add(`${constName}.id`)
328 const params = new Set(model.supported_parameters ?? [])
329 if (
330 params.has('structured_outputs') &&
331 params.has('tools') &&
332 params.has('tool_choice')
333 ) {
334 combinedToolsAndSchemaModels.add(`${constName}.id`)
335 }
336 if (params.has('response_format') && !params.has('structured_outputs')) {
337 jsonObjectOnlyModels.add(`${constName}.id`)
338 }
339 }
340 if (outputModalities.includes('image')) {
341 imageModels.add(`${constName}.id`)
342 }
343 if (outputModalities.includes('video')) {
344 videoModels.add(`${constName}.id`)
345 }
346 const paramNameMap: Record<string, string> = {
347 max_tokens: 'maxCompletionTokens',
348 frequency_penalty: 'frequencyPenalty',
349 presence_penalty: 'presencePenalty',
350 repetition_penalty: 'repetitionPenalty',
351 logit_bias: 'logitBias',
352 top_logprobs: 'topLogprobs',
353 top_k: 'topK',
354 top_p: 'topP',
355 top_a: 'topA',
356 min_p: 'minP',
357 response_format: 'responseFormat',
358 tool_choice: 'toolChoice',
359 include_reasoning: 'includeReasoning',
360 max_completion_tokens: 'maxCompletionTokens',
361 web_search_options: 'webSearchOptions',
362 parallel_tool_calls: 'parallelToolCalls',
363 }
364 // The @openrouter/sdk's ChatRequest$outboundSchema strips any keys it
365 // doesn't declare, so these arrive at OpenRouter as empty. We omit them
366 // from the public type surface to avoid silently no-op'ing user input.
367 const excludedParams = new Set([
368 'tools',
369 'reasoning_effort',
370 'structured_outputs',
371 'top_k',
372 'top_a',
373 'min_p',
374 'repetition_penalty',
375 'include_reasoning',
376 'verbosity',
377 'web_search_options',
378 'prediction',
379 ])
380​
381 // Build the object as a formatted string
382 const lines: Array<string> = []
383 lines.push(`const ${constName} = {`)
384 lines.push(` id: '${model.id}',`)
385 lines.push(` name: '${model.name.replace(/'/g, "\\'")}',`)
386 lines.push(` supports: {`)
387 lines.push(
388 ` input: [${inputModalities.map((m) => `'${m}'`).join(', ')}],`,
389 )
390 lines.push(
391 ` output: [${outputModalities.map((m) => `'${m}'`).join(', ')}],`,
392 )
393 lines.push(
394 ` supports: [${
395 model.supported_parameters
396 ?.filter((p) => !excludedParams.has(p))
397 .map((p) => `'${paramNameMap[p] ?? p}'`)
398 .join(', ') || ''
399 }],`,
400 )
401 lines.push(` },`)
402​
403 if (model.context_length) {
404 lines.push(` context_window: ${model.context_length},`)
405 }
406​
407 if (model.top_provider.max_completion_tokens) {
408 lines.push(
409 ` max_output_tokens: ${model.top_provider.max_completion_tokens},`,
410 )
411 }
412​
413 const reasoning = existingReasoning[model.id]
414 if (reasoning) {
415 lines.push(` reasoning: ${reasoningShapeName(reasoning)},`)
416 reasoningModels.add(constName)
417 reasoningShapes.push(reasoning)
418 }
419 lines.push(` } as const`)
420​
421 const supportedParams =
422 model.supported_parameters
423 ?.map((p) => {
424 // `chat({ reasoning })` owns reasoning, so it is not a model option.
425 if (excludedParams.has(p) || p === 'reasoning') return ''
426 const mapped = paramNameMap[p] ?? p
427 return `'${mapped}'`
428 })
429 .filter(Boolean) ?? []
430 perModelProviderOptions[`${constName}.id`] =
431 supportedParams.length > 0
432 ? `OpenRouterCommonOptions & Pick<OpenRouterBaseOptions,${
433 supportedParams.join(' | ') || ''
434 }>`
435 : 'OpenRouterCommonOptions & OpenRouterBaseOptions'
436 perModelInputModalities[`${constName}.id`] = inputModalities
437 .map((m) => `'${m}'`)
438 .join(' | ')
439 return lines.join('\n')
441​
442function convertModels(sourceModels: Array<OpenRouterModel>): string {
443 return sourceModels.map(generateModelMetaString).join('\n')
445​
446// ============================================================
447// PASTE YOUR OPENROUTER MODELS ARRAY BELOW
448// ============================================================
449​
450// ============================================================
451// RUN CONVERSION
452// ============================================================
453​
454console.log('// Generated ModelMeta entries:')
455console.log('')
456// The shapes go above the models, but come from them: convert first.
457const modelsCode = convertModels(models)
458const reasoningMapsCode = generateReasoningMaps()
459const file = `// AUTO-GENERATED by scripts/convert-openrouter-models.ts from scripts/openrouter.models.json
460// (\`pnpm generate:models\`). Do not edit by hand — every block here is rewritten on sync.
461import type { Modality, ModelReasoning } from '@tanstack/ai'
462import type { ModelReasoningCapability } from '@tanstack/ai/adapter-internals'
463import type { OpenRouterBaseOptions, OpenRouterCommonOptions } from './text/text-provider-options'
464​
465${generateReasoningShapes()}
466​
467${modelsCode}
468​
469${createPerModelModelOptions()}
470​
471${createPerModelInputModalities()}
472​
473${generateChatModelsArray()}
474​
475${generateChatModelInputModalitiesMap()}
476​
477${reasoningMapsCode}
478​
479${generateChatToolCapabilitiesType()}
480${generateVideoModelsArray()}
481${generateVideoModelMeta()}
482${generateImageModelsArray()}
483​
484${generateCombinedToolsAndSchemaModelsSet()}
485​
486${generateJsonObjectOnlyModelsSet()}
488console.log(file)
489writeFile('packages/ai-openrouter/src/model-meta.ts', file).then(() => {
490 console.log(
491 'Model meta file written to packages/ai-openrouter/src/model-meta.ts',
492 )
493})