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

vercel.ts

508 lines15.7 KB

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