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

fetch-neon-models.ts

85 lines2.6 KB

1/**
2 * Fetches the Neon AI Gateway model catalog and writes it to
3 * neon.models.json.
4 *
5 * Usage:
6 * pnpm tsx scripts/fetch-neon-models.ts
7 *
8 * The catalog is public. `https://neon.com/models` serves it as JSON when the
9 * request asks for JSON. That shape carries `capabilities` (which endpoint
10 * serves each model); `neon.com/models.json` (the models.dev shape) does not.
11 *
12 * The output is plain JSON so a malicious or compromised upstream response
13 * cannot smuggle executable code into the build. The committed wrapper at
14 * `neon.models.ts` re-exports this JSON typed as `Array<NeonCatalogModel>`.
15 */
16​
17import { writeFile } from 'node:fs/promises'
18import { dirname, resolve } from 'node:path'
19import { fileURLToPath } from 'node:url'
20​
21const __dirname = dirname(fileURLToPath(import.meta.url))
22const OUTPUT_PATH = resolve(__dirname, 'neon.models.json')
23const API_URL = 'https://neon.com/models'
24const SCHEMA = 'https://neon.com/schemas/ai-gateway-models.json'
25​
26interface ApiModel {
27 id: string
28 [key: string]: unknown
30​
31function isValidModel(model: unknown): model is ApiModel {
32 return (
33 typeof model === 'object' &&
34 model !== null &&
35 typeof (model as { id?: unknown }).id === 'string' &&
36 (model as { id: string }).id.length > 0
37 )
39​
40async function main() {
41 console.log(`Fetching models from ${API_URL}...`)
42​
43 const response = await fetch(API_URL, {
44 headers: { Accept: 'application/json' },
45 signal: AbortSignal.timeout(30_000),
46 })
47 if (!response.ok) {
48 throw new Error(
49 `Failed to fetch the Neon AI Gateway catalog: ${response.status} ${response.statusText}`,
50 )
51 }
52​
53 const json = (await response.json()) as {
54 $schema?: unknown
55 models?: unknown
56 }
57 if (json.$schema !== SCHEMA) {
58 throw new Error(
59 `The Neon catalog has $schema ${JSON.stringify(json.$schema)}, expected ${SCHEMA}`,
60 )
61 }
62 if (!Array.isArray(json.models)) {
63 throw new Error('The Neon catalog is missing a models array')
64 }
65​
66 const validModels = json.models.filter(isValidModel)
67 const skipped = json.models.length - validModels.length
68 if (skipped > 0) {
69 console.log(`Skipped ${skipped} models missing a string id`)
70 }
71​
72 // ponytail: `examples` is copy-paste code for the website, not model data.
73 const rows = validModels
74 .map(({ examples: _examples, ...model }) => model)
75 .sort((a, b) => a.id.localeCompare(b.id))
76​
77 await writeFile(OUTPUT_PATH, JSON.stringify(rows, null, 2) + '\n', 'utf-8')
78 console.log(`Fetched ${rows.length} models`)
79 console.log(`Written to ${OUTPUT_PATH}`)
81​
82main().catch((error) => {
83 console.error(error)
84 process.exit(1)
85})