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