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

fetch-vercel-gateway-models.ts

92 lines2.5 KB

1/**
2 * Fetches models from the Vercel AI Gateway API and writes them to
3 * vercel-gateway.models.json.
4 *
5 * Usage:
6 * pnpm tsx scripts/fetch-vercel-gateway-models.ts
7 *
8 * The output is plain JSON so a malicious or compromised upstream response
9 * cannot smuggle executable code into the build (JSON.stringify cannot produce
10 * a JS expression). The committed wrapper at `vercel-gateway.models.ts`
11 * re-exports this JSON typed as `Array<VercelGatewayCatalogModel>`.
12 */
13​
14import { writeFile } from 'node:fs/promises'
15import { dirname, resolve } from 'node:path'
16import { fileURLToPath } from 'node:url'
17​
18const __dirname = dirname(fileURLToPath(import.meta.url))
19const OUTPUT_PATH = resolve(__dirname, 'vercel-gateway.models.json')
20const API_URL = 'https://ai-gateway.vercel.sh/v1/models'
21​
22interface ApiModel {
23 id: string
24 [key: string]: unknown
26​
27function isValidModel(model: unknown): model is ApiModel {
28 return (
29 typeof model === 'object' &&
30 model !== null &&
31 typeof (model as { id?: unknown }).id === 'string' &&
32 (model as { id: string }).id.length > 0
33 )
35​
36async function main() {
37 console.log(`Fetching models from ${API_URL}...`)
38​
39 const apiKey = process.env.AI_GATEWAY_API_KEY
40 const headers: Record<string, string> = {
41 Accept: 'application/json',
42 }
43 if (apiKey) {
44 headers.Authorization = `Bearer ${apiKey}`
45 }
46​
47 const response = await fetch(API_URL, {
48 headers,
49 signal: AbortSignal.timeout(30_000),
50 })
51​
52 if (response.status === 401 && !apiKey) {
53 throw new Error(
54 'GET https://ai-gateway.vercel.sh/v1/models returned 401. Set AI_GATEWAY_API_KEY in the environment (CI must set secrets.AI_GATEWAY_API_KEY).',
55 )
56 }
57​
58 if (!response.ok) {
59 throw new Error(
60 `Failed to fetch Vercel AI Gateway models: ${response.status} ${response.statusText}`,
61 )
62 }
63​
64 const json = (await response.json()) as { data?: unknown }
65 if (!Array.isArray(json.data)) {
66 throw new Error(
67 'Vercel AI Gateway /v1/models response is missing a data array',
68 )
69 }
70​
71 const allModels = json.data
72 const validModels = allModels.filter(isValidModel)
73 const skipped = allModels.length - validModels.length
74 if (skipped > 0) {
75 console.log(`Skipped ${skipped} models missing a string id`)
76 }
77​
78 validModels.sort((a, b) => a.id.localeCompare(b.id))
79​
80 await writeFile(
81 OUTPUT_PATH,
82 JSON.stringify(validModels, null, 2) + '\n',
83 'utf-8',
84 )
85 console.log(`Fetched ${validModels.length} models`)
86 console.log(`Written to ${OUTPUT_PATH}`)
88​
89main().catch((error) => {
90 console.error(error)
91 process.exit(1)
92})