Vercel AI Gateway
AI Gateway exposes models from multiple providers through shared authentication, model IDs, routing, billing, and observability. Model availability, SDK APIs, CLI commands, prices, and product capabilities change frequently. Verify them from current sources before changing code.
Start with current sources
Before implementing:
Inspect the project's language, package manager, installed AI SDK version, and existing provider integration.
Read the relevant Vercel page under https://vercel.com/docs/ai-gateway. Use the page's .md form when a tool needs Markdown.
Fetch the complete live model list. Do not construct model variants by analogy:
curl -fsSL https://ai-gateway.vercel.sh/v1/models
If the code uses the ai package, load the ai-sdk skill when available. Read version-matched docs under node_modules/ai/docs/ and source under node_modules/ai/src/. If the skill is not installed, use those bundled files directly.
Run vercel ai-gateway <command> --help before documenting or scripting CLI flags.
The live model endpoint and installed package take precedence over model names or SDK syntax remembered from training data.
Vercel CLI inventory
The vercel ai-gateway command manages gateway resources for the current team. Agents often discover only coding-agents setup; the rest of the CLI covers the jobs that previously required dashboard work:
| Command |
What it does |
api-keys create/list/inspect/remove |
Create and manage AI Gateway API keys, with budgets, spend alerts, expiry, and restriction exemptions |
budgets set/list/inspect/remove |
Set metered spend limits for the team, a project, a user, or an API key |
budgets defaults set/list/remove |
Set per-scope default limits covering projects, keys, or members without a custom budget |
models list / models endpoints <model> |
List the model catalog and one model's provider endpoints from the CLI |
rules add/list/edit/remove |
Manage routing rules; the CLI marks rules beta, so check --help before relying on them. REST CRUD exists under /v1/ai-gateway/rules |
coding-agents setup |
Configure supported coding agents; see references/coding-agents.md |
leaderboard |
Explore public, anonymized usage leaderboards; rarely needed for implementation work |
Use the CLI for credential and spend management when the user is working from a terminal or in CI. Check vercel ai-gateway <command> --help for current flags before scripting; do not copy a flag list from this skill into generated code.
Route the request to the right guide
| User's job |
Read |
| First request, credentials, compatible SDKs, or migration |
references/setup.md |
| Provider selection, model fallbacks, caching, BYOK, or timeouts |
references/routing.md |
| Credits, budgets, reporting, Logs, or request debugging |
references/spend-observability.md |
| Claude Code, Codex, OpenCode, Pi, or another coding agent |
references/coding-agents.md |
Read each relevant reference before editing. A task can require more than one.
Choose the integration surface
| Existing project |
Default path |
| JavaScript or TypeScript using AI SDK |
Use a plain provider/model string with generateText, streamText, ToolLoopAgent, or the relevant modality API |
| Python using AI SDK for Python |
Use ai.get_model('provider/model') and the current Python SDK docs |
| Existing OpenAI SDK |
Keep the SDK and point baseURL or base_url to https://ai-gateway.vercel.sh/v1 |
| Existing Anthropic SDK |
Keep the SDK and point baseURL or base_url to https://ai-gateway.vercel.sh |
| Provider-neutral HTTP |
Use an AI Gateway compatible endpoint, such as Chat Completions or OpenResponses |
| Existing direct-provider AI SDK integration |
Replace the provider instance with a live AI Gateway provider/model string, then remove provider credentials only after verifying the gateway path |
| Coding agent |
Use vercel ai-gateway coding-agents setup; inspect its help before claiming agent support |
AI Gateway also supports OpenAI Responses, Anthropic Messages, OpenResponses, Cohere Rerank, embeddings, image and video generation, speech, transcription, and realtime sessions. Modality pages under https://vercel.com/docs/ai-gateway/modalities cover each request shape, including background jobs for long-running video generation. Read the relevant modality or API page instead of translating one request shape from memory.
Minimal AI SDK request
The current AI SDK requires Node.js 22 or later. Confirm the installed package's engines field before enforcing a version in an existing project.
import { generateText } from 'ai';
const { text } = await generateText({
model: 'openai/gpt-5.6-sol',
prompt: 'Explain the project in one paragraph.',
});
console.log(text);
The model is a current example, not a permanent default. Fetch /v1/models and choose a model that fits the requested modality, capabilities, price, context window, data-retention policy, and team access.
Plain model strings route through AI Gateway. Add @ai-sdk/gateway only when the task needs its exported provider, types, model discovery, generation lookup, or spend-report helpers.
Authentication decision
- Use an AI Gateway API key for local scripts, CI, external servers, and non-Vercel deployments. Store it in
AI_GATEWAY_API_KEY and never print or commit it.
- Use Vercel OIDC for Vercel deployments and linked local projects. Vercel deployments receive
VERCEL_OIDC_TOKEN; local development uses vercel link and vercel env pull.
- BYOK provider credentials do not replace AI Gateway request authentication. They decide how AI Gateway authenticates to a model provider.
- A plain Node.js script does not automatically load
.env.local. Export variables in the shell or load that file explicitly. Framework behavior may differ.
Do not ask the user to paste a secret into chat, source code, a committed config file, or a command that will enter shell history unless the repository has an established secure mechanism.
Implementation workflow
- Establish the user's job, runtime, deployment target, current provider, and required capabilities.
- Select authentication from the rules above. Preserve a working existing method unless the user asked to migrate it.
- Fetch live model metadata and choose a compatible model. State why it fits.
- Read the matching SDK, API, modality, routing, or coding-agent docs.
- Make the smallest end-to-end change. Reuse the current project structure and error handling.
- Handle only errors the application can act on. Common gateway outcomes include authentication failure, insufficient credits, budget exhaustion, rate limiting, and provider capacity failure.
- Run the project's formatter, type checker, and focused tests.
- When the task authorizes a live request, run one and inspect the returned model, text or media, usage, and provider metadata.
- Verify the request in AI Gateway Logs when dashboard access is available. Logs can take about 90 seconds to ingest.
Only spend credits, create keys, change budgets, change routing rules, or write coding-agent config when the user requested or approved that outward-facing action. Prefer dry runs and interactive previews when available.
Routing invariants
- Model IDs use the exact
provider/model strings returned by /v1/models.
order controls provider preference, only restricts providers, and sort ranks providers by a supported metric.
models lists fallback models after the primary model.
caching: 'auto' manages provider prompt-cache markers. It is not an HTTP response cache.
providerTimeouts applies to BYOK provider attempts and measures time until the provider starts responding.
- A reasoning entry in
providerOptions overrides the AI SDK top-level reasoning value entirely; the two never merge.
user and tags attach reporting dimensions. They do not create per-user rate limits.
- Request-scoped provider credentials belong under
providerOptions.gateway.byok and must remain secret.
Read references/routing.md before adding any of these fields.
Verification checklist
Current documentation
1---
2name: ai-gateway
3description: Vercel AI Gateway guidance for setup, model discovery, authentication, routing, fallbacks, BYOK, budgets, spend reporting, observability, compatible APIs, and coding-agent configuration. Use when adding AI Gateway to an app, migrating provider calls, choosing models or providers, debugging gateway requests, or running `vercel ai-gateway` commands.
4summary: Set up and operate Vercel AI Gateway with current models, correct authentication, routing, spend controls, and verification.
5metadata:
6 priority: 7
7 docs:
8 - "https://vercel.com/docs/ai-gateway"
9 - "https://vercel.com/docs/ai-gateway/getting-started"
10 - "https://ai-sdk.dev/providers/ai-sdk-providers/ai-gateway"
11 sitemap: "https://vercel.com/docs/sitemap.md"
12 pathPatterns: []
13 importPatterns:
14 - 'ai'
15 - '@ai-sdk/gateway'
16 bashPatterns:
17 - '\bvercel\s+ai-gateway\b'
18 - '\bvercel\s+env\s+pull\b'
19 - '\bnpm\s+(install|i|add)\s+[^\n]*@ai-sdk/gateway\b'
20 - '\bpnpm\s+(install|i|add)\s+[^\n]*@ai-sdk/gateway\b'
21 - '\bbun\s+(install|i|add)\s+[^\n]*@ai-sdk/gateway\b'
22 - '\byarn\s+add\s+[^\n]*@ai-sdk/gateway\b'
23 promptSignals:
24 phrases:
25 - "ai gateway"
26 - "vercel ai gateway"
27 - "ai-gateway"
28 - "ai-gateway.vercel.sh"
29 allOf:
30 - [model, routing]
31 - [provider, failover]
32 - [gateway, budget]
33 - [gateway, logs]
34 - [gateway, oidc]
35 - [coding, gateway]
36 anyOf:
37 - "provider ordering"
38 - "model fallback"
39 - "byok"
40 - "spend tracking"
41 - "gateway key"
42 - "credit balance"
43 - "safety identifier"
44 - "reasoning effort"
45 - "tool calling"
46 - "structured outputs"
47 noneOf:
48 - "cloudflare ai gateway"
49 - "aws api gateway"
50 minScore: 6
51validate:
52 -
53 pattern: '\bclaude-(sonnet|opus|haiku)-\d+-\d+\b'
54 message: 'Claude model version uses a hyphen where the AI Gateway slug uses a dot. Fetch /v1/models and use the returned provider/model ID.'
55 severity: error
56 -
57 pattern: gateway\(['"][^'"/]+['"]\)
58 message: 'AI Gateway model string is missing its provider prefix. Fetch /v1/models and use a provider/model ID.'
59 severity: error
60 -
61 pattern: (OPENAI_API_KEY|ANTHROPIC_API_KEY|GOOGLE_API_KEY)
62 message: 'Provider key detected. AI Gateway request authentication uses AI_GATEWAY_API_KEY or VERCEL_OIDC_TOKEN; provider keys belong only in an intentional BYOK configuration.'
63 severity: recommended
64 skipIfFileContains: '[Bb][Yy][Oo][Kk]|providerOptions\s*:\s*\{[^}]*gateway'
65 -
66 pattern: gateway\s*:\s*\{[^}]*cacheControl
67 message: "AI Gateway does not cache whole responses through cacheControl. Use caching: 'auto' for provider prompt caching and verify the current caching docs."
68 severity: error
69 -
70 pattern: ANTHROPIC_BASE_URL\s*=\s*["']?https://ai-gateway\.vercel\.sh
71 message: 'Claude Code through AI Gateway needs ANTHROPIC_API_KEY set to an empty value and the gateway key in ANTHROPIC_AUTH_TOKEN. A non-empty ANTHROPIC_API_KEY is used instead of the gateway token.'
72 severity: recommended
73 skipIfFileContains: 'ANTHROPIC_AUTH_TOKEN'
74chainTo:
75 -
76 pattern: 'from\s+[''"]ai[''"]|require\([''"]ai[''"]\)|\b(generateText|streamText|ToolLoopAgent)\b'
77 targetSkill: ai-sdk
78 message: 'AI SDK code detected. Load the AI SDK skill and read the installed package docs before writing or changing SDK code.'
79retrieval:
80 aliases:
81 - model router
82 - ai proxy
83 - provider failover
84 - llm gateway
85 - gateway credits
86 intents:
87 - add Vercel AI Gateway to an application
88 - route AI models across providers
89 - configure provider or model fallbacks
90 - authenticate AI Gateway requests
91 - track AI model costs and set budgets
92 - debug AI Gateway requests and routing
93 - connect coding agents to AI Gateway
94 - find a model by modality, capability, price, or data retention
95 - check AI Gateway credit balance or generation cost
96 - configure reasoning or extended thinking across providers and API formats
97 - add tool calling or function calling across API formats
98 - get structured JSON output matching a schema
99 - send images or PDFs to a model
100 entities:
101 - AI Gateway
102 - AI Gateway Credits
103 - providerOptions.gateway
104 - AI_GATEWAY_API_KEY
105 - VERCEL_OIDC_TOKEN
106 - model routing
107 - provider failover
108 - BYOK
109 - spend reporting
110 - safetyIdentifier
111 - Usage & Billing API
112---
113
114# Vercel AI Gateway
115
116AI Gateway exposes models from multiple providers through shared authentication, model IDs, routing, billing, and observability. Model availability, SDK APIs, CLI commands, prices, and product capabilities change frequently. Verify them from current sources before changing code.
117
118## Start with current sources
119
120Before implementing:
121
1221. Inspect the project's language, package manager, installed AI SDK version, and existing provider integration.
1232. Read the relevant Vercel page under <https://vercel.com/docs/ai-gateway>. Use the page's `.md` form when a tool needs Markdown.
1243. Fetch the complete live model list. Do not construct model variants by analogy:
125
126 ```bash
127 curl -fsSL https://ai-gateway.vercel.sh/v1/models
128 ```
129
1304. If the code uses the `ai` package, load the `ai-sdk` skill when available. Read version-matched docs under `node_modules/ai/docs/` and source under `node_modules/ai/src/`. If the skill is not installed, use those bundled files directly.
1315. Run `vercel ai-gateway <command> --help` before documenting or scripting CLI flags.
132
133The live model endpoint and installed package take precedence over model names or SDK syntax remembered from training data.
134
135## Vercel CLI inventory
136
137The `vercel ai-gateway` command manages gateway resources for the current team. Agents often discover only `coding-agents setup`; the rest of the CLI covers the jobs that previously required dashboard work:
138
139| Command | What it does |
140| --- | --- |
141| `api-keys create/list/inspect/remove` | Create and manage AI Gateway API keys, with budgets, spend alerts, expiry, and restriction exemptions |
142| `budgets set/list/inspect/remove` | Set metered spend limits for the team, a project, a user, or an API key |
143| `budgets defaults set/list/remove` | Set per-scope default limits covering projects, keys, or members without a custom budget |
144| `models list` / `models endpoints <model>` | List the model catalog and one model's provider endpoints from the CLI |
145| `rules add/list/edit/remove` | Manage routing rules; the CLI marks rules beta, so check `--help` before relying on them. REST CRUD exists under `/v1/ai-gateway/rules` |
146| `coding-agents setup` | Configure supported coding agents; see [references/coding-agents.md](references/coding-agents.md) |
147| `leaderboard` | Explore public, anonymized usage leaderboards; rarely needed for implementation work |
148
149Use the CLI for credential and spend management when the user is working from a terminal or in CI. Check `vercel ai-gateway <command> --help` for current flags before scripting; do not copy a flag list from this skill into generated code.
150
151## Route the request to the right guide
152
153| User's job | Read |
154| --- | --- |
155| First request, credentials, compatible SDKs, or migration | [references/setup.md](references/setup.md) |
156| Provider selection, model fallbacks, caching, BYOK, or timeouts | [references/routing.md](references/routing.md) |
157| Credits, budgets, reporting, Logs, or request debugging | [references/spend-observability.md](references/spend-observability.md) |
158| Claude Code, Codex, OpenCode, Pi, or another coding agent | [references/coding-agents.md](references/coding-agents.md) |
159
160Read each relevant reference before editing. A task can require more than one.
161
162## Choose the integration surface
163
164| Existing project | Default path |
165| --- | --- |
166| JavaScript or TypeScript using AI SDK | Use a plain `provider/model` string with `generateText`, `streamText`, `ToolLoopAgent`, or the relevant modality API |
167| Python using AI SDK for Python | Use `ai.get_model('provider/model')` and the current Python SDK docs |
168| Existing OpenAI SDK | Keep the SDK and point `baseURL` or `base_url` to `https://ai-gateway.vercel.sh/v1` |
169| Existing Anthropic SDK | Keep the SDK and point `baseURL` or `base_url` to `https://ai-gateway.vercel.sh` |
170| Provider-neutral HTTP | Use an AI Gateway compatible endpoint, such as Chat Completions or OpenResponses |
171| Existing direct-provider AI SDK integration | Replace the provider instance with a live AI Gateway `provider/model` string, then remove provider credentials only after verifying the gateway path |
172| Coding agent | Use `vercel ai-gateway coding-agents setup`; inspect its help before claiming agent support |
173
174AI Gateway also supports OpenAI Responses, Anthropic Messages, OpenResponses, Cohere Rerank, embeddings, image and video generation, speech, transcription, and realtime sessions. Modality pages under <https://vercel.com/docs/ai-gateway/modalities> cover each request shape, including background jobs for long-running video generation. Read the relevant modality or API page instead of translating one request shape from memory.
175
176## Minimal AI SDK request
177
178The current AI SDK requires Node.js 22 or later. Confirm the installed package's `engines` field before enforcing a version in an existing project.
179
180```ts
181import { generateText } from 'ai';
182
183const { text } = await generateText({
184 model: 'openai/gpt-5.6-sol',
185 prompt: 'Explain the project in one paragraph.',
186});
187
188console.log(text);
189```
190
191The model is a current example, not a permanent default. Fetch `/v1/models` and choose a model that fits the requested modality, capabilities, price, context window, data-retention policy, and team access.
192
193Plain model strings route through AI Gateway. Add `@ai-sdk/gateway` only when the task needs its exported provider, types, model discovery, generation lookup, or spend-report helpers.
194
195## Authentication decision
196
197- Use an **AI Gateway API key** for local scripts, CI, external servers, and non-Vercel deployments. Store it in `AI_GATEWAY_API_KEY` and never print or commit it.
198- Use **Vercel OIDC** for Vercel deployments and linked local projects. Vercel deployments receive `VERCEL_OIDC_TOKEN`; local development uses `vercel link` and `vercel env pull`.
199- **BYOK provider credentials do not replace AI Gateway request authentication.** They decide how AI Gateway authenticates to a model provider.
200- A plain Node.js script does not automatically load `.env.local`. Export variables in the shell or load that file explicitly. Framework behavior may differ.
201
202Do not ask the user to paste a secret into chat, source code, a committed config file, or a command that will enter shell history unless the repository has an established secure mechanism.
203
204## Implementation workflow
205
2061. Establish the user's job, runtime, deployment target, current provider, and required capabilities.
2072. Select authentication from the rules above. Preserve a working existing method unless the user asked to migrate it.
2083. Fetch live model metadata and choose a compatible model. State why it fits.
2094. Read the matching SDK, API, modality, routing, or coding-agent docs.
2105. Make the smallest end-to-end change. Reuse the current project structure and error handling.
2116. Handle only errors the application can act on. Common gateway outcomes include authentication failure, insufficient credits, budget exhaustion, rate limiting, and provider capacity failure.
2127. Run the project's formatter, type checker, and focused tests.
2138. When the task authorizes a live request, run one and inspect the returned model, text or media, usage, and provider metadata.
2149. Verify the request in AI Gateway Logs when dashboard access is available. Logs can take about 90 seconds to ingest.
215
216Only spend credits, create keys, change budgets, change routing rules, or write coding-agent config when the user requested or approved that outward-facing action. Prefer dry runs and interactive previews when available.
217
218## Routing invariants
219
220- Model IDs use the exact `provider/model` strings returned by `/v1/models`.
221- `order` controls provider preference, `only` restricts providers, and `sort` ranks providers by a supported metric.
222- `models` lists fallback models after the primary model.
223- `caching: 'auto'` manages provider prompt-cache markers. It is not an HTTP response cache.
224- `providerTimeouts` applies to BYOK provider attempts and measures time until the provider starts responding.
225- A reasoning entry in `providerOptions` overrides the AI SDK top-level `reasoning` value entirely; the two never merge.
226- `user` and `tags` attach reporting dimensions. They do not create per-user rate limits.
227- Request-scoped provider credentials belong under `providerOptions.gateway.byok` and must remain secret.
228
229Read [references/routing.md](references/routing.md) before adding any of these fields.
230
231## Verification checklist
232
233- [ ] The model ID exists in the full live model response.
234- [ ] The selected API or SDK supports the requested modality and feature.
235- [ ] Authentication works in the actual runtime, including `.env.local` loading where relevant.
236- [ ] The example prints or returns a result instead of discarding the response.
237- [ ] The project type checker and focused tests pass.
238- [ ] A live request was made only when authorized, and its cost was understood.
239- [ ] Provider routing or fallback behavior is visible in response metadata or Logs.
240- [ ] No secret appears in source, logs, diffs, or the final response.
241- [ ] The final report distinguishes code verification from live and dashboard verification.
242
243## Current documentation
244
245- Getting started: <https://vercel.com/docs/ai-gateway/getting-started>
246- Models and providers: <https://vercel.com/docs/ai-gateway/models-and-providers>
247- SDKs and APIs: <https://vercel.com/docs/ai-gateway/sdks-and-apis>
248- Authentication and BYOK: <https://vercel.com/docs/ai-gateway/authentication-and-byok>
249- Observability and spend: <https://vercel.com/docs/ai-gateway/observability-and-spend>
250- Modalities: <https://vercel.com/docs/ai-gateway/modalities>
251- REST API reference: <https://vercel.com/docs/ai-gateway/sdks-and-apis/rest-api>
252- FAQ: <https://vercel.com/docs/ai-gateway/faq>
253- Coding agents: <https://vercel.com/docs/ai-gateway/coding-agents>
254- AI SDK provider: <https://ai-sdk.dev/providers/ai-sdk-providers/ai-gateway>