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

convert-openrouter-models.ts

384 lines12.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'
16​
17type InputModality = 'text' | 'image' | 'audio' | 'video' | 'document'
18​
19function mapInputModality(modality: string): InputModality | null {
20 const mapping: Record<string, InputModality> = {
21 text: 'text',
22 image: 'image',
23 audio: 'audio',
24 video: 'video',
25 file: 'document',
26 document: 'document',
27 }
28 return mapping[modality.toLowerCase()] || null
30​
31function convertPricing(priceStr: string, isImage: boolean = false): number {
32 // OpenRouter pricing is typically per token (in dollars)
33 // Convert to number
34 const price = parseFloat(priceStr)
35 if (isImage) {
36 return isNaN(price) ? 0 : price
37 }
38 return finalPrice(isNaN(price) ? 0 : price)
40function finalPrice(price: number): number {
41 // Ensure price is non-negative and rounded to avoid floating-point errors
42 const result = price * 1_000_000
43 // Round to a reasonable number of decimal places
44 return Math.round(result * 1e10) / 1e10
46const perModelProviderOptions: Record<string, string> = {}
47const perModelInputModalities: Record<string, string> = {}
48​
49const imageModels = new Set<string>([])
50const chatModels = new Set<string>([])
51const combinedToolsAndSchemaModels = new Set<string>([])
52const videoModels = new Set<string>([])
53​
54/**
55 * Catalog ids whose `supported_parameters` include `structured_outputs`, `tools`
56 * and `tool_choice` — OpenRouter can run strict json_schema output together with
57 * tools in one request ("combined mode", #836). Derived from the catalog on every
58 * sync; never hand-edit (#1163).
59 */
60function generateCombinedToolsAndSchemaModelsSet(): string {
61 return `/**
62 * Generated: chat models whose catalog \`supported_parameters\` include
63 * \`structured_outputs\`, \`tools\` and \`tool_choice\` (combined tools + outputSchema mode).
64 */
65export const OPENROUTER_COMBINED_TOOLS_AND_SCHEMA_MODELS: ReadonlySet<string> =
66 new Set<string>([\n${Array.from(combinedToolsAndSchemaModels)
67 .map((id) => ` ${id},`)
68 .join('\n')}\n ])`
70​
71function generateChatModelsArray(): string {
72 const modelIds = Array.from(chatModels)
73 if (modelIds.length === 0) {
74 return ''
75 }
76 if (
77 !modelIds.some(
78 (id) => id.includes('openrouter/auto') || id === 'OPENROUTER_AUTO.id',
79 )
80 ) {
81 modelIds.push(`"openrouter/auto"`)
82 }
83 return `export const OPENROUTER_CHAT_MODELS = [\n${modelIds
84 .map((id) => ` ${id},`)
85 .join('\n')}\n] as const`
87​
88/**
89 * OpenRouter's web_search and web_fetch plugins work across all chat models via
90 * the gateway, so the tool-capability map is structural and identical for every
91 * chat model. Emitted as a mapped type to stay in sync with
92 * OPENROUTER_CHAT_MODELS without touching each model constant.
93 */
94function generateChatToolCapabilitiesType(): string {
95 if (chatModels.size === 0) {
96 return ''
97 }
98 return `export type OpenRouterChatModelToolCapabilitiesByName = {\n [K in (typeof OPENROUTER_CHAT_MODELS)[number]]: readonly ['web_search', 'web_fetch']\n}`
100​
101function generateImageModelsArray(): string {
102 const modelIds = Array.from(imageModels)
103 if (modelIds.length === 0) {
104 return ''
105 }
106 return `export const OPENROUTER_IMAGE_MODELS = [\n${modelIds
107 .map((id) => ` ${id},`)
108 .join('\n')}\n] as const`
110​
111function generateVideoModelsArray(): string {
112 // Video generation models come from the dedicated `GET /api/v1/videos/models`
113 // endpoint (openrouter.video-models.json) — they don't appear in the plain
114 // models listing. Models the main listing reports with a `video` output
115 // modality (none today) are merged in for completeness.
116 const ids = new Set(videoApiModels.map((m) => `'${m.id}'`))
117 for (const constRef of videoModels) ids.add(constRef)
118 if (ids.size === 0) {
119 return ''
120 }
121 return `export const OPENROUTER_VIDEO_MODELS = [\n${Array.from(ids)
122 .map((id) => ` ${id},`)
123 .join('\n')}\n] as const`
125​
126function videoMetaLiteral(value: Array<number | string> | null): string {
127 if (value === null) return 'null'
128 return `[${value
129 .map((v) => (typeof v === 'number' ? `${v}` : `'${v}'`))
130 .join(', ')}]`
132​
133/**
134 * Per-model capability metadata for the dedicated video generation API.
135 * `@tanstack/ai-openrouter/src/video/video-provider-options.ts` derives the
136 * per-model provider-option and size types from this const, and the video
137 * adapter validates sizes / durations / frame roles against it at runtime.
138 */
139function generateVideoModelMeta(): string {
140 if (videoApiModels.length === 0) {
141 return ''
142 }
143 const entries = videoApiModels.map((m: OpenRouterVideoApiModel) => {
144 const lines = [
145 ` '${m.id}': {`,
146 ` name: '${m.name.replace(/'/g, "\\'")}',`,
147 ` durations: ${videoMetaLiteral(m.supported_durations)},`,
148 ` resolutions: ${videoMetaLiteral(m.supported_resolutions)},`,
149 ` aspectRatios: ${videoMetaLiteral(m.supported_aspect_ratios)},`,
150 ` frameImages: ${videoMetaLiteral(m.supported_frame_images)},`,
151 ` sizes: ${videoMetaLiteral(m.supported_sizes)},`,
152 ` generateAudio: ${m.generate_audio},`,
153 ` seed: ${m.seed},`,
154 ` },`,
155 ]
156 return lines.join('\n')
157 })
158 return `export const OPENROUTER_VIDEO_MODEL_META = {\n${entries.join(
159 '\n',
160 )}\n} as const`
162​
163function createPerModelModelOptions(): string {
164 const entries = Object.entries(perModelProviderOptions).map(
165 ([modelId, typeStr]) => ` [${modelId}]: ${typeStr};`,
166 )
167 if (
168 !Object.keys(perModelProviderOptions).some((k) =>
169 k.includes('OPENROUTER_AUTO'),
170 )
171 ) {
172 entries.push(
173 ` "openrouter/auto": OpenRouterCommonOptions & OpenRouterBaseOptions;`,
174 )
175 }
176​
177 return `\nexport type OpenRouterModelOptionsByName = {\n${entries.join(
178 '\n',
179 )}\n}`
181​
182function createPerModelInputModalities(): string {
183 const entries = Object.entries(perModelInputModalities).map(
184 ([modelId, modalitiesStr]) =>
185 ` [${modelId}]: ReadonlyArray<${modalitiesStr}>;`,
186 )
187​
188 if (
189 !Object.keys(perModelInputModalities).some((k) =>
190 k.includes('OPENROUTER_AUTO'),
191 )
192 ) {
193 entries.push(
194 ` "openrouter/auto": ReadonlyArray<'text' | 'image' | 'audio' | 'video' | 'document'>;`,
195 )
196 }
197 return `\nexport type OpenRouterModelInputModalitiesByName = {\n${entries.join(
198 '\n',
199 )}\n}`
201​
202function generateModelMetaString(model: OpenRouterModel): string {
203 const inputModalities = model.architecture.input_modalities
204 .map(mapInputModality)
205 .filter((m): m is InputModality => m !== null)
206 const outputModalities = model.architecture.output_modalities
207 .map(mapInputModality)
208 .filter((m): m is InputModality => m !== null)
209 const constName = toModelConstName(model.id)
210 // Ensure at least 'text' is present
211 if (!inputModalities.includes('text')) {
212 inputModalities.unshift('text')
213 }
214 const nonChatFamilies = ['lyria', 'veo', 'imagen', 'sora', 'dall-e', 'tts']
215 const isNonChat = nonChatFamilies.some((f) =>
216 model.id.toLowerCase().includes(f),
217 )
218 if (outputModalities.includes('text') && !isNonChat) {
219 chatModels.add(`${constName}.id`)
220 const params = new Set(model.supported_parameters ?? [])
221 if (
222 params.has('structured_outputs') &&
223 params.has('tools') &&
224 params.has('tool_choice')
225 ) {
226 combinedToolsAndSchemaModels.add(`${constName}.id`)
227 }
228 }
229 if (outputModalities.includes('image')) {
230 imageModels.add(`${constName}.id`)
231 }
232 if (outputModalities.includes('video')) {
233 videoModels.add(`${constName}.id`)
234 }
235 const inputPrice = convertPricing(model.pricing.prompt)
236 const outputPrice = convertPricing(model.pricing.completion)
237 const imagePrice = convertPricing(model.pricing.image ?? '0', true)
238 const inputCacheReadPrice = convertPricing(
239 model.pricing.input_cache_read ?? '0',
240 )
241 const inputCacheWritePrice = convertPricing(
242 model.pricing.input_cache_write ?? '0',
243 )
244​
245 const paramNameMap: Record<string, string> = {
246 max_tokens: 'maxCompletionTokens',
247 frequency_penalty: 'frequencyPenalty',
248 presence_penalty: 'presencePenalty',
249 repetition_penalty: 'repetitionPenalty',
250 logit_bias: 'logitBias',
251 top_logprobs: 'topLogprobs',
252 top_k: 'topK',
253 top_p: 'topP',
254 top_a: 'topA',
255 min_p: 'minP',
256 response_format: 'responseFormat',
257 tool_choice: 'toolChoice',
258 include_reasoning: 'includeReasoning',
259 max_completion_tokens: 'maxCompletionTokens',
260 web_search_options: 'webSearchOptions',
261 parallel_tool_calls: 'parallelToolCalls',
262 }
263 // The @openrouter/sdk's ChatRequest$outboundSchema strips any keys it
264 // doesn't declare, so these arrive at OpenRouter as empty. We omit them
265 // from the public type surface to avoid silently no-op'ing user input.
266 const excludedParams = new Set([
267 'tools',
268 'reasoning_effort',
269 'structured_outputs',
270 'top_k',
271 'top_a',
272 'min_p',
273 'repetition_penalty',
274 'include_reasoning',
275 'verbosity',
276 'web_search_options',
277 'prediction',
278 ])
279​
280 // Build the object as a formatted string
281 const lines: Array<string> = []
282 lines.push(`const ${constName} = {`)
283 lines.push(` id: '${model.id}',`)
284 lines.push(` name: '${model.name.replace(/'/g, "\\'")}',`)
285 lines.push(` supports: {`)
286 lines.push(
287 ` input: [${inputModalities.map((m) => `'${m}'`).join(', ')}],`,
288 )
289 lines.push(
290 ` output: [${outputModalities.map((m) => `'${m}'`).join(', ')}],`,
291 )
292 lines.push(
293 ` supports: [${
294 model.supported_parameters
295 ?.filter((p) => !excludedParams.has(p))
296 .map((p) => `'${paramNameMap[p] ?? p}'`)
297 .join(', ') || ''
298 }],`,
299 )
300 lines.push(` },`)
301​
302 if (model.context_length) {
303 lines.push(` context_window: ${model.context_length},`)
304 }
305​
306 if (model.top_provider.max_completion_tokens) {
307 lines.push(
308 ` max_output_tokens: ${model.top_provider.max_completion_tokens},`,
309 )
310 }
311​
312 lines.push(` pricing: {`)
313 lines.push(` text: {`)
314 lines.push(` input: {`)
315 lines.push(` normal: ${inputPrice},`)
316 lines.push(` cached: ${inputCacheReadPrice + inputCacheWritePrice},`)
317 lines.push(` },`)
318 lines.push(` output: {`)
319 lines.push(` normal: ${outputPrice},`)
320 lines.push(` },`)
321 lines.push(` },`)
322 lines.push(` image: ${imagePrice},`)
323 lines.push(` },`)
324 lines.push(` } as const`)
325​
326 const supportedParams =
327 model.supported_parameters
328 ?.map((p) => {
329 if (excludedParams.has(p)) return ''
330 const mapped = paramNameMap[p] ?? p
331 return `'${mapped}'`
332 })
333 .filter(Boolean) ?? []
334 perModelProviderOptions[`${constName}.id`] =
335 supportedParams.length > 0
336 ? `OpenRouterCommonOptions & Pick<OpenRouterBaseOptions,${
337 supportedParams.join(' | ') || ''
338 }>`
339 : 'OpenRouterCommonOptions & OpenRouterBaseOptions'
340 perModelInputModalities[`${constName}.id`] = inputModalities
341 .map((m) => `'${m}'`)
342 .join(' | ')
343 return lines.join('\n')
345​
346function convertModels(sourceModels: Array<OpenRouterModel>): string {
347 return sourceModels.map(generateModelMetaString).join('\n')
349​
350// ============================================================
351// PASTE YOUR OPENROUTER MODELS ARRAY BELOW
352// ============================================================
353​
354// ============================================================
355// RUN CONVERSION
356// ============================================================
357​
358console.log('// Generated ModelMeta entries:')
359console.log('')
360const file = `// AUTO-GENERATED by scripts/convert-openrouter-models.ts from scripts/openrouter.models.json
361// (\`pnpm generate:models\`). Do not edit by hand — every block here is rewritten on sync.
362import type { OpenRouterBaseOptions, OpenRouterCommonOptions } from './text/text-provider-options'
364${convertModels(models)}
365​
366${createPerModelModelOptions()}
367​
368${createPerModelInputModalities()}
369​
370${generateChatModelsArray()}
371​
372${generateChatToolCapabilitiesType()}
373${generateVideoModelsArray()}
374${generateVideoModelMeta()}
375${generateImageModelsArray()}
376​
377${generateCombinedToolsAndSchemaModelsSet()}
379console.log(file)
380writeFile('packages/ai-openrouter/src/model-meta.ts', file).then(() => {
381 console.log(
382 'Model meta file written to packages/ai-openrouter/src/model-meta.ts',
383 )
384})