All skills
vercel-labs avatar

/ai-gateway

@8fd4644 official

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.

  • 5 files
  • 49.1 KB
  • Updated last week
  • GitHub

Use this Skill: https://skilld.dev/gh/vercel-labs/vercel-plugin/ai-gateway

This session only. Nothing lands on disk.

referencessetup.md

≈1.9k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Setup and compatible APIs

Use this reference for first requests, authentication setup, migration, and compatible clients.

First request

  1. Confirm a Vercel account and team are available.
  2. For free AI Gateway Credits, the team needs a valid payment method. If the gateway returns customer_verification_required, use the action URL in the error.
  3. Create an AI Gateway API key from the dashboard or CLI, or use OIDC for a Vercel deployment.
  4. Export AI_GATEWAY_API_KEY in the shell or load it from an uncommitted environment file.
  5. Fetch /v1/models, choose a current model, and make one request.
  6. Print or return the result.
  7. Open AI Gateway Logs and inspect the model, provider, usage, cost, status, and routing attempts. Allow about 90 seconds for ingestion.

Canonical tutorial: https://vercel.com/docs/ai-gateway/getting-started

When a user asks a coding agent to make this request, the coding agent is the tool writing and running the API call. Its own inference does not need to use AI Gateway. The selected provider/model is the target of the request, not the identity of the coding agent. Routing the agent's own model traffic is a separate workflow routed from SKILL.md.

API key setup

Dashboard: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai-gateway%2Fapi-keys&title=AI+Gateway+API+Keys

export AI_GATEWAY_API_KEY="your_ai_gateway_api_key"

The key value is shown once. Never write it to committed source or print it in a response.

Agent-safe credential handling

Reuse an existing key without revealing it. Do not inspect the environment with broad commands such as env, bare set, or printenv, and do not echo the value. Use a subshell so tracing is restored automatically:

(
  set +x
  if [ -n "${AI_GATEWAY_API_KEY:-}" ]; then
    echo "AI_GATEWAY_API_KEY is set"
  else
    echo "AI_GATEWAY_API_KEY is missing"
  fi
)

If the key exists, skip CLI login and team-scope discovery unless another requested operation needs them. If it is missing and the user authorized key creation:

  1. Use the existing project CLI when available; otherwise use npx vercel@latest without installing globally.
  2. Read ai-gateway api-keys create --help before choosing flags.
  3. Reuse the current CLI team scope. Ask for a team only when that scope is missing or ambiguous.
  4. Prefer an interactive prompt or OS credential store. Never put a literal key in shell history or a command argument, and never send raw key output through agent logs or chat.
  5. Keep shell tracing disabled while a secret is in scope; prefer a subshell so the prior tracing state returns automatically.

For a one-request smoke test, report the generated content, whether the request succeeded, and any action the user must take. Do not dump authorization headers or an unfiltered raw response.

Use the CLI when the user asks for CLI management:

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

The CLI can bind a budget, spend alerts, and an expiry at creation, which beats re-editing the key later:

vercel ai-gateway api-keys create --budget 500 --alert-thresholds 75,100 --expiration 90d

inspect shows a key's budget, spend, BYOK spend, alerts, and expiry; list shows every key. Run vercel ai-gateway api-keys create --help before scripting because available quota, expiration, alert, and restriction-exemption flags change.

OIDC setup

OIDC is preferred for Vercel deployments because the deployment receives VERCEL_OIDC_TOKEN automatically. For local development against a linked Vercel project:

vercel link
vercel env pull

The current OIDC documentation states that locally pulled tokens are valid for 12 hours. Re-run vercel env pull when the token expires.

Do not say that OIDC removes request authentication. The token authenticates the request to AI Gateway. BYOK credentials are separate provider credentials.

Docs: https://vercel.com/docs/ai-gateway/authentication-and-byok/oidc

AI SDK

Current AI SDK JavaScript releases require Node.js 22 or later. Verify the installed package rather than upgrading an established project without approval.

A plain provider/model string uses AI Gateway:

