Open History to see the last commit
1/**
2 * Vercel AI Gateway — public model list at ai-gateway.vercel.sh.
3 * Token prices there are USD per token. A zero price is free, not a card.
4 * Context-length tiers are the standard schedule. fast, flex, priority,
5 * regional, and peak are not. Effort values are stored when the row
6 * publishes them. A missing price stays null.
7 */
8import { compileTokenCard } from '@modelschemas/rate-card'
9import type { RateCard } from '@modelschemas/rate-card'
10
11import type { Activity } from '#/db/schema.ts'
12
13import { SHARED_EFFORT_LEVELS } from '../request-map.ts'
14import type {
15 ChatRequestMap,
16 EffortLevelMap,
17 ThinkingRequest,
18} from '../request-map.ts'
19import { fetchJson, sha256Text } from '../types.ts'
20import { namespacedUpstreamIdentity } from '../upstream-model.ts'
21import type {
22 FactSource,
23 ListModelsResult,
24 ModelInfo,
25 ModelReasoning,
26 ProviderConfig,
27 ProviderSecrets,
28 SpecFetchResult,
29} from '../types.ts'
30
31export const VERCEL_MODELS_URL = 'https://ai-gateway.vercel.sh/v1/models'
32
33const SPEC_SKIP = 'vercel: no first-party OpenAPI document — skipped'
34
35const TYPE_ACTIVITY: Record<string, Activity> = {
36 language: 'chat',
37 embedding: 'embeddings',
38 image: 'image',
39 video: 'video',
40 speech: 'audio',
41 transcription: 'audio',
42}
43
44/** Listing `supported_parameters` names that are catalog flags. */
45const PARAMETER_FLAGS: Record<string, string> = {
46 tools: 'tools',
47 tool_choice: 'tool_choice',
48 max_tokens: 'max_tokens',
49 max_completion_tokens: 'max_tokens',
50 temperature: 'temperature',
51 top_p: 'top_p',
52 top_k: 'top_k',
53 stop: 'stop',
54 seed: 'seed',
55 frequency_penalty: 'frequency_penalty',
56 presence_penalty: 'presence_penalty',
57 response_format: 'response_format',
58 reasoning: 'reasoning',
59 include_reasoning: 'include_reasoning',
60 reasoning_effort: 'reasoning_effort',
61 structured_outputs: 'structured_outputs',
62}
63
64const TOKEN_LEVERS = [
65 ['input', 'input_tokens'],
66 ['output', 'output_tokens'],
67 ['input_cache_read', 'cache_read_tokens'],
68 ['input_cache_write', 'cache_write_tokens'],
69] as const
70
71function isRecord(value: unknown): value is Record<string, unknown> {
72 return typeof value === 'object' && value !== null && !Array.isArray(value)
73}
74
75function positive(value: unknown): number | null {
76 return typeof value === 'number' && Number.isFinite(value) && value > 0
77 ? value
78 : null
79}
80
81function stringList(value: unknown): Array<string> | null {
82 if (!Array.isArray(value) || value.length === 0) return null
83 const out: Array<string> = []
84 for (const item of value) {
85 if (typeof item !== 'string') return null
86 out.push(item)
87 }
88 return out
89}
90
91/** USD per token. Zero is free, not a billed rate. */
92function perToken(value: unknown): number | null {
93 if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
94 return value
95 }
96 if (typeof value !== 'string' || value.length === 0) return null
97 const parsed = Number(value)
98 return Number.isFinite(parsed) && parsed > 0 ? parsed : null
99}
100
101function modalities(value: unknown): ModelInfo['modalities'] {
102 if (!isRecord(value)) return null
103 const input = stringList(value.input)
104 const output = stringList(value.output)
105 if (!input || !output) return null
106 return { input, output }
107}
108
109/**
110 * The Chat Completions field behind a toggle or budget row
111 * (vercel.com/docs/ai-gateway/models-and-providers/reasoning, "How
112 * reasoning is mapped"). Effort rows carry no source of their own.
113 */
114function controlField(reasoning: ModelReasoning | null): string | null {
115 if (reasoning?.mode === 'toggle') return 'reasoning.enabled'
116 return reasoning?.mode === 'budget' ? 'reasoning.max_tokens' : null
117}
118
119/**
120 * The controls the gateway row lists in `reasoning_options`. An `effort`
121 * entry is an effort row. Without one: `toggle` "identifies an on/off
122 * control", so a row that lists it can turn reasoning off; a
123 * `budget_tokens` entry alone leaves that unstated. A row with a control
124 * type this does not know stores nothing.
125 */
126export function vercelReasoning(
127 row: Record<string, unknown>,
128): ModelReasoning | null {
129 const options = Array.isArray(row.reasoning_options)
130 ? row.reasoning_options.filter(isRecord)
131 : []
132 const toggle = options.some((option) => option.type === 'toggle')
133 const effort = options.find((option) => option.type === 'effort')
134 const efforts = effort ? stringList(effort.values) : null
135 if (efforts) {
136 return {
137 mode: 'effort',
138 mandatory:
139 !toggle && !efforts.includes('none') && !efforts.includes('off'),
140 efforts,
141 }
142 }
143 const types = options.map((option) => option.type)
144 if (types.some((type) => type !== 'toggle' && type !== 'budget_tokens')) {
145 return null
146 }
147 if (types.includes('budget_tokens')) {
148 return { mode: 'budget', mandatory: toggle ? false : null }
149 }
150 return toggle ? { mode: 'toggle', mandatory: false } : null
151}
152
153interface PriceTier {
154 min: number
155 max: number | null
156 cost: number
157}
158
159function readTiers(
160 rawId: string,
161 key: string,
162 value: unknown,
163): Array<PriceTier> | null {
164 if (value == null) return null
165 if (!Array.isArray(value)) {
166 throw new Error(`vercel: ${rawId} pricing.${key}_tiers is not an array`)
167 }
168 const tiers: Array<PriceTier> = []
169 for (const entry of value) {
170 if (!isRecord(entry)) {
171 throw new Error(
172 `vercel: ${rawId} pricing.${key}_tiers entry is not an object`,
173 )
174 }
175 const cost = perToken(entry.cost)
176 const min = entry.min === undefined ? 0 : entry.min
177 const max = entry.max === undefined ? null : entry.max
178 if (
179 cost === null ||
180 typeof min !== 'number' ||
181 !Number.isFinite(min) ||
182 min < 0 ||
183 (max !== null &&
184 (typeof max !== 'number' || !Number.isFinite(max) || max <= min))
185 ) {
186 throw new Error(
187 `vercel: ${rawId} pricing.${key}_tiers entry is unreadable`,
188 )
189 }
190 tiers.push({ min, max, cost })
191 }
192 tiers.sort((a, b) => a.min - b.min)
193 for (let i = 0; i < tiers.length; i++) {
194 const tier = tiers[i]
195 const next = tiers[i + 1]
196 if (!tier) continue
197 if (i > 0 && tier.min === tiers[i - 1]?.min) {
198 throw new Error(`vercel: ${rawId} pricing.${key}_tiers repeats a min`)
199 }
200 if (next) {
201 if (tier.max === null || tier.max !== next.min) {
202 throw new Error(
203 `vercel: ${rawId} pricing.${key}_tiers ranges do not meet`,
204 )
205 }
206 } else if (tier.max !== null) {
207 throw new Error(
208 `vercel: ${rawId} pricing.${key}_tiers does not cover every longer prompt`,
209 )
210 }
211 }
212 return tiers
213}
214
215/** Cost of the tier that contains `tokens`, or null when none does. */
216function rateAt(tiers: Array<PriceTier>, tokens: number): number | null {
217 let found: PriceTier | null = null
218 for (const tier of tiers) {
219 if (tier.min <= tokens && (tier.max === null || tokens < tier.max)) {
220 if (!found || tier.min >= found.min) found = tier
221 }
222 }
223 return found?.cost ?? null
224}
225
226/**
227 * Standard token card. `input_tiers` and the cache tier arrays re-quote
228 * that schedule above a prompt size. Vercel's `min` is inclusive;
229 * `compileTokenCard` applies a tier only when the prompt is strictly above
230 * `minPromptTokens`, so the stored threshold is `min - 1`.
231 */
232function tokenCard(
233 rawId: string,
234 pricing: Record<string, unknown>,
235 source: RateCard['source'],
236): RateCard | null {
237 const base: Record<string, number> = {}
238 const tiersByLever = new Map<string, Array<PriceTier>>()
239 for (const [key, lever] of TOKEN_LEVERS) {
240 const rate = perToken(pricing[key])
241 if (rate !== null) base[lever] = rate
242 const tiers = readTiers(rawId, key, pricing[`${key}_tiers`])
243 if (!tiers || tiers.length === 0) continue
244 const floor = tiers.find((tier) => tier.min === 0)
245 if (floor && rate !== null && floor.cost !== rate) {
246 throw new Error(
247 `vercel: ${rawId} pricing.${key} disagrees with its first tier`,
248 )
249 }
250 if (rate === null) {
251 throw new Error(
252 `vercel: ${rawId} pricing.${key}_tiers has no base ${key}`,
253 )
254 }
255 tiersByLever.set(lever, tiers)
256 }
257 if (base.input_tokens === undefined || base.output_tokens === undefined) {
258 return null
259 }
260 const thresholds = new Set<number>()
261 for (const tiers of tiersByLever.values()) {
262 for (const tier of tiers) {
263 if (tier.min > 0) thresholds.add(tier.min)
264 }
265 }
266 const tokenTiers = [...thresholds]
267 .sort((a, b) => a - b)
268 .map((min) => {
269 const rates: Record<string, number> = {}
270 for (const [lever, tiers] of tiersByLever) {
271 const at = rateAt(tiers, min)
272 if (at === null) {
273 throw new Error(
274 `vercel: ${rawId} pricing tier at ${min} does not cover ${lever}`,
275 )
276 }
277 rates[lever] = at
278 }
279 return { minPromptTokens: min - 1, rates }
280 })
281 return compileTokenCard(base, tokenTiers, source)
282}
283
284function parameterNames(rawId: string, value: unknown): Array<string> | null {
285 if (value == null) return null
286 if (!Array.isArray(value)) {
287 throw new Error(
288 `vercel: ${rawId} supported_parameters is not a string array`,
289 )
290 }
291 const names: Array<string> = []
292 for (const item of value) {
293 if (typeof item !== 'string') {
294 throw new Error(
295 `vercel: ${rawId} supported_parameters is not a string array`,
296 )
297 }
298 names.push(item)
299 }
300 return names
301}
302
303function capabilityFlags(names: Array<string>): Array<string> {
304 const flags: Array<string> = []
305 const seen = new Set<string>()
306 for (const name of names) {
307 const flag = PARAMETER_FLAGS[name]
308 if (!flag || seen.has(flag)) continue
309 seen.add(flag)
310 flags.push(flag)
311 }
312 return flags
313}
314
315/**
316 * Chat Completions body for the controls this row lists
317 * (vercel.com/docs/ai-gateway/models-and-providers/reasoning, "How
318 * reasoning is mapped"). `on` is effort high, and only when the row lists
319 * `high`. A toggle is `reasoning.enabled`. A budget names no high token
320 * count, so it adds no thinking body.
321 */
322function thinkingFor(
323 options: Array<Record<string, unknown>>,
324): ThinkingRequest | null {
325 const effort = options.find((option) => option.type === 'effort')
326 const values = effort ? stringList(effort.values) : null
327 const toggle = options.some((option) => option.type === 'toggle')
328 if (values?.includes('high')) {
329 const off = values.includes('none')
330 ? 'none'
331 : values.includes('off')
332 ? 'off'
333 : null
334 const levels = Object.fromEntries(
335 SHARED_EFFORT_LEVELS.map((level) => [
336 level,
337 level === 'off' ? off : values.includes(level) ? level : null,
338 ]),
339 ) as EffortLevelMap
340 return {
341 on: { reasoning: { effort: 'high' } },
342 off: off
343 ? { reasoning: { effort: off } }
344 : toggle
345 ? { reasoning: { enabled: false } }
346 : null,
347 levels,
348 }
349 }
350 // Effort values with no `high` have no "on at high" body. The toggle,
351 // when the row also lists one, is the on/off control.
352 if (toggle) {
353 return {
354 on: { reasoning: { enabled: true } },
355 off: { reasoning: { enabled: false } },
356 levels: null,
357 }
358 }
359 return null
360}
361
362function chatRequest(
363 activity: Activity | null,
364 names: Array<string> | null,
365 options: Array<Record<string, unknown>>,
366): ChatRequestMap | null {
367 if (activity !== 'chat') return null
368 const params = names ?? []
369 const maxTokensField = params.includes('max_completion_tokens')
370 ? 'max_completion_tokens'
371 : params.includes('max_tokens')
372 ? 'max_tokens'
373 : null
374 const thinking = thinkingFor(options)
375 if (maxTokensField === null && thinking === null) return null
376 return {
377 thinking,
378 maxTokensField,
379 developerRole: null,
380 replayReasoningContent: null,
381 store: null,
382 strictTools: null,
383 sessionAffinity: null,
384 cacheControl: null,
385 toolStream: null,
386 reasoningEffort: null,
387 }
388}
389
390function listed(source: RateCard['source'], path: string): FactSource {
391 return {
392 derivation: 'listing',
393 sourceUrl: source.url,
394 sourceHash: source.hash,
395 path,
396 }
397}
398
399export function parseVercelModels(
400 payload: unknown,
401 source: RateCard['source'],
402): Array<ModelInfo> {
403 if (!isRecord(payload) || !Array.isArray(payload.data)) {
404 throw new Error('vercel: models payload has no data array')
405 }
406 const models: Array<ModelInfo> = []
407 for (const row of payload.data) {
408 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
409 continue
410 }
411 const pricing = isRecord(row.pricing) ? row.pricing : null
412 const card = pricing ? tokenCard(row.id, pricing, source) : null
413 const activity =
414 typeof row.type === 'string' ? (TYPE_ACTIVITY[row.type] ?? null) : null
415 const reasoning = vercelReasoning(row)
416 const field = controlField(reasoning)
417 const names = parameterNames(row.id, row.supported_parameters)
418 const flags = names ? capabilityFlags(names) : null
419 const options = Array.isArray(row.reasoning_options)
420 ? row.reasoning_options.filter(isRecord)
421 : []
422 const requestMap = chatRequest(activity, names, options)
423 const factSources: NonNullable<ModelInfo['factSources']> = {}
424 if (card) factSources.pricing = listed(source, 'pricing')
425 if (flags && flags.length > 0 && names) {
426 const seen = new Set<string>()
427 factSources.capabilities = {}
428 for (const name of names) {
429 const flag = PARAMETER_FLAGS[name]
430 if (!flag || seen.has(flag)) continue
431 seen.add(flag)
432 factSources.capabilities[flag] = listed(
433 source,
434 `supported_parameters.${name}`,
435 )
436 }
437 }
438 if (field) factSources.reasoning = listed(source, field)
439 models.push({
440 rawId: row.id,
441 displayName: typeof row.name === 'string' ? row.name : null,
442 activity,
443 contextWindow: positive(row.context_window),
444 maxOutput: positive(row.max_tokens),
445 modalities: modalities(row.modalities),
446 pricing: card,
447 ...(flags ? { capabilities: flags, exactCapabilities: true } : {}),
448 reasoning,
449 ...(requestMap ? { requestMap } : {}),
450 releasedAt: positive(row.released),
451 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
452 })
453 }
454 if (models.length === 0) {
455 throw new Error('vercel: models payload listed no ids')
456 }
457 return models
458}
459
460async function listModels(_env: ProviderSecrets): Promise<ListModelsResult> {
461 const payload = await fetchJson(VERCEL_MODELS_URL)
462 const text = JSON.stringify(payload)
463 return {
464 models: parseVercelModels(payload, {
465 url: VERCEL_MODELS_URL,
466 hash: await sha256Text(text),
467 extractedAt: new Date().toISOString(),
468 }),
469 }
470}
471
472function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
473 return Promise.resolve({
474 specs: [],
475 sources: [],
476 outputStrategy: 'post-200',
477 skipped: SPEC_SKIP,
478 })
479}
480
481export const provider: ProviderConfig = {
482 id: 'vercel',
483 upstreamModelIdentity: (rawId) =>
484 namespacedUpstreamIdentity(rawId, {
485 derivation: 'listing',
486 sourceUrl: VERCEL_MODELS_URL,
487 path: 'data[].id',
488 }),
489 displayName: 'Vercel AI Gateway',
490 specSourceUrl: 'https://vercel.com/docs/ai-gateway',
491 modelsEndpoint: VERCEL_MODELS_URL,
492 defaultDerivation: 'docs-derived',
493 fetchSpec,
494 listModels,
495 classify: () => null,
496}