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

convert-vercel-gateway-models.ts

381 lines11.5 KB

1/**
2 * Converts Vercel AI Gateway catalog rows into packages/ai-vercel-gateway/src/model-meta.ts.
3 *
4 * Usage:
5 * pnpm tsx scripts/convert-vercel-gateway-models.ts
6 */
7​
8import { writeFile } from 'node:fs/promises'
9import { dirname, resolve } from 'node:path'
10import { fileURLToPath, pathToFileURL } from 'node:url'
11import { models } from './vercel-gateway.models'
12import {
13 reasoningShapeName,
14 reasoningShapeTable,
15} from './model-sync/reasoning-shapes'
16import type { VercelGatewayCatalogModel } from './vercel-gateway.models'
17import type { ModelReasoning } from '@tanstack/ai'
18import type { ReasoningShape } from './model-sync/reasoning-shapes'
19​
20const __dirname = dirname(fileURLToPath(import.meta.url))
21const OUTPUT_PATH = resolve(
22 __dirname,
23 '../packages/ai-vercel-gateway/src/model-meta.ts',
25​
26type CatalogKind =
27 | 'language'
28 | 'embedding'
29 | 'image'
30 | 'video'
31 | 'reranking'
32 | 'other'
33​
34const TYPE_ALIASES: Record<string, CatalogKind> = {
35 language: 'language',
36 chat: 'language',
37 embedding: 'embedding',
38 embeddings: 'embedding',
39 image: 'image',
40 video: 'video',
41 reranking: 'reranking',
42 rerank: 'reranking',
44​
45function classifyModel(model: VercelGatewayCatalogModel): CatalogKind {
46 const type = typeof model.type === 'string' ? model.type.toLowerCase() : ''
47 if (type in TYPE_ALIASES) {
48 return TYPE_ALIASES[type]!
49 }
50​
51 const id = model.id
52 if (/embed/i.test(id)) return 'embedding'
53 if (/image|dall-e|imagen|flux|seedream/i.test(id)) return 'image'
54 if (/rerank/i.test(id)) return 'reranking'
55 if (/video|veo|sora|seedance/i.test(id)) return 'video'
56 return 'language'
58​
59type InputModality = 'text' | 'image' | 'audio' | 'video' | 'document'
60​
61const INPUT_MODALITY_ORDER: Array<InputModality> = [
62 'text',
63 'image',
64 'document',
65 'audio',
66 'video',
68​
69// `chat({ reasoning })` owns reasoning, so its params are not model options.
70const EXCLUDED_PARAMS = new Set([
71 'tools',
72 'tool_choice',
73 'reasoning',
74 'include_reasoning',
75 'reasoning_effort',
76])
77​
78const PARAM_NAME_MAP: Record<string, Array<string>> = {
79 max_tokens: ['max_tokens', 'max_output_tokens'],
80 max_completion_tokens: ['max_completion_tokens', 'max_output_tokens'],
81 temperature: ['temperature'],
82 top_p: ['top_p'],
83 stop: ['stop'],
84 seed: ['seed'],
85 frequency_penalty: ['frequency_penalty'],
86 presence_penalty: ['presence_penalty'],
87 response_format: ['response_format'],
88 structured_outputs: ['structured_outputs'],
90​
91function formatStringArray(ids: Array<string>): string {
92 if (ids.length === 0) {
93 return '[] as const'
94 }
95 return `[\n${ids.map((id) => ` ${JSON.stringify(id)},`).join('\n')}\n] as const`
97​
98function mapInputModality(modality: string): InputModality | null {
99 const mapping: Record<string, InputModality> = {
100 text: 'text',
101 image: 'image',
102 audio: 'audio',
103 video: 'video',
104 pdf: 'document',
105 file: 'document',
106 document: 'document',
107 }
108 return mapping[modality.toLowerCase()] ?? null
110​
111function uniqueSorted(values: Iterable<string>): Array<string> {
112 return [...new Set(values)].sort((a, b) => a.localeCompare(b))
114​
115function inputModalitiesFor(
116 model: VercelGatewayCatalogModel,
117): Array<InputModality> {
118 const mapped = (model.modalities?.input ?? [])
119 .map(mapInputModality)
120 .filter((modality): modality is InputModality => modality !== null)
121 if (!mapped.includes('text')) {
122 mapped.unshift('text')
123 }
124 return INPUT_MODALITY_ORDER.filter((modality) => mapped.includes(modality))
126​
127function optionKeysFor(model: VercelGatewayCatalogModel): Array<string> {
128 const keys = new Set<string>()
129 for (const param of model.supported_parameters ?? []) {
130 if (EXCLUDED_PARAMS.has(param)) continue
131 const mapped = PARAM_NAME_MAP[param] ?? [param]
132 for (const key of mapped) keys.add(key)
133 }
134 return [...keys]
136​
137function formatOptionType(keys: Array<string>): string {
138 if (keys.length === 0) {
139 return 'VercelGatewayCommonOptions'
140 }
141 return `VercelGatewayCommonOptions & Pick<VercelGatewayBaseOptions, ${keys
142 .map((key) => `'${key}'`)
143 .join(' | ')}>`
145​
146function formatModalitiesType(modalities: Array<InputModality>): string {
147 return `readonly [${modalities.map((modality) => `'${modality}'`).join(', ')}]`
149​
150/**
151 * The `reasoning` block: each chat model's data for `chat({ reasoning })`.
152 * The data comes from models.dev, which this script does not read, so the
153 * entries of the current file are kept.
154 */
155function formatReasoning(
156 chatIds: Array<string>,
157 existing: Readonly<Record<string, ModelReasoning>>,
158): string {
159 const shapes: Array<ReasoningShape> = []
160 const entries: Array<string> = []
161 for (const id of chatIds) {
162 const reasoning = existing[id]
163 if (!reasoning) continue
164 shapes.push(reasoning)
165 entries.push(` ${JSON.stringify(id)}: ${reasoningShapeName(reasoning)},`)
166 }
167 if (entries.length === 0) return ''
168 return `
169// Reasoning
170//
171// Each model's data for \`chat({ reasoning })\`: the levels it has, with the
172// provider value for each, and whether it takes a thinking token budget. The
173// data comes from models.dev. The generator that writes it comes with the
174// model catalog later. Until then, scripts/convert-vercel-gateway-models.ts
175// keeps the entries of the current file. Each model points at one shape.
176​
177${reasoningShapeTable(shapes).code}
178​
179const VERCEL_GATEWAY_REASONING = {
180${entries.join('\n')}
181} satisfies Partial<Record<VercelGatewayChatModel, ModelReasoning>>
182​
183/**
184 * Each chat model's reasoning levels, and whether it takes a token budget,
185 * for \`chat({ reasoning })\`. A model that is not here does not reason.
186 */
187export type VercelGatewayModelReasoningByName = {
188 [K in keyof typeof VERCEL_GATEWAY_REASONING]: ModelReasoningCapability<
189 (typeof VERCEL_GATEWAY_REASONING)[K]
190 >
192​
193/**
194 * Runtime map from chat model id to its reasoning data, for the text
195 * adapters. An unknown id gives \`undefined\`: the adapter sends no reasoning
196 * field.
197 */
198export const VERCEL_GATEWAY_MODEL_REASONING: Readonly<
199 Record<string, ModelReasoning>
200> = VERCEL_GATEWAY_REASONING
203​
204function convertModels(
205 existingReasoning: Readonly<Record<string, ModelReasoning>>,
206): string {
207 const chat: Array<VercelGatewayCatalogModel> = []
208 const embedding: Array<string> = []
209 const image: Array<string> = []
210 const providers = new Set<string>()
211 const tags = new Set<string>()
212 let video = 0
213 let reranking = 0
214 let other = 0
215​
216 for (const model of models) {
217 if (typeof model.owned_by === 'string' && model.owned_by.length > 0) {
218 providers.add(model.owned_by)
219 }
220 const kind = classifyModel(model)
221 switch (kind) {
222 case 'language':
223 chat.push(model)
224 for (const tag of model.tags ?? []) tags.add(tag)
225 break
226 case 'embedding':
227 embedding.push(model.id)
228 break
229 case 'image':
230 image.push(model.id)
231 break
232 case 'video':
233 video += 1
234 break
235 case 'reranking':
236 reranking += 1
237 break
238 default:
239 other += 1
240 }
241 }
242​
243 chat.sort((a, b) => a.id.localeCompare(b.id))
244 embedding.sort((a, b) => a.localeCompare(b))
245 image.sort((a, b) => a.localeCompare(b))
246​
247 if (chat.length === 0) {
248 throw new Error(
249 'Vercel AI Gateway catalog produced no chat models. Refusing to overwrite model-meta.ts.',
250 )
251 }
252 if (embedding.length === 0) {
253 throw new Error(
254 'Vercel AI Gateway catalog produced no embedding models. Refusing to overwrite model-meta.ts.',
255 )
256 }
257 if (image.length === 0) {
258 throw new Error(
259 'Vercel AI Gateway catalog produced no image models. Refusing to overwrite model-meta.ts.',
260 )
261 }
262​
263 console.log(
264 `Classified ${models.length} models: chat=${chat.length} embedding=${embedding.length} image=${image.length} video=${video} reranking=${reranking} other=${other}`,
265 )
266​
267 const chatIds = chat.map((model) => model.id)
268 const optionEntries = chat
269 .map(
270 (model) =>
271 ` ${JSON.stringify(model.id)}: ${formatOptionType(optionKeysFor(model))}`,
272 )
273 .join('\n')
274 const modalityEntries = chat
275 .map(
276 (model) =>
277 ` ${JSON.stringify(model.id)}: ${formatModalitiesType(inputModalitiesFor(model))}`,
278 )
279 .join('\n')
280​
281 return `/**
282 * This file is generated by scripts/convert-vercel-gateway-models.ts. Do not edit by hand.
283 */
284​
285import type { ModelReasoning } from '@tanstack/ai'
286import type { ModelReasoningCapability } from '@tanstack/ai/adapter-internals'
287import type { VercelGatewayEmbeddingProviderOptions } from './embedding/embedding-provider-options'
288import type {
289 VercelGatewayImageProviderOptions,
290 VercelGatewayImageSize,
291} from './image/image-provider-options'
292import type {
293 VercelGatewayBaseOptions,
294 VercelGatewayCommonOptions,
295 VercelGatewayTextProviderOptions,
296} from './text/text-provider-options'
297​
298export const VERCEL_GATEWAY_CHAT_MODELS = ${formatStringArray(chatIds)}
299​
300export type VercelGatewayChatModel = (typeof VERCEL_GATEWAY_CHAT_MODELS)[number]
301​
302export const VERCEL_GATEWAY_PROVIDERS = ${formatStringArray(uniqueSorted(providers))}
303​
304export type VercelGatewayProvider = (typeof VERCEL_GATEWAY_PROVIDERS)[number]
305​
306export const VERCEL_GATEWAY_MODEL_TAGS = ${formatStringArray(uniqueSorted(tags))}
307​
308export type VercelGatewayModelTag = (typeof VERCEL_GATEWAY_MODEL_TAGS)[number]
309​
310export const VERCEL_GATEWAY_EMBEDDING_MODELS = ${formatStringArray(embedding)}
311​
312export type VercelGatewayEmbeddingModel =
313 (typeof VERCEL_GATEWAY_EMBEDDING_MODELS)[number]
314​
315export const VERCEL_GATEWAY_IMAGE_MODELS = ${formatStringArray(image)}
316​
317export type VercelGatewayImageModel =
318 (typeof VERCEL_GATEWAY_IMAGE_MODELS)[number]
319​
320export type VercelGatewayChatModelProviderOptionsByName = {
321${optionEntries}
323​
324export type VercelGatewayModelInputModalitiesByName = {
325${modalityEntries}
327​
328export type VercelGatewayChatModelToolCapabilitiesByName = {
329 [K in VercelGatewayChatModel]: readonly []
331​
332export type VercelGatewayEmbeddingModelProviderOptionsByName = {
333 [K in VercelGatewayEmbeddingModel]: VercelGatewayEmbeddingProviderOptions
335​
336export type VercelGatewayEmbeddingModelInputModalitiesByName = {
337 [K in VercelGatewayEmbeddingModel]: readonly ['text']
339​
340export type VercelGatewayImageModelProviderOptionsByName = {
341 [K in VercelGatewayImageModel]: VercelGatewayImageProviderOptions
343​
344export type VercelGatewayImageModelSizeByName = {
345 [K in VercelGatewayImageModel]: VercelGatewayImageSize
347​
348export type VercelGatewayImageModelInputModalitiesByName = {
349 [K in VercelGatewayImageModel]: readonly []
351​
352export type ResolveProviderOptions<TModel extends string> =
353 TModel extends keyof VercelGatewayChatModelProviderOptionsByName
354 ? VercelGatewayChatModelProviderOptionsByName[TModel]
355 : TModel extends VercelGatewayEmbeddingModel
356 ? VercelGatewayEmbeddingProviderOptions
357 : TModel extends VercelGatewayImageModel
358 ? VercelGatewayImageProviderOptions
359 : VercelGatewayTextProviderOptions
360​
361export type ResolveInputModalities<TModel extends string> =
362 TModel extends keyof VercelGatewayModelInputModalitiesByName
363 ? VercelGatewayModelInputModalitiesByName[TModel]
364 : readonly ['text']
365${formatReasoning(chatIds, existingReasoning)}`
367​
368async function main() {
369 // ponytail: preserved, not generated. The models.dev generator comes with the model catalog.
370 const current = (await import(pathToFileURL(OUTPUT_PATH).href)) as {
371 VERCEL_GATEWAY_MODEL_REASONING?: Readonly<Record<string, ModelReasoning>>
372 }
373 const file = convertModels(current.VERCEL_GATEWAY_MODEL_REASONING ?? {})
374 await writeFile(OUTPUT_PATH, file, 'utf-8')
375 console.log(`Model meta file written to ${OUTPUT_PATH}`)
377​
378main().catch((error) => {
379 console.error(error)
380 process.exit(1)
381})