Skip to content
Dashboard

What is an AI gateway?

Content Engineer

An AI gateway is a proxy between your application and the model providers it calls. It gives your application a common endpoint and credential for model requests. Depending on the gateway and its configuration, it can choose a provider, retry failed requests elsewhere, and record token usage and cost.

Suppose a support chatbot calls one provider directly. Adding a backup means managing its credentials, rate limits, and retry logic, plus any differences in its API. With a gateway that supports model fallback, you can configure the backup model in the request and let the gateway handle those retries.

Copy link to headingHow does an AI gateway work?

The gateway authenticates incoming requests and calls providers on the application's behalf. When it manages the provider credentials, application code doesn't need those keys. Each request identifies a model, and the gateway forwards it to a provider that hosts that model.

More than one provider can host the same model, which gives a gateway two ways to recover from a failure. Provider failover retries the same model on another provider; model fallback moves to a different model listed in advance. Check which behavior your gateway enables by default before relying on either.

The gateway stays on the request path until the response finishes so it can record what each call used. Vercel AI Gateway, for example, records the status, provider, latency, token usage, cost, and routing attempts for each request.

Copy link to headingHow does an AI gateway differ from a model router and an API gateway?

Model routers, API gateways, and AI gateways handle different routing decisions, though one product can fill more than one role.

Attribute

Model router

API gateway

AI gateway

Sits in front of

Several models

Backend HTTP services

Model providers

Decides

Which model serves each request

Which backend serves each path and host

Which provider serves the requested model, and where to retry

Unit of work

One routing decision

One HTTP request

One model request, with its tokens and cost

Tailscale's Aperture model router controls model access by tailnet identity and uses Vercel AI Gateway to reach hundreds of models through one API.

Copy link to headingWhat problems does an AI gateway solve?

Calling providers directly means handling their authentication, error formats, and rate limits, even when they share a compatible API. Okara's backend used eight separate provider SDKs, and adding models required engineering work on adapters. An AI gateway gives the application a common request format, though each model still needs to support the features the application uses.

Centralizing provider credentials also reduces the keys distributed across laptops and CI pipelines. Applications authenticate to the gateway with credentials that can be scoped and revoked separately from the upstream provider keys.

Without a backup route, a provider incident or rate limit leaves the application retrying the same destination. Mercor's batch jobs took more than 12 hours as requests waited in retry queues. Mercor reports that jobs now finish in 2 to 3 hours after Vercel AI Gateway added inference capacity and provider failover.

Provider bills show aggregate spend, but connecting that spend to a user or feature requires request-level records. Gateway logs can collect the model, provider, latency, and token counts in one place to help investigate failures and attribute costs to users and features. Provider abstraction, failover, and cost attribution are three common gateway architecture patterns.

Copy link to headingDoes an AI gateway add latency?

An AI gateway adds a routing step and processing time. The effect on latency depends on where the gateway runs, its load, and the path to the selected provider. On Vercel, requests travel from a point of presence to a compute region over Vercel's managed network, where AI Gateway authenticates and routes them.

Cloudflare AI Gateway can cache supported responses for identical requests and return a cached answer without a provider call. Vercel AI Gateway doesn't retain prompts or responses, so response caching belongs in your application, including a semantic cache that matches similar prompts.

Provider prompt caching reuses eligible input prefixes. Setting caching: 'auto' adds cache markers where needed; other providers cache prefixes automatically. Cache hits depend on minimum input lengths and expiration rules, and providers can charge for cache writes.

Measure the effect with the same prompts sent directly and through the gateway at production concurrency. Compare time to first token and total duration at the median and P99, separating cache hits from requests that reach a provider.

Copy link to headingWhen do you need an AI gateway?

One direct provider integration is enough while a single model serves your traffic, an outage is tolerable, and one bill answers your cost questions. The case for a gateway grows when any of these becomes true:

  • You call a second provider or model family in production.

  • You need requests to survive a provider outage or rate limit.

  • You need to attribute spend to users, features, or teams.

  • You need routing or spending controls across an agent's model calls.

Production usage shows how model choices can change as applications grow. In the June 2026 AI Gateway production index, most apps in the lowest-volume tier run a single model, while the majority of apps at 1M+ requests route across 11 or more models. In the November 2026 edition, about half of paid teams that processed at least 10 million tokens in both September and October changed their most-used model in October. Six in ten of those changes moved to a different lab.

Agents add to the request count, because one task makes many model calls. In April 2026, 58.9% of tokens on AI Gateway were in tool-call requests, up from 31.6% six months earlier.

Outside Vercel's data, a16z's January 2026 survey of 100 executives at Global 2000 companies found that 81% use three or more model families in testing or production, up from 68% less than a year earlier. The survey's respondents weren't randomly sampled, by a16z's own account.

Once you need a gateway, the remaining decision is who operates it. Compare managed, self-hosted, and platform-built gateways by who runs the proxy and how your application uses models.

Copy link to headingWhat doesn't an AI gateway do?

An AI gateway handles the request to a model, and several things around that request stay with you.

Copy link to headingModel compatibility and recovery

Fallback models can differ in output and API behavior, so test your prompts and tool definitions against every candidate. Claude Opus 5.5, for example, rejects requests that force a tool call, which earlier models accepted.

Provider filters narrow the available fallback routes. With only, Vercel AI Gateway can fail over among listed providers but cannot use one outside the list. The request fails if no listed provider can serve the primary model or any configured fallback.

Copy link to headingProvider policies and spending limits

Provider data handling is outside the gateway's control. Vercel AI Gateway deletes prompts and responses when a request completes, but that policy doesn't constrain providers. Zero data retention (ZDR) routing narrows which providers can serve a request, but it rests on each provider's commitment and doesn't extend to tools that a provider runs, such as provider web search. Review the provider's own policy when you have strict retention requirements.

Vercel AI Gateway checks budgets at the start of each request, so the request that crosses a limit can complete. Later requests in that budget's scope receive HTTP 402, including requests using your own provider keys. With bring your own key (BYOK), inference billed by the provider doesn't count toward the budget, but fees for disabling fallback to Vercel credentials do. Set provider-side controls for the inference spend billed directly to you.

Copy link to headingAgent state and network boundaries

The gateway routes model requests, but your application or workflow engine must preserve agent progress and recover interrupted runs. Your application also decides which records a tool may read and which actions it may perform.

If policy requires the proxy to run inside your network, choose a deployment that meets that requirement. Running a self-hosted proxy still sends data outside the network when it calls external model providers.

Copy link to headingWhen should you choose Vercel AI Gateway?

Vercel AI Gateway fits when you want a hosted gateway and don't want to operate your own proxy, database, and routing control plane. It's a hosted API at https://ai-gateway.vercel.sh that you can call from any server, cloud, or local environment, and your application doesn't need to run on Vercel. AI Gateway is the same system that has powered v0, and as of November 2026 it routes more than 100 trillion tokens every month.

Copy link to headingAuthentication and provider routing

Every request authenticates with an AI Gateway API key or an OpenID Connect (OIDC) token. On a Vercel deployment, the AI SDK sends the project's OIDC token for you when AI_GATEWAY_API_KEY isn't set. Other clients, such as the OpenAI SDK, don't discover the token, so you pass it yourself.

AI Gateway selects providers using recent uptime and latency, then fails over to another provider that serves the same model if needed. Set order to prefer particular providers while retaining failover. For BYOK requests, provider timeouts limit how long the gateway waits for a response to begin. After aborting a timed-out attempt, the gateway tries the next provider, though a provider that cannot cancel the work may still charge for it.

Copy link to headingBilling and usage reporting

AI Gateway charges the provider's list price from prepaid credits without a token markup or platform fee on inference. Before purchasing credits, teams receive a monthly free credit for eligible models at lower rate limits. Purchasing credits ends that recurring allowance; enabled add-ons have separate charges.

With BYOK, the provider bills inference directly, though you still need purchased AI Gateway Credits and a positive balance. Failed requests fall back to Vercel's provider keys by default and use your credits for that inference. You can disable fallback to Vercel credentials for $0.20 per 1,000 successful requests served by your keys, in addition to the provider's inference charges.

AI Gateway logs every request with its model, token counts, and spend. On Pro and Enterprise plans, Custom Reporting returns cost and token totals grouped by day, user, model, tag, provider, credential type, ZDR status, or API key name. Each model's page shows time to first token and throughput by provider for the last hour, and uptime for the last hour, day, or week.

Copy link to headingData policies and ZDR

Vercel doesn't train on prompts, and AI Gateway retains request metadata without keeping prompt or response content. ZDR routing restricts requests to providers with a ZDR commitment for the model. Pro and Enterprise teams can enable it; Hobby teams and Pro trials need purchased credits. An active Token Pass also permits per-request ZDR, but does not by itself enable the team-wide setting.

Provider ZDR commitments are self-reported through policies or agreements with Vercel. Under the announced Audited ZDR tier, an independent security firm must test a provider's claims and publish a report before that provider receives the label.

Copy link to headingProduction examples

Zo Computer cut its retry rate from 7.5% to 0.34%, a 20x reduction, after it moved retries and fallback routing from its own code to the AI SDK and AI Gateway. In a week of A/B testing against its previous AI router, Cline measured a 10% to 14% improvement in P99 streaming latency across its most-used models and a 43.8% drop in API error rates. Searchable builds on the AI SDK and AI Gateway to test new models without rotating API keys or SDKs.

Copy link to headingBuild with Vercel AI Gateway

AI SDK 7 requires Node.js 22 or later and ECMAScript modules (ESM). In an existing server-side TypeScript project, follow the setup instructions to set AI_GATEWAY_API_KEY, then install ai and zod for the agent tool's input schema. The snippets make billable model requests.

AI Gateway supports AI SDK 6 and 7. If your project still uses version 5, upgrade before January 8, 2027, when AI Gateway stops accepting its requests.

pnpm add ai@7 zod

Copy link to headingCall any model with one string

In index.ts, pass a model ID as a plain string, and the AI SDK routes the request through AI Gateway:

index.ts
import { generateText } from 'ai';
const { text } = await generateText({
model: 'anthropic/claude-sonnet-5',
prompt: 'Explain quantum computing in one paragraph.',
});
console.log(text);

Switch models by changing the ID, for example to openai/gpt-6.2-astra or spacexai/grok-4.7. Cost-aware routing selects a model based on the task's complexity. For streamed output, use streamText and read its textStream property.

Copy link to headingFall back when a model is unavailable

List backup model IDs in providerOptions.gateway.models:

model-fallbacks.ts
import { generateText } from 'ai';
const { text } = await generateText({
model: 'anthropic/claude-fable-5',
prompt: 'Write a haiku about TypeScript.',
providerOptions: {
gateway: {
models: ['anthropic/claude-opus-5', 'google/gemini-3.1-pro-preview'],
},
},
});
console.log(text);

If every eligible provider for the primary model fails, AI Gateway tries the backup models in order and returns the first successful response. Add order to the same gateway options to set a provider preference for each model. Before listing backups, decide which models can serve your customer-facing requests, because their outputs and prices differ.

To update routing without a redeploy, save the configuration as a virtual model. Its vmc/ ID represents the model, fallbacks, provider order, ZDR setting, and tags.

Copy link to headingAttribute cost to users and features

Attach a user and tags to each request, as in custom-reporting.ts:

custom-reporting.ts
import { generateText } from 'ai';
const { text } = await generateText({
model: 'anthropic/claude-sonnet-5',
prompt: 'Tell me about San Francisco.',
providerOptions: {
gateway: {
user: 'user-123',
tags: ['feature:chat', 'env:development'],
},
},
});
console.log(text);

The fields label requests; use gateway.getSpendReport() to retrieve their spend. Supply startDate and endDate as UTC dates in YYYY-MM-DD format, plus groupBy: 'user' or 'tag'. Both dates are required, and omitting groupBy groups results by day. The same report is available through the documented REST endpoint.

The reporting endpoint is available on Pro and Enterprise, excluding Pro trials, and requests can take a few minutes to appear. Custom Reporting costs $0.075 per 1,000 tag, user ID, or quota entity ID writes and $5 per 1,000 queries.

Copy link to headingRequire zero data retention for one request

Set zeroDataRetention: true on a request that carries sensitive data, as in zdr.ts:

zdr.ts
import { generateText } from 'ai';
const { text } = await generateText({
model: 'anthropic/claude-sonnet-5',
prompt: 'Analyze this example business data: revenue grew by 5%.',
providerOptions: {
gateway: {
zeroDataRetention: true,
},
},
});
console.log(text);

AI Gateway returns no_zdr_providers_available when no provider offers ZDR for the requested model. Claude Fable models retain data on every provider and cannot serve ZDR requests. Use other provider data controls to restrict prompt training and select permitted providers and models.

Per-request ZDR has no added charge and is available on Pro and Enterprise; Hobby teams and Pro trials need purchased credits or an active Token Pass.

Copy link to headingPoint an existing OpenAI client at AI Gateway

