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

fetch-openrouter-models.ts

181 lines5.3 KB

1/**
2 * Fetches models from the OpenRouter API and writes them to openrouter.models.json
3 * and openrouter.video-models.json.
4 *
5 * Usage:
6 * pnpm tsx scripts/fetch-openrouter-models.ts
7 *
8 * Video generation models do NOT appear in the plain `GET /api/v1/models`
9 * listing — they live behind the dedicated `GET /api/v1/videos/models`
10 * endpoint, so this script fetches both and writes each to its own JSON file.
11 *
12 * The output is plain JSON so a malicious or compromised upstream response
13 * cannot smuggle executable code into the build (JSON.stringify cannot produce
14 * a JS expression). The committed wrappers at `openrouter.models.ts` /
15 * `openrouter.video-models.ts` re-export the JSON typed as
16 * `Array<OpenRouterModel>` / `Array<OpenRouterVideoApiModel>` so consumers
17 * don't need to know where the data lives.
18 */
19​
20import { writeFile } from 'node:fs/promises'
21import { dirname, resolve } from 'node:path'
22import { fileURLToPath } from 'node:url'
23​
24const __dirname = dirname(fileURLToPath(import.meta.url))
25const OUTPUT_PATH = resolve(__dirname, 'openrouter.models.json')
26const VIDEO_OUTPUT_PATH = resolve(__dirname, 'openrouter.video-models.json')
27const API_URL = 'https://openrouter.ai/api/v1/models'
28const VIDEO_API_URL = 'https://openrouter.ai/api/v1/videos/models'
29​
30interface ApiModel {
31 id: string
32 canonical_slug?: string
33 hugging_face_id?: string | null
34 name: string
35 created?: number
36 description?: string
37 context_length: number
38 architecture: {
39 modality: string
40 input_modalities: Array<string>
41 output_modalities: Array<string>
42 tokenizer?: string
43 instruct_type?: string | null
44 } | null
45 pricing: {
46 prompt: string
47 completion: string
48 audio?: string
49 request?: string
50 image?: string
51 web_search?: string
52 internal_reasoning?: string
53 input_cache_read?: string
54 input_cache_write?: string
55 } | null
56 top_provider: {
57 context_length: number
58 max_completion_tokens: number | null
59 is_moderated: boolean
60 } | null
61 per_request_limits?: Record<string, string> | null
62 supported_parameters?: Array<string>
64​
65function isValidModel(model: ApiModel): boolean {
66 if (
67 typeof model.id !== 'string' ||
68 typeof model.name !== 'string' ||
69 typeof model.context_length !== 'number' ||
70 model.architecture == null ||
71 model.pricing == null ||
72 model.top_provider == null
73 ) {
74 return false
75 }
76 if (model.created !== undefined && !Number.isFinite(model.created)) {
77 return false
78 }
79 const tp = model.top_provider
80 if (!Number.isFinite(tp.context_length)) return false
81 if (
82 tp.max_completion_tokens !== null &&
83 !Number.isFinite(tp.max_completion_tokens)
84 ) {
85 return false
86 }
87 if (typeof tp.is_moderated !== 'boolean') return false
88 return true
90​
91interface VideoApiModel {
92 id: string
93 name: string
94 supported_durations: Array<number> | null
95 supported_resolutions: Array<string> | null
96 supported_aspect_ratios: Array<string> | null
97 supported_frame_images: Array<string> | null
98 supported_sizes: Array<string> | null
99 generate_audio: boolean | null
100 seed: boolean | null
101 pricing_skus?: Record<string, string> | null
102 allowed_passthrough_parameters?: Array<string>
104​
105function isValidVideoModel(model: VideoApiModel): boolean {
106 if (typeof model.id !== 'string' || typeof model.name !== 'string') {
107 return false
108 }
109 const arrayOrNull = (v: unknown) => v === null || Array.isArray(v)
110 return (
111 arrayOrNull(model.supported_durations) &&
112 arrayOrNull(model.supported_resolutions) &&
113 arrayOrNull(model.supported_aspect_ratios) &&
114 arrayOrNull(model.supported_frame_images) &&
115 arrayOrNull(model.supported_sizes)
116 )
118​
119async function fetchJson<T>(url: string): Promise<T> {
120 console.log(`Fetching models from ${url}...`)
121 const response = await fetch(url, {
122 signal: AbortSignal.timeout(30_000),
123 })
124​
125 if (!response.ok) {
126 throw new Error(
127 `Failed to fetch models: ${response.status} ${response.statusText}`,
128 )
129 }
130​
131 return (await response.json()) as T
133​
134async function main() {
135 const json = await fetchJson<{ data: Array<ApiModel> }>(API_URL)
136 const allModels = json.data
137​
138 const validModels = allModels.filter(isValidModel)
139 const skipped = allModels.length - validModels.length
140 if (skipped > 0) {
141 console.log(
142 `Skipped ${skipped} models missing required fields (id, name, context_length, architecture, pricing, top_provider)`,
143 )
144 }
145​
146 validModels.sort((a, b) => a.id.localeCompare(b.id))
147​
148 await writeFile(
149 OUTPUT_PATH,
150 JSON.stringify(validModels, null, 2) + '\n',
151 'utf-8',
152 )
153 console.log(`Fetched ${validModels.length} models`)
154 console.log(`Written to ${OUTPUT_PATH}`)
155​
156 const videoJson = await fetchJson<{ data: Array<VideoApiModel> }>(
157 VIDEO_API_URL,
158 )
159 const validVideoModels = videoJson.data.filter(isValidVideoModel)
160 const skippedVideo = videoJson.data.length - validVideoModels.length
161 if (skippedVideo > 0) {
162 console.log(
163 `Skipped ${skippedVideo} video models with malformed fields (id, name, supported_* arrays)`,
164 )
165 }
166​
167 validVideoModels.sort((a, b) => a.id.localeCompare(b.id))
168​
169 await writeFile(
170 VIDEO_OUTPUT_PATH,
171 JSON.stringify(validVideoModels, null, 2) + '\n',
172 'utf-8',
173 )
174 console.log(`Fetched ${validVideoModels.length} video models`)
175 console.log(`Written to ${VIDEO_OUTPUT_PATH}`)
177​
178main().catch((error) => {
179 console.error(error)
180 process.exit(1)
181})