import { generateText } from 'ai';

const model = process.env.AI_GATEWAY_MODEL;
if (!model) {
  throw new Error('Set AI_GATEWAY_MODEL to an ID returned by /v1/models');
}

const { text } = await generateText({
  model,
  prompt: 'Explain this codebase.',
});

console.log(text);

Load the ai-sdk skill and read node_modules/ai/docs/ before writing SDK-specific code. Use @ai-sdk/gateway exports only when needed. Do not add a provider-specific package for a model called through AI Gateway.

AI SDK for Python

Current AI SDK for Python releases require Python 3.12 or later. Install and follow its current docs:

uv add ai
import asyncio
import os
import ai


async def main() -> None:
    model = ai.get_model(os.environ['AI_GATEWAY_MODEL'])
    messages = [ai.user_message('Explain this project.')]

    async with ai.stream(model, messages) as stream:
        async for event in stream:
            if isinstance(event, ai.events.TextDelta):
                print(event.chunk, end='', flush=True)


asyncio.run(main())

Docs: https://vercel.com/docs/ai-gateway/sdks-and-apis/ai-sdk-python

Compatible clients

Client or API Base URL or endpoint
OpenAI Chat Completions and OpenAI Responses SDKs https://ai-gateway.vercel.sh/v1
Anthropic Messages SDK https://ai-gateway.vercel.sh
OpenResponses HTTP https://ai-gateway.vercel.sh/v1/responses
Cohere Rerank Follow the current Cohere Rerank page

Keep the client's request shape and replace its base URL and request authentication. AI Gateway model IDs remain provider/model strings even when using an OpenAI or Anthropic SDK.

Docs: https://vercel.com/docs/ai-gateway/sdks-and-apis

Migration

For an existing integration:

  1. Inventory the SDK, model IDs, provider-specific request fields, provider credentials, streaming behavior, and error handling.
  2. Choose the closest AI Gateway API shape. An existing OpenAI or Anthropic client can usually keep its SDK.
  3. Change request authentication and the base URL.
  4. Map model IDs to live AI Gateway slugs. Do not mechanically prepend a provider name.
  5. Preserve provider-specific options that the selected API supports.
  6. Remove direct-provider credentials only after the AI Gateway path passes a live request.
  7. Verify usage, cost, and routing in Logs.

Migration guide: https://vercel.com/docs/ai-gateway/getting-started/migrate-to-ai-gateway

Common first-request errors

Status or type Meaning Action
401 Missing, invalid, or revoked API key/OIDC token Fix request authentication
402 insufficient_funds No positive AI Gateway Credits balance Add credits
402 quota_for_entity_exceeded A team, project, API key, or user budget is exhausted Wait for refresh or raise the budget
403 customer_verification_required A valid payment method is required for free credits Use the action URL in the error
429 Gateway or provider rate limit Honor retry-after when present and retry with backoff; see the rate limits page
503 Provider capacity or gateway service unavailable Retry if safe; inspect provider attempts before changing routing

Source: SKILL.md on GitHub

No third-party reports yet.

Signed by skilld at 8fd4644. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 11 hours ago.

