Open History to see the last commit
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 type { OpenRouterModel } from './openrouter.models'
13
14type InputModality = 'text' | 'image' | 'audio' | 'video' | 'document'
15
16function mapInputModality(modality: string): InputModality | null {
17 const mapping: Record<string, InputModality> = {
18 text: 'text',
19 image: 'image',
20 audio: 'audio',
21 video: 'video',
22 file: 'document',
23 document: 'document',
24 }
25 return mapping[modality.toLowerCase()] || null
26}
27
28function convertPricing(priceStr: string, isImage: boolean = false): number {
29 // OpenRouter pricing is typically per token (in dollars)
30 // Convert to number
31 const price = parseFloat(priceStr)
32 if (isImage) {
33 return isNaN(price) ? 0 : price
34 }
35 return finalPrice(isNaN(price) ? 0 : price)
36}
37function finalPrice(price: number): number {
38 // Ensure price is non-negative and rounded to avoid floating-point errors
39 const result = price * 1_000_000
40 // Round to a reasonable number of decimal places
41 return Math.round(result * 1e10) / 1e10
42}
43const perModelProviderOptions: Record<string, string> = {}
44const perModelInputModalities: Record<string, string> = {}
45
46const imageModels = new Set<string>([])
47const chatModels = new Set<string>([])
48const videoModels = new Set<string>([])
49
50function generateChatModelsArray(): string {
51 const modelIds = Array.from(chatModels)
52 if (modelIds.length === 0) {
53 return ''
54 }
55 if (
56 !modelIds.some(
57 (id) => id.includes('openrouter/auto') || id === 'OPENROUTER_AUTO.id',
58 )
59 ) {
60 modelIds.push(`"openrouter/auto"`)
61 }
62 return `export const OPENROUTER_CHAT_MODELS = [\n${modelIds
63 .map((id) => ` ${id},`)
64 .join('\n')}\n] as const`
65}
66
67/**
68 * OpenRouter's web_search plugin works across all chat models via the gateway,
69 * so the tool-capability map is structural and identical for every chat model.
70 * Emitted as a mapped type to stay in sync with OPENROUTER_CHAT_MODELS without
71 * touching each model constant.
72 */
73function generateChatToolCapabilitiesType(): string {
74 if (chatModels.size === 0) {
75 return ''
76 }
77 return `export type OpenRouterChatModelToolCapabilitiesByName = {\n [K in (typeof OPENROUTER_CHAT_MODELS)[number]]: readonly ['web_search']\n}`
78}
79
80function generateImageModelsArray(): string {
81 const modelIds = Array.from(imageModels)
82 if (modelIds.length === 0) {
83 return ''
84 }
85 return `export const OPENROUTER_IMAGE_MODELS = [\n${modelIds
86 .map((id) => ` ${id},`)
87 .join('\n')}\n] as const`
88}
89
90function generateVideoModelsArray(): string {
91 const modelIds = Array.from(videoModels)
92 if (modelIds.length === 0) {
93 return ''
94 }
95 return `export const OPENROUTER_VIDEO_MODELS = [\n${modelIds
96 .map((id) => ` ${id},`)
97 .join('\n')}\n] as const`
98}
99
100function createPerModelModelOptions(): string {
101 const entries = Object.entries(perModelProviderOptions).map(
102 ([modelId, typeStr]) => ` [${modelId}]: ${typeStr};`,
103 )
104 if (
105 !Object.keys(perModelProviderOptions).some((k) =>
106 k.includes('OPENROUTER_AUTO'),
107 )
108 ) {
109 entries.push(
110 ` "openrouter/auto": OpenRouterCommonOptions & OpenRouterBaseOptions;`,
111 )
112 }
113
114 return `\nexport type OpenRouterModelOptionsByName = {\n${entries.join(
115 '\n',
116 )}\n}`
117}
118
119function createPerModelInputModalities(): string {
120 const entries = Object.entries(perModelInputModalities).map(
121 ([modelId, modalitiesStr]) =>
122 ` [${modelId}]: ReadonlyArray<${modalitiesStr}>;`,
123 )
124
125 if (
126 !Object.keys(perModelInputModalities).some((k) =>
127 k.includes('OPENROUTER_AUTO'),
128 )
129 ) {
130 entries.push(
131 ` "openrouter/auto": ReadonlyArray<'text' | 'image' | 'audio' | 'video' | 'document'>;`,
132 )
133 }
134 return `\nexport type OpenRouterModelInputModalitiesByName = {\n${entries.join(
135 '\n',
136 )}\n}`
137}
138
139function generateModelMetaString(model: OpenRouterModel): string {
140 const inputModalities = model.architecture.input_modalities
141 .map(mapInputModality)
142 .filter((m): m is InputModality => m !== null)
143 const outputModalities = model.architecture.output_modalities
144 .map(mapInputModality)
145 .filter((m): m is InputModality => m !== null)
146 // OpenRouter uses `~prefix/name` to denote routing aliases (e.g.
147 // `~anthropic/claude-haiku-latest`). The model ID itself is preserved as a
148 // string literal so users can pass it to `chat({ model: ... })`. The leading
149 // `~` is mapped to `_` only for the derived constant name so it's a valid
150 // JavaScript identifier.
151 const constName = model.id
152 .replaceAll('~', '_')
153 .replaceAll('/', '-')
154 .replaceAll('-', '_')
155 .replaceAll('.', '_')
156 .replaceAll(':', '_')
157 .toUpperCase()
158 // Safety net: if a future OpenRouter ID quirk produces a non-identifier
159 // constant name, fail loudly here instead of letting prettier choke on the
160 // generated file later in the pipeline.
161 if (!/^[A-Z_][A-Z0-9_]*$/.test(constName)) {
162 throw new Error(
163 `Generated constant name is not a valid JS identifier: ${JSON.stringify(
164 constName,
165 )} (from OpenRouter model.id ${JSON.stringify(
166 model.id,
167 )}). Extend the constName sanitiser to handle this case.`,
168 )
169 }
170 // Ensure at least 'text' is present
171 if (!inputModalities.includes('text')) {
172 inputModalities.unshift('text')
173 }
174 const nonChatFamilies = ['lyria', 'veo', 'imagen', 'sora', 'dall-e', 'tts']
175 const isNonChat = nonChatFamilies.some((f) =>
176 model.id.toLowerCase().includes(f),
177 )
178 if (outputModalities.includes('text') && !isNonChat) {
179 chatModels.add(`${constName}.id`)
180 }
181 if (outputModalities.includes('image')) {
182 imageModels.add(`${constName}.id`)
183 }
184 if (outputModalities.includes('video')) {
185 videoModels.add(`${constName}.id`)
186 }
187 const inputPrice = convertPricing(model.pricing.prompt)
188 const outputPrice = convertPricing(model.pricing.completion)
189 const imagePrice = convertPricing(model.pricing.image ?? '0', true)
190 const inputCacheReadPrice = convertPricing(
191 model.pricing.input_cache_read ?? '0',
192 )
193 const inputCacheWritePrice = convertPricing(
194 model.pricing.input_cache_write ?? '0',
195 )
196
197 const paramNameMap: Record<string, string> = {
198 max_tokens: 'maxCompletionTokens',
199 frequency_penalty: 'frequencyPenalty',
200 presence_penalty: 'presencePenalty',
201 repetition_penalty: 'repetitionPenalty',
202 logit_bias: 'logitBias',
203 top_logprobs: 'topLogprobs',
204 top_k: 'topK',
205 top_p: 'topP',
206 top_a: 'topA',
207 min_p: 'minP',
208 response_format: 'responseFormat',
209 tool_choice: 'toolChoice',
210 include_reasoning: 'includeReasoning',
211 max_completion_tokens: 'maxCompletionTokens',
212 web_search_options: 'webSearchOptions',
213 parallel_tool_calls: 'parallelToolCalls',
214 }
215 // The @openrouter/sdk's ChatRequest$outboundSchema strips any keys it
216 // doesn't declare, so these arrive at OpenRouter as empty. We omit them
217 // from the public type surface to avoid silently no-op'ing user input.
218 const excludedParams = new Set([
219 'tools',
220 'reasoning_effort',
221 'structured_outputs',
222 'top_k',
223 'top_a',
224 'min_p',
225 'repetition_penalty',
226 'include_reasoning',
227 'verbosity',
228 'web_search_options',
229 ])
230
231 // Build the object as a formatted string
232 const lines: Array<string> = []
233 lines.push(`const ${constName} = {`)
234 lines.push(` id: '${model.id}',`)
235 lines.push(` name: '${model.name.replace(/'/g, "\\'")}',`)
236 lines.push(` supports: {`)
237 lines.push(
238 ` input: [${inputModalities.map((m) => `'${m}'`).join(', ')}],`,
239 )
240 lines.push(
241 ` output: [${outputModalities.map((m) => `'${m}'`).join(', ')}],`,
242 )
243 lines.push(
244 ` supports: [${
245 model.supported_parameters
246 ?.filter((p) => !excludedParams.has(p))
247 .map((p) => `'${paramNameMap[p] ?? p}'`)
248 .join(', ') || ''
249 }],`,
250 )
251 lines.push(` },`)
252
253 if (model.context_length) {
254 lines.push(` context_window: ${model.context_length},`)
255 }
256
257 if (model.top_provider.max_completion_tokens) {
258 lines.push(
259 ` max_output_tokens: ${model.top_provider.max_completion_tokens},`,
260 )
261 }
262
263 lines.push(` pricing: {`)
264 lines.push(` text: {`)
265 lines.push(` input: {`)
266 lines.push(` normal: ${inputPrice},`)
267 lines.push(` cached: ${inputCacheReadPrice + inputCacheWritePrice},`)
268 lines.push(` },`)
269 lines.push(` output: {`)
270 lines.push(` normal: ${outputPrice},`)
271 lines.push(` },`)
272 lines.push(` },`)
273 lines.push(` image: ${imagePrice},`)
274 lines.push(` },`)
275 lines.push(` } as const`)
276
277 const supportedParams =
278 model.supported_parameters
279 ?.map((p) => {
280 if (excludedParams.has(p)) return ''
281 const mapped = paramNameMap[p] ?? p
282 return `'${mapped}'`
283 })
284 .filter(Boolean) ?? []
285 perModelProviderOptions[`${constName}.id`] =
286 supportedParams.length > 0
287 ? `OpenRouterCommonOptions & Pick<OpenRouterBaseOptions,${
288 supportedParams.join(' | ') || ''
289 }>`
290 : 'OpenRouterCommonOptions & OpenRouterBaseOptions'
291 perModelInputModalities[`${constName}.id`] = inputModalities
292 .map((m) => `'${m}'`)
293 .join(' | ')
294 return lines.join('\n')
295}
296
297function convertModels(models: Array<OpenRouterModel>): string {
298 const modelStrings = models.map(generateModelMetaString)
299 return modelStrings.join('\n')
300}
301
302// ============================================================
303// PASTE YOUR OPENROUTER MODELS ARRAY BELOW
304// ============================================================
305
306// ============================================================
307// RUN CONVERSION
308// ============================================================
309
310console.log('// Generated ModelMeta entries:')
311console.log('')
312const file = `
313import type { OpenRouterBaseOptions, OpenRouterCommonOptions } from './text/text-provider-options'
315${convertModels(models)}
316
317${createPerModelModelOptions()}
318
319${createPerModelInputModalities()}
320
321${generateChatModelsArray()}
322
323${generateChatToolCapabilitiesType()}
324${generateVideoModelsArray()}
325${generateImageModelsArray()}
326`
327console.log(file)
328writeFile('packages/typescript/ai-openrouter/src/model-meta.ts', file).then(
329 () => {
330 console.log(
331 'Model meta file written to packages/typescript/ai-openrouter/src/model-meta.ts',
332 )
333 },
334)