翻篇收录说明
翻篇网页快照

AI Gateway Provider Routing and Fallbacks

https://vercel.com/docs/ai-gateway/models-and-providers/provider-options

最近抓取:2026-12-03 20:44:07(北京时间)

最近内容变化:2026-12-03 20:44:07(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Configure provider routing, ordering, and fallback behavior in Vercel AI Gateway to control latency, cost, and availability across providers.

正文摘录

Copy pageCopy pageAI Gateway Provider Routing and FallbacksCopy pageCopy pageAI Gateway can route your AI model requests across multiple AI providers. Each provider offers different models, pricing, and performance characteristics. By default, Vercel AI Gateway dynamically chooses the default providers to give you the best experience based on a combination of recent uptime and latency. Use providerOptions.gateway to control provider order and fallback behavior. If you want to customize individual AI model provider settings rather than general AI Gateway behavior, please refer to the model-specific provider options in the AI SDK documentation. Provider filtering, ordering, and sorting Default routing needs no configuration. AI Gateway orders providers by each model's default priority, adjusted for recent provider health, and fails over to other providers serving the same model when one is unavailable. To prefer specific providers without giving up that failover, set order in providerOptions.gateway. AI Gateway tries the listed providers first and can still fall back to others: providerOptions: { gateway: { order: ['bedrock', 'anthropic'], // Try Bedrock first, then Anthropic }, }, only is a hard filter: AI Gateway routes only to the listed providers and never fails over outside the list. If none of the listed providers serve the model, or they are all unavailable or rate limited, the request fails instead of falling back. If your requirement is compliance rather than a specific provider, zero data retention, disallow prompt training, and regional inference express it directly while keeping every qualifying provider eligible. The team provider allowlist works like a team-wide only. You can also use sort to rank providers by a performance or cost metric. The gateway sorts providers by the chosen metric and tries them in that order: providerOptions: { gateway: { sort: 'cost', // Sort by cost, latency ('ttft'), or throughput ('tps') }, }, For full details, examples, and provider metadata output, see Provider Filtering, Ordering & Sorting. Provider headquarters Use headquarters to route only to providers whose parent company is headquartered in the countries you list, as ISO 3166-1 alpha-2 codes: providerOptions: { gateway: { headquarters: ['US', 'GB', 'DE', 'FR'], }, }, To exclude countries instead, prefix every code with !, as in ['!US']. A list can't mix the two. Providers without a headquarters country on record are always excluded. See Provider Headquarters for the full rules and how it combines with other options. Automatic caching You can use caching: 'auto' in providerOptions.gateway to let AI Gateway automatically apply the appropriate caching strategy based on the provider. This is useful for providers like Anthropic and MiniMax that require explicit cache markers. providerOptions: { gateway: { caching: 'auto', }, }, For full details, supported providers, and examples across all APIs, see Automatic Caching. Clients on the Responses API can also set these top-level request fields: cache_anchor_items pins a cache marker at a known-stable prefix position. See Cache anchor. cache_ttl selects a five-minute or one-hour cache lifetime. See Cache lifetime. These fields belong at the top level of the Responses API request, not inside providerOptions.gateway. Session affinity AI Gateway keeps a conversation on the provider that holds its prompt cache. Two options in providerOptions.gateway control this: sessionId groups related requests into one session. Use a stable, opaque value for each conversation or agent run. sessionAffinity turns the behavior on or off. The default is true. Set it to false to stop AI Gateway from pinning and reordering providers for a request. providerOptions: { gateway: { sessionId: 'session_123', sessionAffinity: true, }, }, You can also send the session ID in the x-session-id header. For the full lookup order, how AI Gateway fingerprints requests that have no session ID, and how it keeps caches warm across models, see Session affinity. Provider timeouts You can set per-provider timeouts to trigger fast failover when a provider is slow to respond. See the dedicated Provider Timeouts documentation. Model fallbacks String model fallbacks try backup models when the primary model fails or is unavailable. See Model Fallbacks for failure-based routing. Decision requests can also add one conditional object to providerOptions.gateway.models. It reruns a successful decision when a confidence, Boolean probability, or compound condition matches. AI Gateway rejects a conditional object with a 400 error on any other request type, and when the conditional object names the primary model itself. See Decision Fallbacks for the complete wire contract and provider-option behavior. Advanced configuration Combining AI Gateway provider options with provider-specific options You can combine AI Gateway provider options with provider-specific options. This allows you to control both the routing behavior and provider-specific settings in the same request: These examples use AI SDK 7 and the AI SDK for Python beta. Set AI_GATEWAY_API_KEY before running them. See API format differences for setup, request fields, and response handling. AI SDKChat CompletionsMessages APIResponses / OpenResponsesTypeScriptPython (beta)See the AI SDK Gateway provider-options reference for SDK configuration and usage.provider-options.tsimport { generateText } from 'ai'; const { text } = await generateText({ model: 'anthropic/claude-sonnet-5', prompt: 'Explain quantum computing in two sentences.', providerOptions: { gateway: { order: ['anthropic', 'bedrock'], }, anthropic: { thinking: { type: 'adaptive', }, }, }, }); console.log(text);provider-options_ai.pyimport asyncio import ai async def main(): model = ai.get_model("anthropic/claude-sonnet-5") messages = [ai.user_message("Explain quantum computing in two sentences.")] params = ai.InferenceRequestParams( extra_body={"providerOptions": {"gateway": {"order": ["anthropic", "bedrock"]}, "anthropic": {"thinking": {"type": "adaptive"}}}} ) async with ai.stream(model, messages, params=params) as stream: async for event in stream: if isinstance(event, ai.events.TextDelta): print(event.chunk, end="", flush=True) print() asyncio.run(main())TypeScriptPythoncURLprovider-options-chat.tsimport 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: 'Explain quantum computing in two sentences.', }, ], // AI Gateway extension fields are not included in the upstream SDK types. ...{ providerOptions: { gateway: { order: ['anthropic', 'bedrock'], }, anthropic: { thinking: { type: 'adaptive', }, }, }, }, }); console.log(response.choices[0]?.message.content);provider-options_chat.pyimport 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 quantum computing in two sentences."}], extra_body={"providerOptions": {"gateway": {"order": ["anthropic", "bedrock"]}, "anthropic": {"thinking": {"type": "adaptive"}}}}, ) print(response.choices[0].message.content)provider-options-chat.shcurl --fail-with-body https://ai-gateway.vercel.sh/v1/chat/completions \ -H "Authorization: Bearer $AI_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "anthropic/claude-sonnet-5", "messages": [ { "role": "user", "content": "Explain quantum computing in two sentences." } ], "providerOptions": { "anthropic": {"thinking": {"type": "adaptive"}}, "gateway": { "order": [ "anthropic", "bedrock" ] } } }'TypeScriptPythoncURLprovider-options-messages.tsimport 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: 'Explain quantum computing in two sentences.', }, ], max_tokens: 1024, ...{ providerOptions: { gateway: { order: ['anthropic', 'bedrock'], }, anthropic: { thinking: { type: 'adaptive', }, }, }, }, }); for (const block of response.content) { if (block.type === 'text') console.log(block.text); }provider-options_messages.pyimport os from anthropic import Anthropic client = Anthropic( api_key=os.environ["AI_GATEWAY_API_KEY"], base_url="https://ai-gateway.vercel.sh", ) response = client.messages.create( model="anthropic/claude-sonnet-5", messages=[{"role": "user", "content": "Explain quantum computing in two sentences."}], max_tokens=1024, extra_body={"providerOptions": {"gateway": {"order": ["anthropic", "bedrock"]}, "anthropic": {"thinking": {"type": "adaptive"}}}}, ) for block in response.content: if block.type == "text": print(block.text)provider-options-messages.shcurl --fail-with-body https://ai-gateway.vercel.sh/v1/messages \ -H "Authorization: Bearer $AI_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -H "anthropic-version: 2023-06-01" \ -d '{ "model": "anthropic/claude-sonnet-5", "messages": [ { "role": "user", "content": "Explain quantum computing in two sentences." } ], "max_tokens": 1024, "providerOptions": { "anthropic": {"thinking": {"type": "adaptive"}}, "gateway": { "order": [ "anthropic", "bedrock" ] } } }'TypeScriptPythoncURLprovider-options-responses.tsimport 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.responses.create({ model: 'anthropic/claude-sonnet-5', input: 'Explain quantum computing in two sentences.', ...{ providerOptions: { gateway: { order: ['anthropic', 'bedrock'], }, anthropic: { thinking: { type: 'adaptive', }, }, }, }, }); console.lo