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

Pydantic AI Gateway | Pydantic Docs

https://pydantic.dev/docs/ai/overview/gateway/

最近抓取:2026-12-03 05:47:38(北京时间)

最近内容变化:2026-12-03 05:47:38(北京时间)

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

访问原网页

页面简介

Pydantic AI Gateway: one API key for OpenAI, Anthropic, Google, Groq and Bedrock models, with spending limits, failover, load balancing and observability.

正文摘录

Pydantic AI Gateway Pydantic AI Gateway is a unified interface for accessing multiple AI providers with a single key, managed through Pydantic Logfire. Features include built-in OpenTelemetry observability, real-time cost monitoring, failover management, and native integration with the other tools in the Pydantic stack. Sign up at logfire.pydantic.dev. Documentation Integration To help you get started with Pydantic AI Gateway, some code examples on the Pydantic AI documentation include a “Via Pydantic AI Gateway” tab, alongside a “Direct to Provider API” tab with the standard Pydantic AI model string. The main difference between them is that when using Gateway, model strings use the gateway/ prefix. Key features API key management: Access multiple LLM providers with a single Gateway key. Cost Limits: Set spending limits at project, user, and API key levels with daily, weekly, and monthly caps. BYOK and managed providers: Bring your own API keys (BYOK) from LLM providers, or pay for inference directly through the platform. Multi-provider support: Access models from OpenAI, Anthropic, Google Vertex, Groq, and AWS Bedrock. More providers coming soon. Gateway endpoints: Configure gateway endpoints to fail over between providers serving the same model, or load-balance traffic across them by weight. Backend observability: Log every request through Pydantic Logfire or any OpenTelemetry backend (coming soon). Zero translation: Unlike traditional AI gateways that translate everything to one common schema, Pydantic AI Gateway allows requests to flow through directly in each provider’s native format. This gives you immediate access to new model features as soon as they are released. Enterprise ready: Inherits Logfire’s enterprise features, including SSO, custom roles and permissions. Cloud or self-hosted: Available on the Logfire Cloud plans and on self-hosted Logfire; see the Logfire AI Gateway docs. hello_world.pyfrom pydantic_ai import Agent agent = Agent('gateway/openai:gpt-6.1-sol') result = agent.run_sync('Where does "hello world" come from?') print(result.output) """ The first known use of "hello, world" was in a 1974 textbook about the C programming language. """ Quick Start Set up your account and run your app with Pydantic AI Gateway credentials. Create an account Sign up at logfire.pydantic.dev Choose a region and create an account. Activate the Gateway in your organization’s settings. Create Gateway API keys Go to your organization’s Gateway settings in Logfire and create an API key. Usage After setting up your account with the instructions above, you will be able to make an AI model request with the Pydantic AI Gateway. The code snippets below show how you can use Pydantic AI Gateway with different frameworks and SDKs. To use different models, change the model string gateway/<api_format>:<model_name> to other models offered by the supported providers. Examples of providers and models that can be used are: ProviderAPI FormatExample ModelOpenAIopenaigateway/openai:gpt-6.1-solAnthropicanthropicgateway/anthropic:claude-sonnet-5-5Google Cloud (formerly Vertex AI)google-cloud, googlegateway/google-cloud:gemini-4-hydrogenGroqgroqgateway/groq:openai/gpt-oss-120bAWS Bedrockbedrockgateway/bedrock:amazon.nova-micro-v1:0Doubleworddoubleword (OpenAI Chat Completions)gateway/doubleword:deepseek-ai/DeepSeek-V4.1-Flash Doubleword has no provider class of its own, so it uses the OpenAI Chat Completions client on the doubleword route. Other Gateway routes without a provider class can’t be used as model strings yet. Build the model directly instead: OpenAIChatModel('<model>', provider=gateway_provider('openai-chat', route='<route>')). Image generation routes through the gateway as gateway/google:<model>, which serves the Gemini image models over Google Cloud. Pydantic AI Before you start, make sure you are on version 1.16 or later of pydantic-ai. To update to the latest version run: uv pip Terminaluv sync -P pydantic-ai Set the PYDANTIC_AI_GATEWAY_API_KEY environment variable to your Gateway API key: Terminalexport PYDANTIC_AI_GATEWAY_API_KEY="pylf_v..." You can access multiple models with the same API key, as shown in the code snippet below. hello_world.pyfrom pydantic_ai import Agent agent = Agent('gateway/openai:gpt-6.1-sol') result = agent.run_sync('Where does "hello world" come from?') print(result.output) """ The first known use of "hello, world" was in a 1974 textbook about the C programming language. """ Passing API Key directly Pass your API key directly using the gateway_provider: passing_api_key.pyfrom pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.gateway import gateway_provider provider = gateway_provider('openai', api_key='pylf_v...') model = OpenAIChatModel('gpt-6.1-sol', provider=provider) agent = Agent(model) result = agent.run_sync('Where does "hello world" come from?') print(result.output) """ The first known use of "hello, world" was in a 1974 textbook about the C programming language. """ Using a different upstream provider To use an alternate provider or gateway endpoint, you can specify it in the route parameter: routing_via_provider.pyfrom pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.gateway import gateway_provider provider = gateway_provider( 'openai', api_key='pylf_v...', route='builtin-openai' ) model = OpenAIChatModel('gpt-6.1-sol', provider=provider) agent = Agent(model) result = agent.run_sync('Where does "hello world" come from?') print(result.output) """ The first known use of "hello, world" was in a 1974 textbook about the C programming language. """ Request cost RequestUsage.cost (summed into RunUsage.cost) uses the cost the gateway reports for a request instead of the genai-prices estimate, so cost_limit and your own cost tracking match what the gateway charged, including a free response-cache hit. Google and Bedrock read the gateway’s cost from a response header on non-streamed requests, and from the stream itself on streamed requests; when a gateway doesn’t send the cost yet, they keep the genai-prices estimate. The cost() methods on responses and embedding results always return the genai-prices estimate. Claude Code Before you start, log out of Claude Code using /logout. Set your gateway credentials as environment variables, using the base URL that matches your Logfire region: US EU Terminalexport ANTHROPIC_BASE_URL="https://gateway-us.pydantic.dev/proxy/anthropic" export ANTHROPIC_AUTH_TOKEN="YOUR_GATEWAY_API_KEY" Replace YOUR_GATEWAY_API_KEY with the API key from your Logfire organization’s Gateway settings. Launch Claude Code by typing claude. All requests will now route through the Pydantic AI Gateway. Codex Codex uses the OpenAI Responses API, so it should use the Gateway’s openai-responses route. Set your gateway API key as an environment variable: Terminalexport PYDANTIC_AI_GATEWAY_API_KEY="YOUR_GATEWAY_API_KEY" Then add the following configuration to ~/.codex/config.toml, using the base URL that matches your Logfire region: US EU model = "gpt-6.1-sol" model_provider = "pydantic_gateway" [model_providers.pydantic_gateway] name = "Pydantic AI Gateway" base_url = "https://gateway-us.pydantic.dev/proxy/openai-responses" env_key = "PYDANTIC_AI_GATEWAY_API_KEY" env_key_instructions = "Create a Gateway API key in your Logfire organization's Gateway settings." wire_api = "responses" For more details on configuring custom providers in Codex, see the Codex custom model providers docs and the Codex configuration reference. If you already have a ~/.codex/config.toml, add the [model_providers.pydantic_gateway] block and update model_provider instead of replacing the whole file. Replace gpt-6.1-sol with whichever OpenAI Responses model you want Codex to use. Launch Codex by typing codex. All requests will now route through the Pydantic AI Gateway. SDKs OpenAI SDK Use the base URL that matches your Logfire region (gateway-us or gateway-eu). US EU openai_sdk.pyimport openai client = openai.Client( base_url='https://gateway-us.pydantic.dev/proxy/chat/', api_key='pylf_v...', ) response = client.chat.completions.create( model='gpt-6.1-sol', messages=[{'role': 'user', 'content': 'Hello world'}], ) print(response.choices[0].message.content) #> Hello user Anthropic SDK Use the base URL that matches your Logfire region (gateway-us or gateway-eu). US EU anthropic_sdk.pyimport anthropic client = anthropic.Anthropic( base_url='https://gateway-us.pydantic.dev/proxy/anthropic/', auth_token='pylf_v...', ) response = client.messages.create( max_tokens=1000, model='claude-sonnet-5-5', messages=[{'role': 'user', 'content': 'Hello world'}], ) content = response.content[0] assert isinstance(content, anthropic.types.TextBlock) print(content.text) #> Hello user Vercel AI SDK The Vercel AI SDK can route through the Gateway by pointing each provider’s baseURL at the matching proxy path (e.g. /proxy/openai or /proxy/anthropic). Use the base URL that matches your Logfire region (gateway-us or gateway-eu). US EU import { createOpenAI } from "@ai-sdk/openai"; import { generateText } from "ai"; const apiKey = process.env.PYDANTIC_AI_GATEWAY_API_KEY; if (!apiKey) throw new Error("set PYDANTIC_AI_GATEWAY_API_KEY"); const openai = createOpenAI({ apiKey, baseURL: "https://gateway-us.pydantic.dev/proxy/openai", }); async function main() { const openaiResult = await generateText({ model: openai("gpt-6.1-sol"), prompt: "what color is the sky? reply concisely", }); console.log("openai:", openaiResult.text); } main().catch((err) => { console.error(err); process.exit(1); }); Gateway endpoints A gateway endpoint routes requests across one or more providers under a single slug. Each assigned provider has a priority, a weight, and an active flag, and those three values together let a single endpoint express two different routing strategies: Failover / fallback: Assign providers different priorities. The Gateway always