Activeupdated last week
Other metadata
summary
Set up and operate Vercel AI Gateway with current models, correct authentication, routing, spend controls, and verification.
metadata
{
  "priority": 7,
  "docs": [
    "https://vercel.com/docs/ai-gateway",
    "https://vercel.com/docs/ai-gateway/getting-started",
    "https://ai-sdk.dev/providers/ai-sdk-providers/ai-gateway"
  ],
  "sitemap": "https://vercel.com/docs/sitemap.md",
  "pathPatterns": [],
  "importPatterns": [
    "ai",
    "@ai-sdk/gateway"
  ],
  "bashPatterns": [
    "\\bvercel\\s+ai-gateway\\b",
    "\\bvercel\\s+env\\s+pull\\b",
    "\\bnpm\\s+(install|i|add)\\s+[^\\n]*@ai-sdk/gateway\\b",
    "\\bpnpm\\s+(install|i|add)\\s+[^\\n]*@ai-sdk/gateway\\b",
    "\\bbun\\s+(install|i|add)\\s+[^\\n]*@ai-sdk/gateway\\b",
    "\\byarn\\s+add\\s+[^\\n]*@ai-sdk/gateway\\b"
  ],
  "promptSignals": {
    "phrases": [
      "ai gateway",
      "vercel ai gateway",
      "ai-gateway",
      "ai-gateway.vercel.sh"
    ],
    "allOf": [
      [
        "model",
        "routing"
      ],
      [
        "provider",
        "failover"
      ],
      [
        "gateway",
        "budget"
      ],
      [
        "gateway",
        "logs"
      ],
      [
        "gateway",
        "oidc"
      ],
      [
        "coding",
        "gateway"
      ]
    ],
    "anyOf": [
      "provider ordering",
      "model fallback",
      "byok",
      "spend tracking",
      "gateway key",
      "credit balance",
      "safety identifier",
      "reasoning effort",
      "tool calling",
      "structured outputs"
    ],
    "noneOf": [
      "cloudflare ai gateway",
      "aws api gateway"
    ],
    "minScore": 6
  }
}
validate
[
  {
    "pattern": "\\bclaude-(sonnet|opus|haiku)-\\d+-\\d+\\b",
    "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.",
    "severity": "error"
  },
  {
    "pattern": "gateway\\(['\"][^'\"/]+['\"]\\)",
    "message": "AI Gateway model string is missing its provider prefix. Fetch /v1/models and use a provider/model ID.",
    "severity": "error"
  },
  {
    "pattern": "(OPENAI_API_KEY|ANTHROPIC_API_KEY|GOOGLE_API_KEY)",
    "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.",
    "severity": "recommended",
    "skipIfFileContains": "[Bb][Yy][Oo][Kk]|providerOptions\\s*:\\s*\\{[^}]*gateway"
  },
  {
    "pattern": "gateway\\s*:\\s*\\{[^}]*cacheControl",
    "message": "AI Gateway does not cache whole responses through cacheControl. Use caching: 'auto' for provider prompt caching and verify the current caching docs.",
    "severity": "error"
  },
  {
    "pattern": "ANTHROPIC_BASE_URL\\s*=\\s*[\"']?https://ai-gateway\\.vercel\\.sh",
    "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.",
    "severity": "recommended",
    "skipIfFileContains": "ANTHROPIC_AUTH_TOKEN"
  }
]
chainTo
[
  {
    "pattern": "from\\s+['\"]ai['\"]|require\\(['\"]ai['\"]\\)|\\b(generateText|streamText|ToolLoopAgent)\\b",
    "targetSkill": "ai-sdk",
    "message": "AI SDK code detected. Load the AI SDK skill and read the installed package docs before writing or changing SDK code."
  }
]
retrieval
{
  "aliases": [
    "model router",
    "ai proxy",
    "provider failover",
    "llm gateway",
    "gateway credits"
  ],
  "intents": [
    "add Vercel AI Gateway to an application",
    "route AI models across providers",
    "configure provider or model fallbacks",
    "authenticate AI Gateway requests",
    "track AI model costs and set budgets",
    "debug AI Gateway requests and routing",
    "connect coding agents to AI Gateway",
    "find a model by modality, capability, price, or data retention",
    "check AI Gateway credit balance or generation cost",
    "configure reasoning or extended thinking across providers and API formats",
    "add tool calling or function calling across API formats",
    "get structured JSON output matching a schema",
    "send images or PDFs to a model"
  ],
  "entities": [
    "AI Gateway",
    "AI Gateway Credits",
    "providerOptions.gateway",
    "AI_GATEWAY_API_KEY",
    "VERCEL_OIDC_TOKEN",
    "model routing",
    "provider failover",
    "BYOK",
    "spend reporting",
    "safetyIdentifier",
    "Usage & Billing API"
  ]
}

README badge

README badge for vercel-labs/vercel-plugin/ai-gateway