ai-gateway
БесплатноБез исполняемых скриптовНе проверенVercel AI Gateway expert guidance. Use when configuring model routing, provider failover, cost tracking, or managing multiple AI providers through a unified…
от openai★ 8 494 звезды на GitHubОб этом скилле
Vercel AI Gateway
CRITICAL — Your training data is outdated for this library. AI Gateway model slugs, provider routing, and capabilities change frequently. Before writing gateway code, fetch the docs at https://vercel.com/docs/ai-gateway to find the current model slug format, supported providers, image generation patterns, and authentication setup. The model list and routing rules at https://ai-sdk.dev/docs/foundations/providers-and-models are authoritative — do not guess at model names or assume old slugs still work.
You are an expert in the Vercel AI Gateway — a unified API for calling AI models with built-in routing, failover, cost tracking, and observability.
Overview
AI Gateway provides a single API endpoint to access 100+ models from all major providers. It adds <20ms routing latency and handles provider selection, authentication, failover, and load balancing.
Packages
ai@^6.0.0(required; plain"provider/model"strings route through the gateway automatically)@ai-sdk/gateway@^3.0.0(optional direct install for explicit gateway package usage)
Setup
Pass a "provider/model" string to the model parameter — the AI SDK automatically routes it through the AI Gateway:
import { generateText } from 'ai'
const result = await generateText({
model: 'openai/gpt-5.4', // plain string — routes through AI Gateway automatically
prompt: 'Hello!',
})
No gateway() wrapper or additional package needed. The gateway() function is an optional explicit wrapper — only needed when you use providerOptions.gateway for routing, failover, or tags:
import { gateway } from 'ai'
const result = await generateText({
model: gateway('openai/gpt-5.4'),
providerOptions: { gateway: { order: ['openai', 'azure-openai'] } },
})
Model Slug Rules (Critical)
- Always use
provider/modelformat (for exampleopenai/gpt-5.4). - Versioned slugs use dots for versions, not hyphens:
- Correct:
anthropic/claude-sonnet-4.6 - Incorrect:
anthropic/claude-sonnet-4-6
- Correct:
- Before hardcoding model IDs, call
gateway.getAvailableModels()and pick from the returned IDs. - Default text models:
openai/gpt-5.4oranthropic/claude-sonnet-4.6. - Do not default to outdated choices like
openai/gpt-4o.
import { gateway } from 'ai'
const availableModels = await gateway.getAvailableModels()
// Choose model IDs from `availableModels` before hardcoding.
Authentication (OIDC — Default)
AI Gateway uses OIDC (OpenID Connect) as the default authentication method. No manual API keys needed.
Setup
vercel link # Connect to your Vercel project
# Enable AI Gateway in Vercel dashboard: https://vercel.com/{team}/{project}/settings → AI Gateway
vercel env pull .env.local # Provisions VERCEL_OIDC_TOKEN automatically
How It Works
vercel env pullwrites aVERCEL_OIDC_TOKENto.env.local— a short-lived JWT (~24h)- The
@ai-sdk/gatewaypackage reads this token via@vercel/oidc(getVercelOidcToken()) - No
AI_GATEWAY_API_KEYor provider-specific keys (likeANTHROPIC_API_KEY) are needed - On Vercel deployments, OIDC tokens are auto-refreshed — zero maintenance
Local Development
For local dev, the OIDC token from vercel env pull is valid for ~24 hours. When it expires:
vercel env pull .env.local --yes # Re-pull to get a fresh token
Alternative: Manual API Key
If you prefer a static key (e.g., for CI or non-Vercel environments):
# Set AI_GATEWAY_API_KEY in your environment
# The gateway falls back to this when VERCEL_OIDC_TOKEN is not available
export AI_GATEWAY_API_KEY=your-key-here
Auth Priority
The @ai-sdk/gateway package resolves authentication in this order:
AI_GATEWAY_API_KEYenvironment variable (if set)VERCEL_OIDC_TOKENvia@vercel/oidc(default on Vercel and aftervercel env pull)
Provider Routing
Configure how AI Gateway routes requests across providers:
const result = await generateText({
model: gateway('anthropic/claude-sonnet-4.6'),
prompt: 'Hello!',
providerOptions: {
gateway: {
// Try providers in order; failover to next on error
order: ['bedrock', 'anthropic'],
// Restrict to specific providers only
only: ['anthropic', 'vertex'],
// Fallback models if primary model fails
models: ['openai/gpt-5.4', 'google/gemini-3-flash'],
// Track usage per end-user
user: 'user-123',
// Tag for cost attribution and filtering
tags: ['feature:chat', 'env:production', 'team:growth'],
},
},
})
Routing Options
| Option | Purpose |
|---|---|
order |
Provider priority list; try first, failover to next |
only |
Restrict to specific providers |
models |
Fallback model list if primary model unavailable |
user |
End-user ID for usage tracking |
tags |
Labels for cost attribution and reporting |
Cache-Control Headers
AI
Установить ai-gateway в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл ai-gateway?
Vercel AI Gateway expert guidance. Use when configuring model routing, provider failover, cost tracking, or managing multiple AI providers through a unified API.
Как установить скилл ai-gateway?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ai-gateway запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic