---
title: Migrate from Neon AI Gateway to Vercel AI Gateway
description: Swap Neon's per-branch base URL and credential for Vercel's, map each short model ID to a creator/model slug, and replace the Gemini endpoint, rate limits, and daily spend cap.
keywords: ["Neon","AI Gateway","AI SDK"]
url: "https://vercel.com/kb/guide/neon-aig-to-vercel-aig"
published: 2026-11-30
last_updated: 2026-11-30
authors: Ben Sabic
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect neon-aig-to-vercel-aig"
---

Move supported model calls from Neon AI Gateway to [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) by updating the endpoint, gateway credential, and model ID. You can keep a supported OpenAI or Anthropic client, but check the request options and response fields your application uses against the [API reference](https://vercel.com/docs/ai-gateway/sdks-and-apis).

Neon-specific behavior, including the native Gemini endpoint, branch-scoped credentials, and the default rate limits and daily spend cap, needs separate replacements before those calls move. Your application can stay on its current host, and your Neon database stays as it is.

## Prerequisites

Before you begin, make sure you have:

- Access to a [Vercel account](https://vercel.com/signup) for API keys and billing. OIDC authentication also needs a Vercel project.
  
- AI Gateway Credits for your selected models. The free tier supports a [subset of models](https://vercel.com/ai-gateway/models?freeTier=true) with lower per-model rate limits. Other models and all requests using your own provider keys require [purchased credits](https://vercel.com/docs/ai-gateway/pricing).
  
- AI SDK 6 or 7 if your app uses the AI SDK, preferably version 7.
  
- Access to your Neon Console or the Neon CLI to review the branches, credentials, and prepaid credits your AI Gateway calls use.
  

For local development, use Node.js 24+ with the latest [Vercel CLI](https://vercel.com/docs/cli).

## Migrate with your agent

Use this prompt in your application's repository to migrate Neon AI Gateway calls. It asks your agent to preserve existing behavior, identify missing replacements, and verify each change before cutover.

### Agent prompt

```txt
Migrate this repository from Neon AI Gateway to Vercel AI Gateway. Read and follow the migration guide using the Vercel CLI: `npx vercel@latest kb inspect neon-aig-to-vercel-aig`.

Inspect code and configuration first. Inventory clients that read NEON_AI_GATEWAY_BASE_URL and NEON_AI_GATEWAY_TOKEN, calls to the /v1, /openai/v1, /anthropic, /gemini, and /ai-gateway paths, @neon/ai-sdk-provider models, and model IDs. Identify the Neon branch credential each environment uses and any code that depends on Neon's rate limits or daily spend cap. Ask for missing settings and use credential placeholders.

Make scoped changes to supported calls. Resolve each model against the Vercel catalog and preserve prompts, tools, output handling, and fallback behavior. Keep unsupported calls on Neon and explain what blocks them. For AI SDK calls, use explicit gateway() models during migration so calls that still use neon() keep their current path. Keep embedding-model changes separate from the gateway migration.

Account for native Gemini API calls, rate limits, spend limits, retention, retries, and timeout behavior before a call moves. Adapt request bodies and conversation history where the APIs differ. Use the chosen API key or OIDC authentication path and identify environment or dashboard setup I must complete. Keep secrets out of code and output.

Run the available local checks and test the application's relevant request paths, including streaming, tool calls, fallbacks, and rejected requests. Ask before running billable model calls or changing production traffic. Preserve Neon credentials and configuration for rollback.

Finish with a summary of changed files, model and policy mappings, checks run, unresolved differences, and the remaining steps for a staged cutover.

To find other KB guides, such as ones on related topics or next steps, search the Vercel Knowledge Base with the Vercel CLI:
`npx vercel@latest kb search "<topic>"`
```

## How Neon AI Gateway features map to Vercel AI Gateway

Before changing endpoints, record the gateway policies each call relies on. Use this table to identify settings you can map directly and features that need [an application replacement](#what-doesn%27t-map-from-neon-ai-gateway). Complete those replacements before sending production traffic through the new path.

| Neon AI Gateway                                                                   | Vercel AI Gateway                                                                                                                                                                                                           | What you change                                                                  |
| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| Per-branch gateway host                                                           | One gateway host for all environments                                                                                                                                                                                       | Replace the base URL in each client                                              |
| Branch-scoped bearer credential                                                   | An AI Gateway [API key](https://vercel.com/docs/ai-gateway/authentication-and-byok/api-keys) or Vercel [OIDC token](https://vercel.com/docs/ai-gateway/authentication-and-byok/oidc)                                        | Create a credential for each environment                                         |
| Environment variables supplied by Neon                                            | OIDC on Vercel deployments, and `vercel env pull` for local development                                                                                                                                                     | Set `AI_GATEWAY_API_KEY` on every other host                                     |
| Short model IDs, such as `gpt-5-mini`                                             | `creator/model` slugs                                                                                                                                                                                                       | Look up each ID in the catalog                                                   |
| Client-specific API paths                                                         | Base URLs selected by client format                                                                                                                                                                                         | Change the path with the host                                                    |
| Native Gemini endpoint at `/gemini`                                               | AI SDK or OpenAI-compatible API                                                                                                                                                                                             | Adapt request and response handling                                              |
| Decisions at `/typesafe/v1/systemone`                                             | [TypeSafe-compatible API](https://vercel.com/docs/ai-gateway/sdks-and-apis/typesafe) at the same path                                                                                                                       | Change the host and credential                                                   |
| `@neon/ai-sdk-provider`                                                           | `gateway()` from `@ai-sdk/gateway`                                                                                                                                                                                          | Replace the provider and each model ID                                           |
| Default limits of 200,000 input and 200,000 output tokens per minute              | No equivalent. Vercel sets [rate limits](https://vercel.com/docs/ai-gateway/rate-limits) per tier, and [budgets](https://vercel.com/docs/ai-gateway/observability-and-spend/budgets) limit spend                            | Limit request rate in your application                                           |
| Account-level daily spend cap that Neon sets                                      | Budgets you set for a team, project, API key, or team member                                                                                                                                                                | Set a budget, and handle `402` as well as `429`                                  |
| One host for each model, Databricks for most                                      | [Model fallbacks](https://vercel.com/docs/ai-gateway/models-and-providers/model-fallbacks) and [provider routing](https://vercel.com/docs/ai-gateway/models-and-providers/provider-filtering-and-ordering)                  | Optional. Restrict or order providers, and send one request with a fallback list |
| Anthropic `cache_control` forwarded on the Messages endpoint                      | [Prompt caching](https://vercel.com/docs/ai-gateway/models-and-providers/automatic-caching) with `caching: 'auto'`                                                                                                          | Set `caching: 'auto'`, or keep your own cache markers                            |
| Retention under Databricks' policy for most models                                | [Per-request ZDR](https://vercel.com/docs/ai-gateway/security-and-compliance/zdr#per-request-zero-data-retention)                                                                                                           | Preserve retention requirements and check provider eligibility                   |
| Token usage by project or branch in the consumption history API on eligible plans | [Logs](https://vercel.com/docs/ai-gateway/observability-and-spend/logs) for each request, and the [Custom Reporting API](https://vercel.com/docs/ai-gateway/observability-and-spend/custom-reporting) on Pro and Enterprise | Review usage for each request, and add `user` and `tags` to group it             |
| Prepaid credits, with no provider keys                                            | AI Gateway Credits with Vercel's provider keys, and optional [BYOK](https://vercel.com/docs/ai-gateway/authentication-and-byok/byok), per team                                                                              | Purchase credits                                                                 |

## Steps

### 1\. Find how your app calls Neon AI Gateway

Neon provides [two environment variables](https://neon.com/docs/ai-gateway/authentication): `NEON_AI_GATEWAY_BASE_URL` contains the branch host without a path, and `NEON_AI_GATEWAY_TOKEN` contains its bearer credential. Clients append the path for their API format. Your application may use several of these integrations.

| Integration                     | Recognize it by                                                                                                                       | Migration step           |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
| Chat completions and embeddings | Base URL ending in `/v1`, usually with the OpenAI SDK                                                                                 | 4                        |
| OpenAI Responses                | Base URL ending in `/openai/v1`                                                                                                       | 4                        |
| Anthropic Messages              | Base URL ending in `/anthropic`, and the credential passed as `authToken`                                                             | 4                        |
| Gemini API                      | Base URL ending in `/gemini`, using the Google Gen AI SDK. JavaScript and TypeScript use `@google/genai`; Python uses `google-genai`. | 4, in another API format |
| Decisions                       | Requests to `/typesafe/v1/systemone`                                                                                                  | 4                        |
| REST call                       | `fetch` or curl to a URL built from `NEON_AI_GATEWAY_BASE_URL`                                                                        | 4                        |
| AI SDK provider                 | `neon()` from `@neon/ai-sdk-provider`                                                                                                 | 5                        |

Most formats also have a longer `/ai-gateway/` path, such as `/ai-gateway/mlflow/v1` for Chat Completions and `/ai-gateway/openai/v1` for Responses. Migrate those aliases the same way as their shorter forms. Decisions uses only `/typesafe/v1/systemone` and has no longer alias.

From the root of your repository, find tracked files that reference Neon AI Gateway:

```bash
git grep -l -i -F \
  -e 'NEON_AI_GATEWAY_' \
  -e '@neon/ai-sdk-provider' \
  -e '-api.ai.' \
  -e '/ai-gateway/' \
  -e 'aiGateway' \
  -e 'nt_live_' \
  -e 'databricks-' \
  -e 'REQUEST_LIMIT_EXCEEDED' \
  -e 'X-Should-Retry'
```

Search results cover tracked files and may include unrelated code or historical examples. Follow each client to its call sites, check `neon.ts` for an `aiGateway` setting, and inspect untracked source separately.

The `-api.ai.` pattern matches a hardcoded branch host, and `nt_live_` matches a credential committed to the repository. Neon also accepts model IDs with a `databricks-` prefix, so the search includes that form. Neon injects both variables into Neon Functions, and `neon env pull` writes them to a local `.env` file, so code can read them with no credential setup in your repository.

For each Neon AI Gateway call site, record the model, the path it appends, and the branch its credential belongs to.

### 2\. Create a Vercel AI Gateway credential

Every Vercel AI Gateway request needs an [AI Gateway API key](https://vercel.com/docs/ai-gateway/authentication-and-byok/api-keys) or Vercel OIDC token. Your Neon credential cannot authenticate to the gateway.

#### Create an API key

API keys work from any environment. On the [AI Gateway API Keys page](https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai-gateway%2Fapi-keys&title=AI+Gateway+API+Keys), click **Create key**, name the key, and copy its value. You can't retrieve the value again. To create the key with the Vercel CLI instead, run:

```bash
vercel ai-gateway api-keys create --name my-api-key
```

Store the value as `AI_GATEWAY_API_KEY` in each environment that calls a model. For local development, add it to the `.env.local` env file:

```text
AI_GATEWAY_API_KEY=your_ai_gateway_api_key
```

Replace `your_ai_gateway_api_key` with the key's value, and keep the file out of version control. Framework dev commands such as `next dev` read variables from this file. Standalone Node.js and Python scripts don't load it, so export the variable in the shell that runs the script, or load the file in your code.

#### Use OIDC on Vercel deployments

An application deployed on Vercel can authenticate with its project's [OIDC token](https://vercel.com/docs/ai-gateway/authentication-and-byok/oidc). This avoids depending on a team member's API key, which Vercel deactivates when its creator leaves the team.

The AI SDK first checks the `apiKey` passed to `createGateway()`, then `AI_GATEWAY_API_KEY`, then OIDC. Even an invalid, non-empty API key takes priority. Remove both explicit API-key settings from the migrated client to use OIDC.

For local development, link your directory to the Vercel project:

```bash
vercel link
```

Pull the development environment variables, including the local OIDC token:

```bash
vercel env pull
```

The local token is valid for 12 hours. Run `vercel env pull` again to refresh it.

#### Check the credential

Before changing application code, set `GATEWAY_TOKEN` to your AI Gateway API key or the current `VERCEL_OIDC_TOKEN` value from `.env.local`:

```bash
export GATEWAY_TOKEN="your_selected_credential"
```

Test the token with a request billed to your AI Gateway Credits:

```bash
curl --fail-with-body \
  https://ai-gateway.vercel.sh/v1/chat/completions \
  -H "Authorization: Bearer $GATEWAY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "anthropic/claude-sonnet-5",
    "messages": [
      {"role": "user", "content": "Why is the sky blue?"}
    ]
  }'
```

Expect a JSON chat completion. For a `401`, `402`, or `403` response, see [troubleshooting](#troubleshooting). The `GATEWAY_TOKEN` variable is only for this test; application clients use the API key or OIDC setup above.

### 3\. Resolve each model ID against the catalog

Vercel AI Gateway names every model as a `creator/model` slug, such as `anthropic/claude-sonnet-5`, in every API format. Neon's [model IDs](https://neon.com/docs/ai-gateway/models) are short names with no provider prefix, such as `gpt-5-mini` or `claude-sonnet-5-5`, and Neon also accepts the same IDs with a `databricks-` prefix. Don't assume that adding a creator prefix to a Neon ID gives a valid slug. Look each one up.

Fetch the catalog to match gateway slugs with provider-native model IDs:

```bash
curl -s https://ai-gateway.vercel.sh/v1/models/catalog
```

The response's `models` array lists gateway slugs and their provider-native IDs. For each model string your app uses:

- Find every entry with a case-insensitive `providerModelId` match.
  
- If several slugs match, confirm the intended model type and version in the [model list](https://vercel.com/ai-gateway/models). Keep the standard version when the only alternative is its [fast-mode variant](https://vercel.com/docs/ai-gateway/models-and-providers/fast-mode).
  
- If no provider ID matches, verify the model's name and version to choose a slug.
  

Punctuation and suffixes differ between the two catalogs. Neon writes versions with hyphens, as in `gemini-3-1-pro`, and Vercel slugs can use a dot and a suffix, as in `google/gemini-3.1-pro-preview`. Treat a near match as a candidate until the model list confirms it's the model you mean.

If a model has no entry, don't substitute a similar name. Keep the call on Neon until you've tested a replacement. The model list includes capabilities and pricing.

Keep the existing embedding model, dimensions, and input settings during the gateway migration. If that model is available through Vercel AI Gateway's [embeddings API](https://vercel.com/docs/ai-gateway/sdks-and-apis/openai-chat-completions/embeddings), test the migrated calls against your existing index.

If you change embedding models, regenerate the stored embeddings before querying them with the new model. Different models can produce incompatible vectors even when their dimensions match; a dimension mismatch can cause the index to reject the query.

Record each call's resolved slug or why it must remain on Neon.

### 4\. Change the base URL and credential

Keep the API format your code already uses. Vercel AI Gateway has one base URL for each client family:

| Client                                                                          | Base URL                                |
| ------------------------------------------------------------------------------- | --------------------------------------- |
| OpenAI SDK, or an HTTP client that sends Chat Completions or Responses requests | `https://ai-gateway.vercel.sh/v1`       |
| Anthropic SDK, or an HTTP client that sends Messages requests                   | `https://ai-gateway.vercel.sh`          |
| TypeSafe SDK, or an HTTP client that sends decision requests                    | `https://ai-gateway.vercel.sh/typesafe` |

For OpenAI Responses over HTTP, send previous turns in `input`. AI Gateway's `gen_` IDs identify requests for observability and cannot substitute for provider response IDs. Use `previous_response_id` to continue turns on the same WebSocket connection. Check [Responses parameters](https://vercel.com/docs/ai-gateway/sdks-and-apis/responses#parameters) before moving a conversation that relies on stored response history.

The credential goes in `Authorization: Bearer`, and the URL carries no branch host. If you used separate Neon branches to track applications or environments, give each one an API key with its own budget.

Project budgets count requests authenticated with that project's OIDC token or an API key [scoped to the project](https://vercel.com/docs/ai-gateway/authentication-and-byok/api-keys#create-a-key). An unscoped key doesn't count toward the project budget, even when a deployment in that project uses it.

#### OpenAI SDK in TypeScript

These clients use the `openai` package. If your app doesn't have it yet, install it:

**pnpm**

```bash
pnpm add openai
```

**yarn**

```bash
yarn add openai
```

**npm**

```bash
npm install openai
```

**bun**

```bash
bun add openai
```

On Neon, the client sends the Neon credential as `apiKey` and builds its base URL from the branch host:

```typescript
const client = new OpenAI({
  apiKey: process.env.NEON_AI_GATEWAY_TOKEN,
  baseURL: `${process.env.NEON_AI_GATEWAY_BASE_URL}/v1`,
});
```

For the Responses API, the same client uses a base URL ending in `/openai/v1`. Both client configurations can use the Vercel base URL below:

```typescript
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);
```

Both Neon variables leave the client. As on Neon, the client holds no provider key, because Vercel's provider keys or your own keys from step 8 authenticate to the provider. Replace the example slug with the one you resolved in step 3. The API format doesn't decide which provider serves a request, so an OpenAI SDK client can also call models from other creators.

Neon's Chat Completions endpoint can return `message.content` as typed blocks for some Gemini and Claude models. If your application joins their text blocks, preserve that handling until you test the migrated responses.

On a Vercel deployment, the OpenAI and Anthropic SDKs don't find the OIDC token themselves. To pass it to them, install `@vercel/oidc`:

**pnpm**

```bash
pnpm add @vercel/oidc
```

**yarn**

```bash
yarn add @vercel/oidc
```

**npm**

```bash
npm install @vercel/oidc
```

**bun**

```bash
bun add @vercel/oidc
```

Await `getVercelOidcToken()` in each request handler and pass the token as `apiKey`. Vercel rotates function tokens within an hour.

#### Anthropic SDK

On Neon, the Anthropic SDK takes the Neon credential as `authToken` and a base URL ending in `/anthropic`:

```typescript
const client = new Anthropic({
  authToken: process.env.NEON_AI_GATEWAY_TOKEN,
  baseURL: `${process.env.NEON_AI_GATEWAY_BASE_URL}/anthropic`,
});
```

If your app doesn't have the `@anthropic-ai/sdk` package yet, install it:

**pnpm**

```bash
pnpm add @anthropic-ai/sdk
```

**yarn**

```bash
yarn add @anthropic-ai/sdk
```

**npm**

```bash
npm install @anthropic-ai/sdk
```

**bun**

```bash
bun add @anthropic-ai/sdk
```

On Vercel AI Gateway, the Anthropic base URL has no `/anthropic` or `/v1` suffix:

```typescript
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  apiKey: process.env.AI_GATEWAY_API_KEY,
  baseURL: 'https://ai-gateway.vercel.sh',
});

const response = await client.messages.create({
  model: "anthropic/claude-sonnet-5",
  messages: [
    {
      role: 'user',
      content: 'Why is the sky blue?',
    },
  ],
  max_tokens: 1024,
});

for (const block of response.content) {
  if (block.type === 'text') console.log(block.text);
}
```

Messages accepts the gateway credential in `x-api-key` or `Authorization: Bearer`, so the Anthropic SDK can keep its usual header. The example passes the credential as `apiKey` where Neon's setup uses `authToken`.

#### OpenAI SDK in Python

If your Python environment doesn't have the `openai` package yet, install it:

```bash
pip install openai
```

In Python, change the same two constructor arguments, `api_key` and `base_url`:

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AI_GATEWAY_API_KEY"],
    base_url="https://ai-gateway.vercel.sh/v1",
)

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5",
    messages=[
        {
            "role": "user",
            "content": "Why is the sky blue?",
        }
    ],
)

print(response.choices[0].message.content)
```

#### curl and other HTTP clients

On Neon, a raw request looks like this:

```bash
curl -X POST "$NEON_AI_GATEWAY_BASE_URL/v1/chat/completions" \
  -H "Authorization: Bearer $NEON_AI_GATEWAY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5-mini",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
```

Change the URL to `https://ai-gateway.vercel.sh/v1/chat/completions`, send the gateway credential in `Authorization: Bearer`, and use the resolved model slug. Step 2 shows the resulting request. Responses and Messages use `/v1/responses` and `/v1/messages`, where Neon uses `/openai/v1/responses` and `/anthropic/v1/messages`.

Decision requests keep their path. Vercel AI Gateway serves `POST /typesafe/v1/systemone` on its host, so change the host and credential, and confirm the decision model with `GET /typesafe/v1/models`.

#### Gemini API calls

For Neon's [native Gemini endpoint](https://neon.com/docs/ai-gateway/gemini), configure `@google/genai` with a placeholder API key and send the Neon credential in the authorization header:

```typescript
const ai = new GoogleGenAI({
  apiKey: 'placeholder',
  httpOptions: {
    apiVersion: 'v1beta',
    baseUrl: `${process.env.NEON_AI_GATEWAY_BASE_URL}/gemini`,
    headers: {
      Authorization: `Bearer ${process.env.NEON_AI_GATEWAY_TOKEN}`,
    },
  },
});
```

[Vercel AI Gateway](https://vercel.com/docs/ai-gateway/sdks-and-apis) accepts Google models through the AI SDK and OpenAI-compatible APIs. It doesn't accept Gemini's native `generateContent` format, so changing the Google Gen AI client's base URL is not enough.

Move generation calls to a supported client and use the resolved `google/` model slug. Update both the request construction and response handling, including streaming calls and raw requests to the native Gemini endpoint. Test the migrated behavior before moving that call to production.

If a call uses the Google Search grounding tool and reads `groundingMetadata`, move it separately. In the AI SDK, [Google web search](https://vercel.com/docs/ai-gateway/models-and-providers/web-search#provider-specific-search) is a provider tool that you pass in `tools`. Keep the call on Neon until you've tested a replacement that returns the sources your code reads.

After you change a client, run one of its calls. One completed response confirms the base URL, the credential, and the slug together.

### 5\. Move AI SDK calls to Vercel AI Gateway

Move calls individually with an explicit `gateway()` model. Each call you change selects Vercel AI Gateway, and calls that still use `neon()` keep going to Neon.

The examples use AI SDK 7. Check the AI SDK version your app has installed first:

```bash
pnpm list ai
```

Vercel AI Gateway supports AI SDK 6 and 7, with some [differences in option names](https://vercel.com/docs/ai-gateway/sdks-and-apis/ai-sdk#version-compatibility). AI SDK 7 requires Node.js 22 or later and ESM.

AI SDK 5 is deprecated, and teams new to Vercel AI Gateway can't use it. Support ends for existing teams on January 8, 2027. If your app uses version 5, follow the [AI SDK migration guides](https://ai-sdk.dev/docs/migration-guides) before changing these calls.

For the AI SDK 7 examples, install the AI SDK and Gateway provider:

**pnpm**

```bash
pnpm add ai@7 @ai-sdk/gateway
```

**yarn**

```bash
yarn add ai@7 @ai-sdk/gateway
```

**npm**

```bash
npm install ai@7 @ai-sdk/gateway
```

**bun**

```bash
bun add ai@7 @ai-sdk/gateway
```

On Neon, the `neon` provider wraps the model ID:

```typescript
import { neon } from '@neon/ai-sdk-provider';
import { generateText } from 'ai';

const { text } = await generateText({
  model: neon('gpt-5-mini'),
  prompt: 'What is Neon?',
});
```

Keep the prompt, but select the model through `gateway()` with the slug you resolved in step 3:

```typescript
import { gateway } from '@ai-sdk/gateway';
import { generateText } from 'ai';

const { text } = await generateText({
  model: gateway('openai/gpt-5-mini'),
  prompt: 'What is Neon?',
});

console.log(text);
```

This call now uses Vercel AI Gateway while other calls can remain on Neon. Explicit models also work with middleware and provider registries.

The AI SDK reads `AI_GATEWAY_API_KEY` from the environment. On a Vercel deployment, it uses the OIDC token when no API key is set.

Change the other places where Neon AI Gateway appears in AI SDK code:

| In your code                                          | Change                                                                                                                                                                                                                                                                                                                                                                                    |
| ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `neon()` models                                       | Use an explicit `gateway()` model with the resolved slug. Remove imports only when no remaining call uses them.                                                                                                                                                                                                                                                                           |
| `neon.embeddingModel()`                               | Use [`gateway.embeddingModel()`](https://vercel.com/docs/ai-gateway/modalities/embeddings) with the slug of the same embedding model, if the catalog lists it. In AI SDK 7, move `providerOptions.neon.dimensions` to the top-level `dimensions` option and preserve its value. Verify the returned vector length against your index before moving the call.                              |
| `neon.decisionModel()`                                | Use [`gateway.decisionModel()`](https://vercel.com/docs/ai-gateway/modalities/decision#ai-gateway-provider-instance) with the decision model's resolved slug. Preserve `state` and `questions`, and test the result handling before moving the call.                                                                                                                                      |
| `neon.tools.imageGeneration()`                        | Use [`openai.tools.imageGeneration()`](https://vercel.com/docs/ai-gateway/modalities/image-generation/ai-sdk) from `@ai-sdk/openai` and preserve the tool's options, including its image model. Neon provider 1.6.0 defaults to `gpt-image-2`. If your installed version uses that default, set `model: 'gpt-image-2'` explicitly in the replacement and test the generated image output. |
| Provider clients with a Neon base URL                 | Update the client as in step 4, or use `gateway()`. Keep packages still used by other calls.                                                                                                                                                                                                                                                                                              |
| Checks for Neon's `REQUEST_LIMIT_EXCEEDED` error code | Replace source-specific handling with the destination error handling in [Rate limiting](#rate-limiting) and [Daily spend cap](#daily-spend-cap).                                                                                                                                                                                                                                          |

Requests without an API key or OIDC token fail with `GatewayAuthenticationError`. Update Neon-specific checks and preserve handling for other provider errors.

### 6\. Set gateway options for usage, caching, and retention

Vercel AI Gateway uses `providerOptions.gateway`: a call option in the AI SDK, or a JSON-body field in the Chat Completions, Messages, and Responses APIs. Set the options below on the calls that need them.

#### Track usage by user and tag

On Neon's Launch, Scale, Agent, and Enterprise plans, the [consumption history API](https://neon.com/docs/guides/consumption-metrics) reports AI Gateway token usage by project or branch. On Vercel AI Gateway, add a user ID or tags to each request to group its usage.

The OpenAI TypeScript SDK doesn't declare AI Gateway's extension fields. Spread `providerOptions` into the request to send usage attribution, as shown here for one user and two tags:

```typescript
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: 'Tell me about San Francisco.',
    },
  ],
  // The upstream SDK types omit
  // AI Gateway extension fields.
  ...{
    providerOptions: {
      gateway: {
        user: 'user-123',
        tags: ['feature:chat', 'env:development'],
      },
    },
  },
});

console.log(response.choices[0]?.message.content);
```

Vercel AI Gateway takes one `user` string of up to 256 characters and up to 10 tags of 1 to 64 characters each. If you separated usage by Neon project or branch, write each one as a tag, such as `branch:preview`. [Custom Reporting](https://vercel.com/docs/ai-gateway/observability-and-spend/custom-reporting) counts each unique tag or user ID in a request as one write and charges $0.075 per 1,000 writes.

In Python, pass the same object in `extra_body`:

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AI_GATEWAY_API_KEY"],
    base_url="https://ai-gateway.vercel.sh/v1",
)

response = client.chat.completions.create(
    model="anthropic/claude-sonnet-5",
    messages=[
        {
            "role": "user",
            "content": "Explain model fallbacks in one sentence.",
        }
    ],
    extra_body={
        "providerOptions": {
            "gateway": {
                "models": ["openai/gpt-6-astra"],
                "user": "user-123",
                "tags": ["feature:summaries"],
                "caching": "auto",
            }
        }
    },
)

print(response.choices[0].message.content)
```

This request enables prompt caching and adds a fallback model, covered in step 7. The Anthropic Python SDK also accepts these options through `extra_body`.

#### Preserve prompt caching

Neon's Anthropic Messages endpoint forwards `cache_control` unchanged. Vercel AI Gateway also preserves explicit cache markers when you omit `caching`.

With `caching: 'auto'`, the gateway adds markers for providers that need them. The provider can reuse the cached prompt prefix at its reduced input-token rate, but still generates a response for every request.

#### Review data retention

On Neon, most models are served through Databricks, and [retention for those requests](https://neon.com/docs/ai-gateway/data-retention) follows Databricks' policy. Under that policy, Databricks may store inputs and outputs for up to 30 days to prevent abuse. On Vercel AI Gateway, a request can route to any provider that serves the model, so compare each call's retention requirement with the providers it can reach.

If a request requires provider zero data retention, set `zeroDataRetention: true`. Vercel AI Gateway restricts the request and its fallbacks to eligible providers and fails if none can serve the model. This requirement is separate from the gateway's own payload logging policy.

Per-request ZDR requires a Pro or Enterprise plan or purchased AI Gateway Credits. BYOK keys must be marked ZDR-compliant under your own provider agreement. Check the [requirements and exclusions](https://vercel.com/docs/ai-gateway/security-and-compliance/zdr#per-request-zero-data-retention) before moving a protected workload.

### 7\. Add fallbacks and provider routing

Neon serves each model through one provider, usually Databricks. Vercel AI Gateway can route a model to several providers and try other models if the primary choice fails. Configure these options where your application needs them.

Add fallback models to `providerOptions.gateway.models` when they can share the primary model's request. Keep your fallback loop if attempts need different prompts, tools, credentials, retries, or timeouts.

Vercel AI Gateway receives the fallback list with the request:

```typescript
import { gateway } from '@ai-sdk/gateway';
import { generateText } from 'ai';

const result = await generateText({
  model: gateway('anthropic/claude-opus-5.5'),
  prompt: 'Write a haiku about TypeScript.',
  providerOptions: {
    gateway: {
      models: ['openai/gpt-5.5'],
    },
  },
});

console.log(result.text);
```

Vercel AI Gateway routes the request to the primary model first. When every provider for a model fails, it tries the next model in `models`, and the response comes from the first model and provider that succeed. The option works in every API format, in the JSON body or in `extra_body`. Resolve each fallback's slug in the catalog the way you did the primary model's.

Inspect the `routing` object in `result.providerMetadata?.gateway`. The entry in `modelAttempts` with `success: true` identifies the model by `canonicalSlug`, while `finalProvider` identifies the serving provider. Open the request in Logs to review the same routing history.

Vercel AI Gateway also tries other providers for the same model. It uses recent uptime and latency to choose a provider unless you set [routing options](https://vercel.com/docs/ai-gateway/models-and-providers/provider-filtering-and-ordering):

- `order` lists provider slugs in the order to try them. It sets a preference, so other providers can still serve the request.
  
- `only` restricts routing to the providers you list. If those providers are down, rate limited, or out of capacity, the request fails.
  
- `sort` ranks providers by cost, time to first token, or tokens per second. Use `'cost'`, `'ttft'`, or `'tps'` respectively.
  

When a request sets both `only` and `order`, `only` defines the allowed set and `order` sets the priority within it.

### 8\. Set up provider keys and billing

Neon AI Gateway needs no provider API keys and bills inference to [prepaid credits](https://neon.com/docs/ai-gateway/prepaid-credits). Vercel AI Gateway's default is the same arrangement, with Vercel's provider keys and AI Gateway Credits, and your own provider keys are an option. Each option still needs the Vercel credential from step 2.

| On Vercel AI Gateway                            | Setup                                                                                                                                                                                                                   |
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AI Gateway Credits, with Vercel's provider keys | Purchase credits                                                                                                                                                                                                        |
| Team BYOK                                       | On the [Bring Your Own Key (BYOK) page](https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai-gateway%2Fbyok&title=AI+Gateway+BYOK), find the provider, click **Add Key**, enter the credentials, and click **Test API Key** |
| Request-scoped BYOK                             | Send the key in `providerOptions.gateway.byok`                                                                                                                                                                          |

Request-scoped BYOK puts the provider key in the request's options. Set `ANTHROPIC_API_KEY` to your provider key before running this example:

```typescript
import { gateway } from '@ai-sdk/gateway';
import { generateText } from 'ai';

const { text } = await generateText({
  model: gateway('anthropic/claude-sonnet-5'),
  prompt: 'Explain quantum computing in two sentences.',
  providerOptions: {
    gateway: {
      byok: {
        anthropic: [
          {
            apiKey: process.env.ANTHROPIC_API_KEY!,
          },
        ],
      },
    },
  },
});

console.log(text);
```

When a request carries its own credentials, Vercel AI Gateway doesn't consider the keys stored in the dashboard for that request. In both cases, the request's details in Logs show whether your key or Vercel's provider keys served it.

Team BYOK keys are available across projects. BYOK requires purchased AI Gateway Credits and a positive balance; otherwise, the gateway returns `402`. If your provider key fails, the gateway retries on Vercel's keys by default and bills that usage to your credit balance.

Vercel AI Gateway stores up to 10 keys per provider and uses the oldest enabled key by default. ZDR requests can use another enabled key marked ZDR-compliant.

Team owners can disable [Fallback to Vercel Keys](https://vercel.com/docs/ai-gateway/authentication-and-byok/byok#turn-off-fallback-to-vercel-keys) in AI Gateway Settings to use only their provider credentials. The team pays $0.20 per 1,000 successful BYOK requests from AI Gateway Credits, and the fee counts toward budgets.

Vercel adds no markup or platform fee to token charges. [AI Gateway Credits](https://vercel.com/docs/ai-gateway/pricing) cover calls using Vercel's keys; your provider bills BYOK tokens directly.

Purchased credits expire after one year, and payment processing fees may apply. Every team starts with a monthly free credit for a subset of models. Purchasing credits moves the team to the paid tier and ends that free credit.

Neon credits and AI Gateway Credits are separate balances. Neon credits are valid for 12 months from purchase, so size your remaining Neon balance for the calls that stay there through cutover and rollback. Low balances also fail differently. Neon returns `429` to new requests once the balance drops below $2, and Vercel AI Gateway returns `402` when the team has no positive credit balance.

### 9\. Cut over and verify

Move one call site at a time, keeping unverified paths on Neon.

1. Complete the request-limit, spend-limit, retention, and routing checks required by that call site.
   
2. Deploy to preview or staging with the intended API key or OIDC credential.
   
3. Test streaming, tool calls, structured output, fallbacks, and rejected requests.
   
4. Review the repository search results for references still used by migrated paths. Keep references needed by calls that remain on Neon.
   
5. Confirm the model, provider, credential source, and routing attempts in Vercel AI Gateway Logs. Set a budget for that credential or project.
   
6. Shift production traffic gradually and compare application errors and model output. Keep a working Neon credential and credit balance for rollback.
   

In the Vercel dashboard, open **AI Gateway**, then [**Logs**](https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai-gateway%2Flogs&title=AI+Gateway+Logs). Each row records the request's time, status, model, provider, usage, cost, duration, and authentication. New rows can take about 90 seconds to appear.

Open a row to inspect its routing attempts and credential source. Confirm that the request used the intended model, provider, and key; a successful response alone doesn't establish that the migration preserved those choices.

To list the same requests from your terminal, run:

```bash
vercel ai-gateway requests list --since 24h
```

Budgets are checked before each request. Once a limit is exceeded, Vercel AI Gateway returns `402`, including for covered BYOK requests. Provider-billed BYOK token charges don't count toward the budget; the fee for disabling fallback does.

> **Warning:**
>
> Revoking a Neon credential stops every use of that credential on its branch and descendants. Check for other consumers, including Object Storage or Neon Functions when its scopes permit them. Revoke it only after those uses have ended and rollback is no longer needed.

After the final call site has moved, check for remaining Neon requests over a period that includes scheduled and infrequent jobs. Use the [consumption history API](https://neon.com/docs/guides/consumption-metrics) on eligible Neon plans. On Free, use your application's request logs or instrumentation.

Once the migration is stable and rollback is no longer needed, revoke unused credentials and remove unused packages. Select the intended project and branch in the Neon CLI, then find the credential ID with `neon credentials list` and revoke it with the following command.

```bash
neon credentials revoke your_token_id
```

Use the credential ID for `your_token_id`. Keep credentials still in use.

## What doesn't map from Neon AI Gateway

### Branch-scoped hosts and credentials

Neon issues a gateway host for each branch and credentials that work on that branch and its descendants. Vercel AI Gateway uses one host, and its API keys can authenticate from any environment.

To keep environments separate, create a key for each environment, store it only where that environment runs, and assign it a budget. Vercel does not apply Neon branch inheritance to those keys.

If your Neon credential expires, set an expiration date on its replacement API key. Otherwise, the Vercel key remains valid until revoked.

Neon Functions get both Neon variables with no setup. Vercel supplies a credential that way on Vercel deployments, through the project's OIDC token. Code that stays in a Neon Function, or on any other host, needs an API key that you store as `AI_GATEWAY_API_KEY` in that host's own configuration for secrets.

### Rate limiting

Neon applies [default limits](https://neon.com/docs/ai-gateway/models) of 200,000 input tokens and 200,000 output tokens per minute to each account, counted separately. Both are soft limits that can vary by account. Vercel AI Gateway applies per-model rate limits on the free tier. The paid tier removes those gateway limits, but upstream provider limits still apply.

For a custom limit on Vercel, protect your model endpoint with [WAF rate limiting](https://vercel.com/docs/vercel-firewall/vercel-waf/rate-limiting). To allow 100 requests per minute:

1. Select your project in the Vercel dashboard, open **Firewall**, then select **Configure** and **\+ New Rule**.
   
2. Name the rule and match **Request Path** with **Equals**. Enter `/api/chat`, or the path of your model endpoint.
   
3. Set the action to **Rate Limit** with **Fixed Window**. Use a **Time Window** of 60 seconds and a **Request Limit** of 100, grouped by source IP.
   
4. Choose **Log** to monitor the rule first. Save it, select **Review Changes**, and inspect the change before choosing **Publish**, which applies it to production. Log mode doesn't block requests.
   
5. Check the rule's traffic in **Firewall**. Once the matches are correct, change the action to **Too Many Requests (429)** and publish the change to enforce the limit.
   

Each source IP has a separate counter in each region, so this is not a gateway-wide limit of 100 requests. The rule counts requests rather than tokens and covers only the protected Vercel route. For endpoints on another host, enforce limits there or in application code. Set a separate budget to control spending.

Rate-limit errors also change shape. Neon returns its account limits as `429` with the error code `REQUEST_LIMIT_EXCEEDED`. Vercel AI Gateway returns `429` with the type `rate_limit_exceeded`, and a provider's `429` can carry that provider's own error body.

### Daily spend cap

Neon enforces an account-level daily spend cap that can vary by account. Confirm the limit for your account before configuring the replacement budget. Past the cap, Neon AI Gateway returns `429` with `REQUEST_LIMIT_EXCEEDED`.

Vercel AI Gateway has no default spend cap. Once budgets are configured, each request must pass every applicable team, project, API-key, and member limit. Defaults can also cover resources without a custom budget.

To preserve Neon's daily cap, set the appropriate [budget](https://vercel.com/docs/ai-gateway/observability-and-spend/budgets) with a `daily` refresh period. It resets at midnight UTC.

The budget check runs at the start of each request, so the request that crosses the limit still completes. After that, Vercel AI Gateway rejects requests in that scope with `402` and the type `quota_for_entity_exceeded` until the budget resets or you raise it. Error handling that only looks for `429` won't catch a budget rejection, so add a branch for `402`.

### Retries and timeouts

Neon recommends exponential backoff for transient upstream errors. Review your application's retry settings, especially if the migration changes its client.

For upstream timeouts, Neon sends [`X-Should-Retry: false`](https://neon.com/docs/ai-gateway/troubleshooting) to suppress automatic retries in the OpenAI and Anthropic SDKs. Set retry counts and timeouts explicitly for Vercel AI Gateway, then test slow requests before cutover.

The AI SDK retries failed requests with exponential backoff, and its `maxRetries` option defaults to 2. In a direct HTTP client, honor the `retry-after` header on a `429` when it's present, and back off exponentially otherwise.

The AI SDK's [streaming timeouts](https://ai-sdk.dev/docs/ai-sdk-core/settings#timeout) let you separate the wait for initial model output from the total response duration. Save this helper in `lib/stream-with-limits.ts` and return its response from your existing HTTP handler:

```typescript
import { gateway } from '@ai-sdk/gateway';
import { streamText } from 'ai';

export function streamWithLimits(
  prompt: string,
) {
  const result = streamText({
    model: gateway('openai/gpt-6-luna'),
    prompt,
    maxRetries: 2,
    timeout: {
      firstChunkMs: 10_000,
      totalMs: 60_000,
    },
  });

  return result.toTextStreamResponse();
}
```

The helper allows two retries for retryable failures when starting the model call. Once the provider response stream opens, the first-output timer allows 10 seconds for content such as text, reasoning, or tool input. Metadata alone doesn't satisfy it. The 60-second total deadline also covers the initial connection, retries, and backoff.

Choose the total deadline for the longest response your app should allow. In this helper, a first-output timeout ends the call, and a broken stream isn't resumed. Keep application error reporting in place because generation failures don't automatically become HTTP error responses.

Vercel AI Gateway's [`providerTimeouts`](https://vercel.com/docs/ai-gateway/models-and-providers/provider-timeouts) is in Beta and applies only to BYOK credentials. For streams, it waits for the first chunk; for non-streaming calls, it waits for the complete response. On expiry, the gateway aborts the attempt and tries the next available provider. Providers that cannot cancel may still charge for that attempt. Use client timeouts for requests made with Vercel's provider keys.

## Troubleshooting

| What you observe                                         | What to check                                                                                                                                                                        |
| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `401`                                                    | The credential is missing, invalid, or revoked. Check that `apiKey` no longer holds a Neon credential.                                                                               |
| `401` in local development after earlier requests worked | The local OIDC token has expired. Run `vercel env pull` again.                                                                                                                       |
| `402`                                                    | The team has no positive credit balance, which every request needs, including BYOK requests. When the error's `type` is `quota_for_entity_exceeded`, a budget has reached its limit. |
| `403` with a message that names the free tier            | The model isn't in the free-tier subset. Choose a free-tier model or purchase credits.                                                                                               |
| `429`                                                    | An AI Gateway or upstream provider rate limit was exceeded. Retry after a short wait.                                                                                                |
| OIDC isn't used on a Vercel deployment                   | For the AI SDK, remove the explicit `apiKey` option and `AI_GATEWAY_API_KEY`. For OpenAI or Anthropic clients, pass the current OIDC token as described in step 4.                   |
| AI SDK calls still reach Neon                            | The call still uses a `neon()` model or a provider client with a Neon base URL. Use an explicit `gateway()` model.                                                                   |
| Vercel AI Gateway rejects a model ID that worked on Neon | The request still sends a Neon short ID or a guessed slug. Use the exact slug from the catalog in step 3.                                                                            |
| Spend-limit handling doesn't run                         | The code checks for Neon's `429` and `REQUEST_LIMIT_EXCEEDED`. A Vercel budget rejection is a `402` with the type `quota_for_entity_exceeded`.                                       |
| BYOK requests show Vercel's provider keys in Logs        | Open the row and inspect the routing attempts and credential source. Check whether your key failed, was excluded by ZDR, or was replaced by request-scoped BYOK credentials.         |

## Next steps

- Set [spend limits for a team, project, API key, or team member](https://vercel.com/docs/ai-gateway/observability-and-spend/budgets)
  
- Add [prompt caching and an application response cache](https://vercel.com/docs/ai-gateway/models-and-providers/automatic-caching)
  
- Group usage by user or tag with the [Custom Reporting API](https://vercel.com/docs/ai-gateway/observability-and-spend/custom-reporting)
  

## Frequently asked questions

### Can I use Vercel AI Gateway with a Neon database?

Yes. Vercel AI Gateway is a hosted API, and an AI Gateway API key authenticates requests from any server or cloud. Your app needs a Vercel account for the key and for billing, and no Vercel project or deployment. Moving model calls to Vercel AI Gateway doesn't change your Neon Postgres connection.

### Do Neon AI Gateway model IDs work on Vercel AI Gateway?

No. Neon AI Gateway uses short model IDs with no provider prefix, and Vercel AI Gateway identifies each model by a `creator/model` slug. Prefixing a Neon ID with a creator name can produce a slug that doesn't exist, because the two catalogs punctuate versions differently. Match every Neon model ID to a slug in the Vercel AI Gateway catalog before moving the call.

### Does Vercel AI Gateway support the Gemini API and the google-genai SDK?

No. Vercel AI Gateway has no API in the Gemini `generateContent` format that Neon AI Gateway serves at `/gemini`. Call Google models with a `google/` slug through the AI SDK or the OpenAI-compatible Chat Completions API, and rewrite the request and response handling for that format.

### Does Vercel AI Gateway have a daily spend cap like Neon AI Gateway?

Not by default. Neon AI Gateway enforces a daily spend cap at the account level, and Vercel AI Gateway limits spend where you create a budget. Budgets with a daily refresh period reset at midnight UTC, and requests over an exceeded budget get a `402` response.

### Do I need my own provider keys for Vercel AI Gateway?

No. Vercel's provider keys serve requests billed to AI Gateway Credits. To use your own keys, add each provider key for your team in the dashboard, or send a key with a single request in `providerOptions.gateway.byok`. BYOK needs purchased AI Gateway Credits, and requests fall back to Vercel's provider keys by default when your key fails.

## More AI Gateway guides

- [Migrate from Netlify AI Gateway to Vercel AI Gateway](/kb/guide/netlify-aig-to-vercel-aig): Replace Netlify's injected provider keys and base URLs with a Vercel AI Gateway credential, map each model to a creator/model slug, and move Gemini SDK calls to a supported API.
- [Migrate from Cloudflare AI Gateway to Vercel AI Gateway](/kb/guide/cloudflare-aig-to-vercel-aig): Swap Cloudflare's base URL and cf-aig-\* headers for Vercel's, map each model to a creator/model slug, and move caching, rate limits, and guardrails into your app.
- [How to control AI provider data handling with AI Gateway](/kb/guide/control-ai-provider-data): Prevent AI providers from training on your prompts, enforce zero data retention, and restrict providers and models with Vercel AI Gateway.

## 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](/kb/architecture/agents): Build and operate agents with models, tools, and durable workflows.
- [Web applications](/kb/architecture/web): Choose rendering, data, authentication, and caching approaches.
- [Backends](/kb/architecture/backends): Choose a runtime, connect services, and run background work.

[Browse all stacks](/kb/architecture)

## Build with prompts

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

[Browse the prompt library](/kb/prompts) · [Read the Markdown index](/kb/prompts.md)

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```
