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

sync-provider-models.ts

572 lines20.5 KB

1/**
2 * Syncs modelschemas catalogs into native provider model-meta.ts files.
3 *
4 * For each synced provider, this script:
5 * 1. Lists that provider's models from modelschemas (`@modelschemas/client`)
6 * 2. Uses native limits, modalities, pricing, and capabilities. Fills any
7 * field the native row left empty from the modelschemas OpenRouter catalog
8 * 3. Identifies models missing from the provider's model-meta.ts
9 * 4. Generates and inserts new model constants, array entries, and type map entries
10 *
11 * Usage:
12 * pnpm tsx scripts/sync-provider-models.ts
13 *
14 * Optional: MODELSCHEMAS_API_KEY raises the modelschemas rate limit.
15 *
16 * ## Providers deliberately NOT synced
17 *
18 * - **fal** — 1k+ model-grained endpoints; image field maps have their own
19 * generator (`scripts/generate-fal-image-field-map.ts`).
20 * - **elevenlabs** — id arrays, not ModelMeta constants; see
21 * `scripts/sync-elevenlabs-models.ts`.
22 * - **bedrock** — ids are AWS-region-qualified; see
23 * `scripts/fetch-bedrock-models.ts`.
24 * - **ollama**, **llmgateway**, **vercel-gateway**, **lovable** — different
25 * catalogs (local, aggregator, or their own fetch scripts).
26 * - **claude-code**, **codex**, **opencode**, **grok-build** — harness aliases.
27 * BytePlus video/image duration and size tables stay hand-curated.
28 */
29​
30import { execFileSync } from 'node:child_process'
31import { readFile, writeFile } from 'node:fs/promises'
32import { dirname, resolve } from 'node:path'
33import { fileURLToPath } from 'node:url'
34import { writeSyncChangeset } from './model-sync/changeset'
35import {
36 alreadySynced,
37 outputsText,
38 pricingLines,
39 selectNativeInserts,
40} from './model-sync/catalog'
41import type { CatalogModel, SyncModel } from './model-sync/catalog'
42import { toModelConstName } from './model-sync/ids'
43import {
44 applyChatModelCatalogInserts,
45 insertConstants,
46} from './model-sync/native-insert'
47import { createSyncClient, fetchSyncCatalogs } from './model-sync/modelschemas'
48import {
49 buildAnthropicProviderOptionsType,
50 buildProviderSupportsBody,
51} from './model-sync/provider-supports'
52import type { ArrayRef } from './model-sync/native-insert'
53import type { SyncedProvider } from './model-sync/provider-supports'
54​
55const __dirname = dirname(fileURLToPath(import.meta.url))
56const ROOT = resolve(__dirname, '..')
57​
58/** Seconds in 30 days — models older than this before the last sync are skipped */
59const MAX_MODEL_AGE_SECONDS = 30 * 24 * 60 * 60
60const LAST_RUN_FILE = resolve(ROOT, 'scripts/.sync-models-last-run')
61​
62interface ProviderConfig {
63 packageName: string
64 metaFile: string
65 /** How array entries reference the constant, e.g. '.name' or '.id' */
66 arrayRef: ArrayRef
67 /** Which field name is used for context window size */
68 contextField: 'context_window' | 'max_input_tokens'
69 /** Name of the exported chat model array */
70 chatArrayName: string
71 /** Name of the provider options type map */
72 providerOptionsTypeName: string
73 /** Name of the input modalities type map */
74 inputModalitiesTypeName: string
75 /**
76 * Name of the per-model tool-capabilities type map. Missing this lets
77 * `ResolveToolCapabilities` fall back to `readonly []` and every provider
78 * tool stops type-checking on the new model.
79 */
80 toolCapabilitiesTypeName?: string
81 /**
82 * Name of the runtime `Record<string, number>` mapping model id →
83 * `max_output_tokens`, if the provider maintains one. Anthropic uses this to
84 * default the required `max_tokens` request field to the model's real ceiling
85 * (issue #849); other providers treat token limits as optional and omit it.
86 */
87 maxOutputTokensMapName?: string
88 /**
89 * Runtime set of models that accept tools plus `output_config.format` in
90 * one request. New Anthropic ids are inserted here. `-fast` variants stay
91 * out: fast mode is a request parameter, not a model id, and the model-meta
92 * test expects every registered model in the set.
93 */
94 combinedToolsAndSchemaSetName?: string
95 /** Valid input modality types for this provider's ModelMeta interface */
96 validInputModalities: Array<InputModality>
97 /** The satisfies type clause (after 'as const satisfies') */
98 referenceSatisfies: string
99 /** The type string for provider options map entries */
100 referenceProviderOptionsEntry: string
101 /** Whether this provider has both name AND id fields */
102 hasBothNameAndId: boolean
103 /** Whether the provider options type is a mapped type (skip insertion) */
104 providerOptionsIsMappedType: boolean
105 /** Raw-id prefixes to always skip */
106 skipPatterns: Array<string>
107 /** Activities to insert. `null` means the catalog left activity unset. */
108 acceptedActivities: Array<string | null>
109 /** See `NativeInsertRules.requireOpenRouterEnrich`. */
110 requireOpenRouterEnrich: boolean
111 /**
112 * Write a `pricing` block. An unknown side is left out, never written as
113 * 0, so Groq/Mistral can insert with `pricing: {}`. BytePlus has none.
114 */
115 includePricing: boolean
116 outputTokenField: 'max_output_tokens' | 'max_completion_tokens'
118​
119const PROVIDER_MAP: Record<SyncedProvider, ProviderConfig> = {
120 openai: {
121 packageName: '@tanstack/ai-openai',
122 metaFile: resolve(ROOT, 'packages/ai-openai/src/model-meta.ts'),
123 arrayRef: '.name',
124 contextField: 'context_window',
125 chatArrayName: 'OPENAI_CHAT_MODELS',
126 providerOptionsTypeName: 'OpenAIChatModelProviderOptionsByName',
127 inputModalitiesTypeName: 'OpenAIModelInputModalitiesByName',
128 toolCapabilitiesTypeName: 'OpenAIChatModelToolCapabilitiesByName',
129 validInputModalities: ['text', 'image', 'audio', 'video'],
130 referenceSatisfies:
131 'ModelMeta<OpenAIBaseOptions & OpenAIStructuredOutputOptions & OpenAIToolsOptions & OpenAIStreamingOptions & OpenAIMetadataOptions>',
132 referenceProviderOptionsEntry:
133 'OpenAIBaseOptions & OpenAIStructuredOutputOptions & OpenAIToolsOptions & OpenAIStreamingOptions & OpenAIMetadataOptions',
134 hasBothNameAndId: false,
135 providerOptionsIsMappedType: false,
136 skipPatterns: [
137 'gpt-3.5-', // Legacy GPT-3.5 models
138 'gpt-4-', // Legacy GPT-4 base models (not 4.1+)
139 'gpt-4o', // GPT-4o variants (4o, 4o-mini, 4o-audio, etc.)
140 'gpt-oss-', // Open-source/experimental models
141 'chatgpt-', // ChatGPT branded models
142 ],
143 acceptedActivities: ['chat'],
144 requireOpenRouterEnrich: true,
145 includePricing: true,
146 outputTokenField: 'max_output_tokens',
147 },
148 anthropic: {
149 packageName: '@tanstack/ai-anthropic',
150 metaFile: resolve(ROOT, 'packages/ai-anthropic/src/model-meta.ts'),
151 arrayRef: '.id',
152 contextField: 'context_window',
153 chatArrayName: 'ANTHROPIC_MODELS',
154 providerOptionsTypeName: 'AnthropicChatModelProviderOptionsByName',
155 inputModalitiesTypeName: 'AnthropicModelInputModalitiesByName',
156 toolCapabilitiesTypeName: 'AnthropicChatModelToolCapabilitiesByName',
157 maxOutputTokensMapName: 'ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS',
158 combinedToolsAndSchemaSetName: 'ANTHROPIC_COMBINED_TOOLS_AND_SCHEMA_MODELS',
159 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
160 referenceSatisfies:
161 'ModelMeta<AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicToolChoiceOptions & AnthropicSamplingOptions>',
162 referenceProviderOptionsEntry:
163 'AnthropicContainerOptions & AnthropicContextManagementOptions & AnthropicMCPOptions & AnthropicServiceTierOptions & AnthropicStopSequencesOptions & AnthropicToolChoiceOptions & AnthropicSamplingOptions',
164 hasBothNameAndId: true,
165 providerOptionsIsMappedType: false,
166 skipPatterns: [],
167 acceptedActivities: ['chat'],
168 requireOpenRouterEnrich: true,
169 includePricing: true,
170 outputTokenField: 'max_output_tokens',
171 },
172 gemini: {
173 packageName: '@tanstack/ai-gemini',
174 metaFile: resolve(ROOT, 'packages/ai-gemini/src/model-meta.ts'),
175 arrayRef: '.name',
176 contextField: 'max_input_tokens',
177 chatArrayName: 'GEMINI_MODELS',
178 providerOptionsTypeName: 'GeminiChatModelProviderOptionsByName',
179 inputModalitiesTypeName: 'GeminiModelInputModalitiesByName',
180 toolCapabilitiesTypeName: 'GeminiChatModelToolCapabilitiesByName',
181 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
182 referenceSatisfies:
183 'ModelMeta<GeminiToolConfigOptions & GeminiSafetyOptions & GeminiCommonConfigOptions & GeminiCachedContentOptions & GeminiStructuredOutputOptions>',
184 referenceProviderOptionsEntry:
185 'GeminiToolConfigOptions & GeminiSafetyOptions & GeminiCommonConfigOptions & GeminiCachedContentOptions & GeminiStructuredOutputOptions',
186 hasBothNameAndId: false,
187 providerOptionsIsMappedType: false,
188 skipPatterns: [
189 'gemma-', // Gemma open-source models (not Gemini API models)
190 ],
191 acceptedActivities: ['chat'],
192 requireOpenRouterEnrich: true,
193 includePricing: true,
194 outputTokenField: 'max_output_tokens',
195 },
196 grok: {
197 packageName: '@tanstack/ai-grok',
198 metaFile: resolve(ROOT, 'packages/ai-grok/src/model-meta.ts'),
199 arrayRef: '.name',
200 contextField: 'context_window',
201 chatArrayName: 'GROK_CHAT_MODELS',
202 providerOptionsTypeName: 'GrokChatModelProviderOptionsByName',
203 inputModalitiesTypeName: 'GrokModelInputModalitiesByName',
204 toolCapabilitiesTypeName: 'GrokChatModelToolCapabilitiesByName',
205 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
206 referenceSatisfies: 'ModelMeta',
207 referenceProviderOptionsEntry: 'GrokProviderOptions',
208 hasBothNameAndId: false,
209 providerOptionsIsMappedType: true,
210 skipPatterns: [],
211 acceptedActivities: ['chat'],
212 requireOpenRouterEnrich: true,
213 includePricing: true,
214 outputTokenField: 'max_output_tokens',
215 },
216 groq: {
217 packageName: '@tanstack/ai-groq',
218 metaFile: resolve(ROOT, 'packages/ai-groq/src/model-meta.ts'),
219 arrayRef: '.name',
220 contextField: 'context_window',
221 chatArrayName: 'GROQ_CHAT_MODELS',
222 providerOptionsTypeName: 'GroqChatModelProviderOptionsByName',
223 inputModalitiesTypeName: 'GroqModelInputModalitiesByName',
224 toolCapabilitiesTypeName: 'GroqChatModelToolCapabilitiesByName',
225 validInputModalities: ['text', 'image', 'audio'],
226 referenceSatisfies: 'ModelMeta<GroqTextProviderOptions>',
227 referenceProviderOptionsEntry: 'GroqTextProviderOptions',
228 hasBothNameAndId: false,
229 providerOptionsIsMappedType: true,
230 skipPatterns: ['whisper-', 'canopylabs/'],
231 acceptedActivities: [null, 'chat'],
232 requireOpenRouterEnrich: false,
233 includePricing: true,
234 outputTokenField: 'max_completion_tokens',
235 },
236 mistral: {
237 packageName: '@tanstack/ai-mistral',
238 metaFile: resolve(ROOT, 'packages/ai-mistral/src/model-meta.ts'),
239 arrayRef: '.name',
240 contextField: 'context_window',
241 chatArrayName: 'MISTRAL_CHAT_MODELS',
242 providerOptionsTypeName: 'MistralChatModelProviderOptionsByName',
243 inputModalitiesTypeName: 'MistralModelInputModalitiesByName',
244 validInputModalities: ['text', 'image', 'audio', 'document'],
245 referenceSatisfies: 'ModelMeta<MistralTextProviderOptions>',
246 referenceProviderOptionsEntry: 'MistralTextProviderOptions',
247 hasBothNameAndId: false,
248 providerOptionsIsMappedType: false,
249 skipPatterns: [
250 'mistral-embed',
251 'codestral-embed',
252 'mistral-ocr',
253 'mistral-moderation',
254 'voxtral-',
255 'mistral-vibe',
256 'mistral-code-fim',
257 'mistral-code-',
258 'glm-',
259 'zai-',
260 ],
261 acceptedActivities: [null, 'chat'],
262 requireOpenRouterEnrich: false,
263 includePricing: true,
264 outputTokenField: 'max_completion_tokens',
265 },
266 byteplus: {
267 packageName: '@tanstack/ai-byteplus',
268 metaFile: resolve(ROOT, 'packages/ai-byteplus/src/model-meta.ts'),
269 arrayRef: '.name',
270 contextField: 'context_window',
271 chatArrayName: 'BYTEPLUS_CHAT_MODELS',
272 providerOptionsTypeName: 'BytePlusChatModelProviderOptionsByName',
273 inputModalitiesTypeName: 'BytePlusModelInputModalitiesByName',
274 validInputModalities: ['text', 'image', 'audio', 'video', 'document'],
275 referenceSatisfies: 'ModelMeta',
276 referenceProviderOptionsEntry: 'BytePlusTextProviderOptions',
277 hasBothNameAndId: false,
278 providerOptionsIsMappedType: true,
279 skipPatterns: [],
280 acceptedActivities: ['chat'],
281 requireOpenRouterEnrich: false,
282 includePricing: false,
283 outputTokenField: 'max_output_tokens',
284 },
286​
287type InputModality = 'text' | 'image' | 'audio' | 'video' | 'document'
288​
289const MODALITY_MAP: Record<string, InputModality> = {
290 text: 'text',
291 image: 'image',
292 audio: 'audio',
293 video: 'video',
294 file: 'document',
295 document: 'document',
297​
298function mapInputModalities(modalities: Array<string>): Array<InputModality> {
299 const mapped = modalities
300 .map((m) => MODALITY_MAP[m.toLowerCase()])
301 .filter((m): m is InputModality => m !== undefined)
302 if (!mapped.includes('text')) {
303 mapped.unshift('text')
304 }
305 return mapped
307​
308function anthropicOptionsType(model: SyncModel): string {
309 return buildAnthropicProviderOptionsType({
310 supportedParameters: model.supportedParameters,
311 // modelschemas has no cache price, and every current Claude model
312 // supports prompt caching.
313 hasCachedPricing: true,
314 })
316​
317function providerOptionsEntryFor(
318 model: SyncModel,
319 provider: SyncedProvider,
320 config: ProviderConfig,
321): string {
322 if (provider === 'anthropic') return anthropicOptionsType(model)
323 return config.referenceProviderOptionsEntry
325​
326function satisfiesClause(
327 model: SyncModel,
328 provider: SyncedProvider,
329 config: ProviderConfig,
330): string {
331 if (provider === 'anthropic') {
332 return `ModelMeta<${anthropicOptionsType(model)}>`
333 }
334 return config.referenceSatisfies
336​
337function extractExistingModelIds(content: string): Set<string> {
338 return new Set(
339 Array.from(content.matchAll(/^\s+(?:name|id):\s*'([^']+)'/gm), (m) =>
340 m[1]!.replaceAll('.', '-'),
341 ),
342 )
344​
345function extractExistingConstNames(content: string): Set<string> {
346 return new Set(
347 Array.from(
348 content.matchAll(/^const\s+([A-Z][A-Z0-9_]+)\s*=/gm),
349 (m) => m[1]!,
350 ),
351 )
353​
354async function readLastRunTimestamp(): Promise<number | null> {
355 let content: string
356 try {
357 content = await readFile(LAST_RUN_FILE, 'utf-8')
358 } catch (error) {
359 // First run. Any other read error must not silently reset the cutoff.
360 if (isNodeError(error) && error.code === 'ENOENT') return null
361 throw error
362 }
363 const ts = parseInt(content.trim(), 10)
364 if (isNaN(ts)) throw new Error(`${LAST_RUN_FILE} is not a timestamp`)
365 return ts
367​
368function isNodeError(error: unknown): error is NodeJS.ErrnoException {
369 return error instanceof Error && 'code' in error
371​
372async function writeLastRunTimestamp(): Promise<void> {
373 const now = Math.floor(Date.now() / 1000)
374 await writeFile(LAST_RUN_FILE, String(now) + '\n', 'utf-8')
376​
377function generateModelConstant(
378 model: SyncModel,
379 provider: SyncedProvider,
380 config: ProviderConfig,
381): string {
382 const constName = toModelConstName(model.nativeId)
383​
384 const inputModalities = mapInputModalities(model.inputModalities).filter(
385 (m) => config.validInputModalities.includes(m),
386 )
387​
388 const lines: Array<string> = []
389 lines.push(`const ${constName} = {`)
390 lines.push(` name: '${model.nativeId}',`)
391 if (config.hasBothNameAndId) {
392 lines.push(` id: '${model.nativeId}',`)
393 }
394 if (isPositive(model.contextWindow)) {
395 lines.push(
396 ` ${config.contextField}: ${formatNumber(model.contextWindow)},`,
397 )
398 }
399 if (isPositive(model.maxOutput)) {
400 lines.push(
401 ` ${config.outputTokenField}: ${formatNumber(model.maxOutput)},`,
402 )
403 }
404 lines.push(` supports: {`)
405 lines.push(
406 buildProviderSupportsBody({
407 provider,
408 inputModalities,
409 outputModalities: model.outputModalities,
410 supportedParameters: model.supportedParameters,
411 reasoningMandatory: model.reasoningMandatory,
412 }),
413 )
414 lines.push(` },`)
415 if (config.includePricing) {
416 lines.push(...pricingLines(model.pricing))
417 }
418 lines.push(`} as const satisfies ${satisfiesClause(model, provider, config)}`)
419 return lines.join('\n')
421​
422function isPositive(n: number | null): n is number {
423 return n != null && n > 0
425​
426/** 1048576 → 1_048_576 */
427function formatNumber(n: number): string {
428 return n.toLocaleString('en-US').replaceAll(',', '_')
430​
431/** Packages the fetch scripts changed, so the changeset covers them too. */
432function detectChangedPackages(): Set<string> {
433 const diff = execFileSync(
434 'git',
435 ['diff', 'HEAD', '--name-only', '--', 'packages/'],
436 { encoding: 'utf-8', cwd: ROOT },
437 )
438 const changed = new Set<string>()
439 for (const match of diff.matchAll(/^packages\/([\w-]+)\//gm)) {
440 changed.add(`@tanstack/${match[1]}`)
441 }
442 return changed
444​
445async function syncModelMeta(
446 provider: SyncedProvider,
447 config: ProviderConfig,
448 catalogs: {
449 native: Record<SyncedProvider, Array<CatalogModel>>
450 openrouter: Array<CatalogModel>
451 },
452 cutoffTimestamp: number,
453): Promise<{ added: number; heldBack: number }> {
454 console.log(`\nProcessing provider: ${provider}`)
455 const rows = catalogs.native[provider]
456 console.log(` Found ${rows.length} modelschemas models for '${provider}'`)
457​
458 let content = await readFile(config.metaFile, 'utf-8')
459 const existingIds = extractExistingModelIds(content)
460 const existingConstNames = extractExistingConstNames(content)
461 console.log(
462 ` Existing models in file: ${existingIds.size} IDs, ${existingConstNames.size} constants`,
463 )
464​
465 const { inserts, heldBack, skipped } = selectNativeInserts(
466 rows,
467 { ...config, provider, cutoffTimestamp },
468 catalogs.openrouter,
469 (nativeId) => alreadySynced(nativeId, existingIds, existingConstNames),
470 )
471 const skipCounts = Object.entries(skipped)
472 .map(([reason, count]) => `${reason}=${count}`)
473 .join(', ')
474 if (skipCounts) console.log(` Skipped: ${skipCounts}`)
475 for (const rawId of heldBack) {
476 console.log(` Waiting for an OpenRouter price: ${rawId}`)
477 }
478​
479 if (inserts.length === 0) {
480 console.log(' No new models to add.')
481 return { added: 0, heldBack: heldBack.length }
482 }
483​
484 console.log(` Adding ${inserts.length} new models:`)
485 for (const { model } of inserts) {
486 console.log(` - ${model.nativeId} (${toModelConstName(model.nativeId)})`)
487 }
488​
489 content = insertConstants(
490 content,
491 inserts.map(({ model }) => generateModelConstant(model, provider, config)),
492 )
493 content = applyChatModelCatalogInserts(
494 content,
495 config,
496 inserts
497 .filter(({ model, activity }) => outputsText(model, activity))
498 .map(({ model }) => ({
499 constName: toModelConstName(model.nativeId),
500 providerOptionsEntry: providerOptionsEntryFor(model, provider, config),
501 hasMaxOutputTokens: isPositive(model.maxOutput),
502 acceptsCombinedToolsAndSchema: !model.nativeId.endsWith('-fast'),
503 })),
504 )
505​
506 await writeFile(config.metaFile, content, 'utf-8')
507 console.log(` Wrote updated file: ${config.metaFile}`)
508 return { added: inserts.length, heldBack: heldBack.length }
510​
511async function main() {
512 const lastRun = await readLastRunTimestamp()
513 const now = Math.floor(Date.now() / 1000)
514 const cutoffTimestamp = (lastRun ?? now) - MAX_MODEL_AGE_SECONDS
515 const cutoffDate = new Date(cutoffTimestamp * 1000)
516 .toISOString()
517 .split('T')[0]
518 console.log(
519 `Model age cutoff: ${cutoffDate} (skipping models created before this date)`,
520 )
521​
522 const catalogs = await fetchSyncCatalogs(createSyncClient())
523 const counts = Object.entries(catalogs.native)
524 .map(([id, rows]) => `${id}=${rows.length}`)
525 .join(', ')
526 console.log(
527 `Fetched modelschemas catalogs: ${counts}, openrouter=${catalogs.openrouter.length}`,
528 )
529​
530 const changedPackages = new Set<string>()
531 let totalAdded = 0
532 let totalHeldBack = 0
533 for (const [provider, config] of Object.entries(PROVIDER_MAP) as Array<
534 [SyncedProvider, ProviderConfig]
535 >) {
536 const { added, heldBack } = await syncModelMeta(
537 provider,
538 config,
539 catalogs,
540 cutoffTimestamp,
541 )
542 totalAdded += added
543 totalHeldBack += heldBack
544 if (added > 0) changedPackages.add(config.packageName)
545 }
546​
547 console.log(`\nDone. Added ${totalAdded} new models total.`)
548​
549 // Held-back ids still age out after 30 days. Freezing the timestamp
550 // instead would stall it for good on ids OpenRouter never prices (Live
551 // API models), so each run names them in its log.
552 if (totalHeldBack > 0) {
553 console.log(
554 `${totalHeldBack} models are waiting for an OpenRouter price (listed above).`,
555 )
556 }
557 await writeLastRunTimestamp()
558​
559 const allChangedPackages = detectChangedPackages()
560 for (const pkg of changedPackages) {
561 allChangedPackages.add(pkg)
562 }
563​
564 if (allChangedPackages.size > 0) {
565 await writeSyncChangeset(ROOT, allChangedPackages)
566 }
568​
569main().catch((err) => {
570 console.error(err)
571 process.exit(1)
572})