AI Gateway exposes an OpenAI-compatible API, so code that already uses the OpenAI SDK keeps its client. For a new project, add the openai package:

pnpm add openai

Then set the client's API key and base URL, as in authentication-chat.ts:

authentication-chat.ts
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.AI_GATEWAY_API_KEY,
baseURL: 'https://ai-gateway.vercel.sh/v1',
});
const response = await client.chat.completions.create({
model: "anthropic/claude-sonnet-5",
messages: [{ "role": "user", "content": "Why is the sky blue?" }],
});
console.log(response.choices[0]?.message.content);

For Python clients, pass the same key and URL as api_key and base_url. Gateway-specific settings, such as fallback models, belong under providerOptions.gateway in the request body. The fallback reference shows how to add this extension through an object spread in TypeScript or extra_body in Python.

Chat Completions, Responses, and OpenResponses use the /v1 base URL shown in the snippet. Anthropic Messages clients use the gateway's root URL without /v1. From this shared client setup, you can build your own model router to select a model for each request.

Copy link to headingRun an agent with tools

Give a ToolLoopAgent a model string and its tools, as in agent.ts:

agent.ts
import { ToolLoopAgent, tool } from 'ai';
import { z } from 'zod';
const agent = new ToolLoopAgent({
model: 'anthropic/claude-sonnet-5',
tools: {
getWeather: tool({
description: 'Get the current weather for a location',
inputSchema: z.object({ location: z.string() }),
execute: async ({ location }) => ({
location,
temperature: 72,
condition: 'sunny',
}),
}),
},
});
const { text } = await agent.generate({
prompt: "What's the weather in Tokyo?",
});
console.log(text);

ToolLoopAgent runs the model-and-tool loop in your application's memory, and its model calls use AI Gateway because the model is a plain string. The weather tool returns fixed sample data; replace its execute function with a real weather service before using it in an application.

The loop does not persist progress across process failures. For durable execution, WorkflowAgent from @ai-sdk/workflow checkpoints a tool loop inside a Vercel Workflow. You can also add streaming, sandboxed execution, and chat platforms around an AI SDK agent.

Copy link to headingFrequently asked questions

Copy link to headingDoes an AI gateway slow down LLM calls?

An AI gateway adds routing and processing time, but total latency depends on its location, load, and provider selection. Response-cache hits can skip the provider call. Compare time to first token and total duration at production concurrency, measuring cached and uncached requests separately.

Copy link to headingDo you need an AI gateway if you call only one model provider?

Not always. One direct integration can be enough if a single model meets your needs and a provider outage is acceptable. Consider a gateway when you add providers, need failover, or want user-level cost tracking.

Copy link to headingWhat is the difference between Vercel AI Gateway and the AI SDK?

The AI SDK is a free, open-source TypeScript library for generating text, calling tools, and streaming responses. Vercel AI Gateway is a hosted API that routes model requests to providers. The AI SDK sends a request through AI Gateway when you pass the model as a plain string, but each works without the other. The AI SDK can call a provider directly through that provider's package, and AI Gateway accepts requests from OpenAI and Anthropic SDK clients.

Copy link to headingDoes Vercel AI Gateway cache model responses?

No. Vercel AI Gateway doesn't store prompts or responses, so exact-match or semantic response caching belongs in your application. Automatic prompt caching helps providers reuse eligible input prefixes instead of completed answers. The caching: 'auto' setting adds cache markers where needed; other providers cache implicitly. Minimum input lengths, expiration rules, and cache read/write prices depend on the provider.

Copy link to headingDoes Vercel store or train on prompts sent through AI Gateway?

No. Vercel doesn't train on prompts, and AI Gateway deletes prompt and response content once a request completes. AI Gateway does record request metadata, including the model, provider, token usage, and cost. Each upstream provider applies its own retention policy, and zero data retention (ZDR) routing limits requests to providers that have made a ZDR commitment.

Reference Architecture

Choose a stack and work through the decisions behind it, with curated documentation, guides, templates, and courses to help you build.

  • Agent stack: Build and operate agents with models, tools, and durable workflows.
  • Web applications: Choose rendering, data, authentication, and caching approaches.
  • Backends: Choose a runtime, connect services, and run background work.

Browse all stacks

Build with prompts

Build an app, extend an agent, or improve your project with ready-to-use prompts for your coding agent.

More AI Gateway articles

Ready to deploy?