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

convert-openrouter-models.ts

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