Open History to see the last commit
1/**
2 * Writes each provider package's model catalog (its `./models` subpath) from
3 * modelschemas, and a patch changeset for each package whose models changed.
4 * One call. Set `MODELSCHEMAS_API_KEY` for a higher rate limit.
5 *
6 * Usage:
7 * node scripts/sync-model-catalogs.ts
8 */
9
10import { existsSync } from 'node:fs'
11import { readFile, writeFile } from 'node:fs/promises'
12import { dirname, resolve } from 'node:path'
13import { fileURLToPath, pathToFileURL } from 'node:url'
14import { listModels } from '@modelschemas/client'
15import { writeSyncChangeset } from './model-sync/changeset.ts'
16import {
17 CATALOGS,
18 buildRecords,
19 isChatModel,
20} from './model-sync/model-catalog.ts'
21import { createSyncClient } from './model-sync/client.ts'
22
23const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
24
25const { data: body, error } = await listModels({
26 client: createSyncClient(),
27 query: { activity: 'chat', pricing: '1', provenance: '0' },
28})
29if (!body) throw new Error(`modelschemas list failed: ${JSON.stringify(error)}`)
30if (body.models.length !== body.count)
31 throw new Error(
32 `modelschemas sent ${body.models.length} of ${body.count} models`,
33 )
34
35const changed = new Set<string>()
36for (const catalog of CATALOGS) {
37 const rows = body.models.filter(
38 (model) => model.provider === catalog.source && isChatModel(model),
39 )
40 if (rows.length === 0)
41 throw new Error(`modelschemas has no chat models for '${catalog.source}'`)
42 const records = buildRecords(rows)
43 const file = resolve(ROOT, catalog.file)
44 const before: unknown = existsSync(file)
45 ? (await import(pathToFileURL(file).href)).models
46 : undefined
47 if (JSON.stringify(before) === JSON.stringify(records)) continue
48 await writeFile(
49 file,
50 `// Generated by scripts/sync-model-catalogs.ts from modelschemas. Do not edit.
51import type { ModelRecord } from '@tanstack/ai'
52
53/** Every ${catalog.name} chat model on modelschemas.com, sorted by id. */
54export const models: ReadonlyArray<ModelRecord> = ${JSON.stringify(records)}
55`,
56 )
57 const packageJson = resolve(dirname(file), '..', 'package.json')
58 changed.add(JSON.parse(await readFile(packageJson, 'utf8')).name)
59 console.log(`${catalog.file}: ${records.length} models`)
60}
61
62if (changed.size > 0) await writeSyncChangeset(ROOT, changed)