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

convert-vercel-gateway-models.ts

308 lines8.9 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 } from 'node:url'
11import { models } from './vercel-gateway.models'
12import type { VercelGatewayCatalogModel } from './vercel-gateway.models'
13​
14const __dirname = dirname(fileURLToPath(import.meta.url))
15const OUTPUT_PATH = resolve(
16 __dirname,
17 '../packages/ai-vercel-gateway/src/model-meta.ts',
19​
20type CatalogKind =
21 | 'language'
22 | 'embedding'
23 | 'image'
24 | 'video'
25 | 'reranking'
26 | 'other'
27​
28const TYPE_ALIASES: Record<string, CatalogKind> = {
29 language: 'language',
30 chat: 'language',
31 embedding: 'embedding',
32 embeddings: 'embedding',
33 image: 'image',
34 video: 'video',
35 reranking: 'reranking',
36 rerank: 'reranking',
38​
39function classifyModel(model: VercelGatewayCatalogModel): CatalogKind {
40 const type = typeof model.type === 'string' ? model.type.toLowerCase() : ''
41 if (type in TYPE_ALIASES) {
42 return TYPE_ALIASES[type]!
43 }
44​
45 const id = model.id
46 if (/embed/i.test(id)) return 'embedding'
47 if (/image|dall-e|imagen|flux|seedream/i.test(id)) return 'image'
48 if (/rerank/i.test(id)) return 'reranking'
49 if (/video|veo|sora|seedance/i.test(id)) return 'video'
50 return 'language'
52​
53type InputModality = 'text' | 'image' | 'audio' | 'video' | 'document'
54​
55const INPUT_MODALITY_ORDER: Array<InputModality> = [
56 'text',
57 'image',
58 'document',
59 'audio',
60 'video',
62​
63const EXCLUDED_PARAMS = new Set(['tools', 'tool_choice'])
64​
65const PARAM_NAME_MAP: Record<string, Array<string>> = {
66 max_tokens: ['max_tokens', 'max_output_tokens'],
67 max_completion_tokens: ['max_completion_tokens', 'max_output_tokens'],
68 temperature: ['temperature'],
69 top_p: ['top_p'],
70 stop: ['stop'],
71 seed: ['seed'],
72 frequency_penalty: ['frequency_penalty'],
73 presence_penalty: ['presence_penalty'],
74 reasoning: ['reasoning'],
75 include_reasoning: ['include_reasoning'],
76 response_format: ['response_format'],
77 structured_outputs: ['structured_outputs'],
79​
80function formatStringArray(ids: Array<string>): string {
81 if (ids.length === 0) {
82 return '[] as const'
83 }
84 return `[\n${ids.map((id) => ` ${JSON.stringify(id)},`).join('\n')}\n] as const`
86​
87function mapInputModality(modality: string): InputModality | null {
88 const mapping: Record<string, InputModality> = {
89 text: 'text',
90 image: 'image',
91 audio: 'audio',
92 video: 'video',
93 pdf: 'document',
94 file: 'document',
95 document: 'document',
96 }
97 return mapping[modality.toLowerCase()] ?? null
99​
100function uniqueSorted(values: Iterable<string>): Array<string> {
101 return [...new Set(values)].sort((a, b) => a.localeCompare(b))
103​
104function inputModalitiesFor(
105 model: VercelGatewayCatalogModel,
106): Array<InputModality> {
107 const mapped = (model.modalities?.input ?? [])
108 .map(mapInputModality)
109 .filter((modality): modality is InputModality => modality !== null)
110 if (!mapped.includes('text')) {
111 mapped.unshift('text')
112 }
113 return INPUT_MODALITY_ORDER.filter((modality) => mapped.includes(modality))
115​
116function optionKeysFor(model: VercelGatewayCatalogModel): Array<string> {
117 const keys = new Set<string>()
118 for (const param of model.supported_parameters ?? []) {
119 if (EXCLUDED_PARAMS.has(param)) continue
120 const mapped = PARAM_NAME_MAP[param] ?? [param]
121 for (const key of mapped) keys.add(key)
122 }
123 return [...keys]
125​
126function formatOptionType(keys: Array<string>): string {
127 if (keys.length === 0) {
128 return 'VercelGatewayCommonOptions'
129 }
130 return `VercelGatewayCommonOptions & Pick<VercelGatewayBaseOptions, ${keys
131 .map((key) => `'${key}'`)
132 .join(' | ')}>`
134​
135function formatModalitiesType(modalities: Array<InputModality>): string {
136 return `readonly [${modalities.map((modality) => `'${modality}'`).join(', ')}]`
138​
139function convertModels(): string {
140 const chat: Array<VercelGatewayCatalogModel> = []
141 const embedding: Array<string> = []
142 const image: Array<string> = []
143 const providers = new Set<string>()
144 const tags = new Set<string>()
145 let video = 0
146 let reranking = 0
147 let other = 0
148​
149 for (const model of models) {
150 if (typeof model.owned_by === 'string' && model.owned_by.length > 0) {
151 providers.add(model.owned_by)
152 }
153 const kind = classifyModel(model)
154 switch (kind) {
155 case 'language':
156 chat.push(model)
157 for (const tag of model.tags ?? []) tags.add(tag)
158 break
159 case 'embedding':
160 embedding.push(model.id)
161 break
162 case 'image':
163 image.push(model.id)
164 break
165 case 'video':
166 video += 1
167 break
168 case 'reranking':
169 reranking += 1
170 break
171 default:
172 other += 1
173 }
174 }
175​
176 chat.sort((a, b) => a.id.localeCompare(b.id))
177 embedding.sort((a, b) => a.localeCompare(b))
178 image.sort((a, b) => a.localeCompare(b))
179​
180 if (chat.length === 0) {
181 throw new Error(
182 'Vercel AI Gateway catalog produced no chat models. Refusing to overwrite model-meta.ts.',
183 )
184 }
185 if (embedding.length === 0) {
186 throw new Error(
187 'Vercel AI Gateway catalog produced no embedding models. Refusing to overwrite model-meta.ts.',
188 )
189 }
190 if (image.length === 0) {
191 throw new Error(
192 'Vercel AI Gateway catalog produced no image models. Refusing to overwrite model-meta.ts.',
193 )
194 }
195​
196 console.log(
197 `Classified ${models.length} models: chat=${chat.length} embedding=${embedding.length} image=${image.length} video=${video} reranking=${reranking} other=${other}`,
198 )
199​
200 const chatIds = chat.map((model) => model.id)
201 const optionEntries = chat
202 .map(
203 (model) =>
204 ` ${JSON.stringify(model.id)}: ${formatOptionType(optionKeysFor(model))}`,
205 )
206 .join('\n')
207 const modalityEntries = chat
208 .map(
209 (model) =>
210 ` ${JSON.stringify(model.id)}: ${formatModalitiesType(inputModalitiesFor(model))}`,
211 )
212 .join('\n')
213​
214 return `/**
215 * This file is generated by scripts/convert-vercel-gateway-models.ts. Do not edit by hand.
216 */
217​
218import type { VercelGatewayEmbeddingProviderOptions } from './embedding/embedding-provider-options'
219import type {
220 VercelGatewayImageProviderOptions,
221 VercelGatewayImageSize,
222} from './image/image-provider-options'
223import type {
224 VercelGatewayBaseOptions,
225 VercelGatewayCommonOptions,
226 VercelGatewayTextProviderOptions,
227} from './text/text-provider-options'
228​
229export const VERCEL_GATEWAY_CHAT_MODELS = ${formatStringArray(chatIds)}
230​
231export type VercelGatewayChatModel = (typeof VERCEL_GATEWAY_CHAT_MODELS)[number]
232​
233export const VERCEL_GATEWAY_PROVIDERS = ${formatStringArray(uniqueSorted(providers))}
234​
235export type VercelGatewayProvider = (typeof VERCEL_GATEWAY_PROVIDERS)[number]
236​
237export const VERCEL_GATEWAY_MODEL_TAGS = ${formatStringArray(uniqueSorted(tags))}
238​
239export type VercelGatewayModelTag = (typeof VERCEL_GATEWAY_MODEL_TAGS)[number]
240​
241export const VERCEL_GATEWAY_EMBEDDING_MODELS = ${formatStringArray(embedding)}
242​
243export type VercelGatewayEmbeddingModel =
244 (typeof VERCEL_GATEWAY_EMBEDDING_MODELS)[number]
245​
246export const VERCEL_GATEWAY_IMAGE_MODELS = ${formatStringArray(image)}
247​
248export type VercelGatewayImageModel =
249 (typeof VERCEL_GATEWAY_IMAGE_MODELS)[number]
250​
251export type VercelGatewayChatModelProviderOptionsByName = {
252${optionEntries}
254​
255export type VercelGatewayModelInputModalitiesByName = {
256${modalityEntries}
258​
259export type VercelGatewayChatModelToolCapabilitiesByName = {
260 [K in VercelGatewayChatModel]: readonly []
262​
263export type VercelGatewayEmbeddingModelProviderOptionsByName = {
264 [K in VercelGatewayEmbeddingModel]: VercelGatewayEmbeddingProviderOptions
266​
267export type VercelGatewayEmbeddingModelInputModalitiesByName = {
268 [K in VercelGatewayEmbeddingModel]: readonly ['text']
270​
271export type VercelGatewayImageModelProviderOptionsByName = {
272 [K in VercelGatewayImageModel]: VercelGatewayImageProviderOptions
274​
275export type VercelGatewayImageModelSizeByName = {
276 [K in VercelGatewayImageModel]: VercelGatewayImageSize
278​
279export type VercelGatewayImageModelInputModalitiesByName = {
280 [K in VercelGatewayImageModel]: readonly []
282​
283export type ResolveProviderOptions<TModel extends string> =
284 TModel extends keyof VercelGatewayChatModelProviderOptionsByName
285 ? VercelGatewayChatModelProviderOptionsByName[TModel]
286 : TModel extends VercelGatewayEmbeddingModel
287 ? VercelGatewayEmbeddingProviderOptions
288 : TModel extends VercelGatewayImageModel
289 ? VercelGatewayImageProviderOptions
290 : VercelGatewayTextProviderOptions
291​
292export type ResolveInputModalities<TModel extends string> =
293 TModel extends keyof VercelGatewayModelInputModalitiesByName
294 ? VercelGatewayModelInputModalitiesByName[TModel]
295 : readonly ['text']
298​
299async function main() {
300 const file = convertModels()
301 await writeFile(OUTPUT_PATH, file, 'utf-8')
302 console.log(`Model meta file written to ${OUTPUT_PATH}`)
304​
305main().catch((error) => {
306 console.error(error)
307 process.exit(1)
308})