Pydantic AI Gateway

Pydantic AI Gateway

**Pydantic AI Gateway**는 Pydantic Logfire로 관리되는 단일 키로 여러 AI 프로바이더에 접근하기 위한 통합 인터페이스예요. 내장 OpenTelemetry 옵저버빌리티, 실시간 비용 모니터링, 페일오버 관리, 그리고 Pydantic 스택의 다른 도구와의 네이티브 통합을 포함해요.

logfire.pydantic.dev에서 가입하세요.

질문이 있나요?

질문과 피드백은 Slack에서 연락 주세요.

출처: 문서

본문

문서 통합

Pydantic AI Gateway를 시작하는 데 도움이 되도록, Pydantic AI 문서의 일부 코드 예제는 표준 Pydantic AI 모델 문자열을 쓰는 "Direct to Provider API" 탭 옆에 "Via Pydantic AI Gateway" 탭을 포함해요. 둘 사이의 주요 차이는 Gateway를 사용할 때 모델 문자열이 gateway/ 프리픽스를 쓴다는 것이에요.

주요 기능

  • API 키 관리: 단일 Gateway 키로 여러 LLM 프로바이더에 접근하세요.
  • 비용 한도(Cost Limits): 프로젝트, 사용자, API 키 수준에서 일일·주간·월간 상한으로 지출 한도를 설정하세요.
  • BYOK와 관리형 프로바이더: LLM 프로바이더의 자체 API 키(BYOK)를 가져오거나, 플랫폼을 통해 추론 비용을 직접 지불하세요.
  • 멀티 프로바이더 지원: OpenAI, Anthropic, Google Vertex, Groq, AWS Bedrock의 모델에 접근하세요. 추가 프로바이더가 곧 제공될 예정이에요.
  • Gateway 엔드포인트: gateway 엔드포인트를 구성해 같은 모델을 서빙하는 프로바이더 사이를 페일오버하거나, 가중치로 트래픽을 부하 분산하세요.
  • 백엔드 옵저버빌리티: Pydantic Logfire 또는 어떤 OpenTelemetry 백엔드로든 모든 요청을 기록하세요(곧 제공 예정).
  • 제로 변환(Zero translation): 모든 것을 하나의 공통 스키마로 변환하는 전통적인 AI 게이트웨이와 달리, Pydantic AI Gateway는 요청이 각 프로바이더의 네이티브 형식으로 직접 흐르게 해요. 이것은 새 모델 기능이 릴리스되자마자 즉시 접근할 수 있게 해줘요.
  • 엔터프라이즈 준비: Logfire의 엔터프라이즈 기능(SSO, 커스텀 역할·권한 포함)을 상속해요.
from pydantic_ai import Agent

agent = Agent('gateway/openai:gpt-5.2')

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.
"""

빠른 시작

계정을 설정하고 Pydantic AI Gateway 자격증명으로 앱을 실행하세요.

계정 만들기

  1. logfire.pydantic.dev에서 가입
  2. 리전을 선택하고 계정 생성
  3. 조직의 설정에서 Gateway 활성화

Gateway API 키 만들기

Logfire에서 조직의 Gateway 설정으로 가서 API 키를 만드세요.

사용법

위 지시대로 계정을 설정한 후에는 Pydantic AI Gateway로 AI 모델 요청을 할 수 있어요. 아래 코드 스니펫은 다양한 프레임워크와 SDK에서 Pydantic AI Gateway를 사용하는 방법을 보여줘요.

다른 모델을 쓰려면 모델 문자열 gateway/<api_format>:<model_name>을 지원되는 프로바이더가 제공하는 다른 모델로 바꾸세요.

사용할 수 있는 프로바이더와 모델 예시:

프로바이더 API 형식 모델 예시
OpenAI openai gateway/openai:gpt-5.2
Anthropic anthropic gateway/anthropic:claude-sonnet-4-6
Google Cloud (구 Vertex AI) google-cloud gateway/google-cloud:gemini-3-flash-preview
Groq groq gateway/groq:openai/gpt-oss-120b
AWS Bedrock bedrock gateway/bedrock:amazon.nova-micro-v1:0

이미지 생성gateway/google:<model>로 게이트웨이를 통과하는데, Google Cloud에서 Gemini 이미지 모델을 서빙해요.

Pydantic AI

시작하기 전에 pydantic-ai 버전 1.16 이상인지 확인하세요. 최신 버전으로 업데이트하려면:

uv sync -P pydantic-ai
pip install -U pydantic-ai

PYDANTIC_AI_GATEWAY_API_KEY 환경 변수를 Gateway API 키로 설정하세요:

export PYDANTIC_AI_GATEWAY_API_KEY="pylf_v..."

아래 코드 스니펫처럼 같은 API 키로 여러 모델에 접근할 수 있어요.

from pydantic_ai import Agent

agent = Agent('gateway/openai:gpt-5.2')

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.
"""

API 키 직접 전달

gateway_provider를 사용해 API 키를 직접 전달하세요:

from 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-5.2', 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.
"""

다른 업스트림 프로바이더 사용

대체 프로바이더나 gateway 엔드포인트를 쓰려면 route 매개변수로 지정할 수 있어요:

from 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-5.2', 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.
"""

Claude Code

시작하기 전에 /logout으로 Claude Code에서 로그아웃하세요.

Logfire 리전에 맞는 base URL로 gateway 자격증명을 환경 변수로 설정하세요:

export ANTHROPIC_BASE_URL="https://gateway-us.pydantic.dev/proxy/anthropic"
export ANTHROPIC_AUTH_TOKEN="YOUR_GATEWAY_API_KEY"
export ANTHROPIC_BASE_URL="https://gateway-eu.pydantic.dev/proxy/anthropic"
export ANTHROPIC_AUTH_TOKEN="YOUR_GATEWAY_API_KEY"

YOUR_GATEWAY_API_KEY를 Logfire 조직 Gateway 설정의 API 키로 바꾸세요.

claude를 입력해 Claude Code를 시작하세요. 이제 모든 요청이 Pydantic AI Gateway를 통해 라우팅돼요.

Codex

Codex는 OpenAI Responses API를 사용하므로 Gateway의 openai-responses 라우트를 써야 해요.

gateway API 키를 환경 변수로 설정하세요:

export PYDANTIC_AI_GATEWAY_API_KEY="YOUR_GATEWAY_API_KEY"

그런 다음 Logfire 리전에 맞는 base URL로 ~/.codex/config.toml에 다음 구성을 추가하세요:

model = "gpt-5.4"
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"
model = "gpt-5.4"
model_provider = "pydantic_gateway"

[model_providers.pydantic_gateway]
name = "Pydantic AI Gateway"
base_url = "https://gateway-eu.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"

Codex에서 커스텀 프로바이더를 구성하는 자세한 내용은 Codex 커스텀 모델 프로바이더 문서Codex 구성 참조를 참고하세요.

이미 ~/.codex/config.toml이 있다면 전체 파일을 바꾸는 대신 [model_providers.pydantic_gateway] 블록을 추가하고 model_provider를 업데이트하세요. gpt-5.4를 Codex가 쓰길 원하는 OpenAI Responses 모델로 바꾸세요.

codex를 입력해 Codex를 시작하세요. 이제 모든 요청이 Pydantic AI Gateway를 통해 라우팅돼요.

SDK

OpenAI SDK

Logfire 리전(gateway-us 또는 gateway-eu)에 맞는 base URL을 사용하세요.

import openai

client = openai.Client(
    base_url='https://gateway-us.pydantic.dev/proxy/chat/',
    api_key='pylf_v...',
)

response = client.chat.completions.create(
    model='gpt-5.2',
    messages=[{'role': 'user', 'content': 'Hello world'}],
)
print(response.choices[0].message.content)
#> Hello user
import openai

client = openai.Client(
    base_url='https://gateway-eu.pydantic.dev/proxy/chat/',
    api_key='pylf_v...',
)

response = client.chat.completions.create(
    model='gpt-5.2',
    messages=[{'role': 'user', 'content': 'Hello world'}],
)
print(response.choices[0].message.content)
#> Hello user

Anthropic SDK

Logfire 리전(gateway-us 또는 gateway-eu)에 맞는 base URL을 사용하세요.

import 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-4-5',
    messages=[{'role': 'user', 'content': 'Hello world'}],
)
print(response.content[0].text)
#> Hello user
import anthropic

client = anthropic.Anthropic(
    base_url='https://gateway-eu.pydantic.dev/proxy/anthropic/',
    auth_token='pylf_v...',
)

response = client.messages.create(
    max_tokens=1000,
    model='claude-sonnet-4-5',
    messages=[{'role': 'user', 'content': 'Hello world'}],
)
print(response.content[0].text)
#> Hello user

Vercel AI SDK

Vercel AI SDK는 각 프로바이더의 baseURL을 매칭되는 프록시 경로(예: /proxy/openai 또는 /proxy/anthropic)로 가리켜 Gateway를 통해 라우팅할 수 있어요. Logfire 리전(gateway-us 또는 gateway-eu)에 맞는 base URL을 사용하세요.

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-5.2"),
    prompt: "what color is the sky? reply concisely",
  });
  console.log("openai:", openaiResult.text);
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
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-eu.pydantic.dev/proxy/openai",
});

async function main() {
  const openaiResult = await generateText({
    model: openai("gpt-5.2"),
    prompt: "what color is the sky? reply concisely",
  });
  console.log("openai:", openaiResult.text);
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

Gateway 엔드포인트

gateway 엔드포인트는 단일 슬러그 아래 하나 이상의 프로바이더에 걸쳐 요청을 라우팅해요. 각 배정된 프로바이더는 우선순위(priority), 가중치(weight), 활성(active) 플래그를 가지며, 이 세 값이 함께 단일 엔드포인트가 두 가지 다른 라우팅 전략을 표현하게 해줘요:

  • 페일오버 / 폴백: 프로바이더마다 다른 우선순위를 배정하세요. Gateway는 항상 가장 높은 우선순위의 활성 프로바이더를 먼저 시도하고, 더 높은 것이 사용 불가능할 때(예: 다운, 레이트 제한, 오류 반환)만 낮은 우선순위 프로바이더로 내려가요.
  • 부하 분산: 둘 이상의 프로바이더에 같은 우선순위를 배정하고 각각 가중치를 주세요. Gateway는 그 가중치에 비례해 트래픽을 그 프로바이더들에 나눠요.

두 전략은 합성돼요. 예를 들어, 70/30으로 부하 분산되는 두 프로바이더의 최상위 우선순위 티어와, 최상위 티어 프로바이더 둘 다 실패할 때만 트래픽을 받는 두 번째 우선순위 티어를 가질 수 있어요.

gateway 엔드포인트 만들기

gateway 엔드포인트는 Logfire의 조직 Gateway 설정에서 관리돼요:

  1. Gateway -> Endpoints를 열고 New Endpoint를 클릭하세요.
  2. 엔드포인트에 슬러그(예: anthropic-routing)와 선택적 description을 주세요.
  3. 엔드포인트의 Providers 페이지를 열고 프로바이더를 하나 이상 추가하세요. 각 프로바이더에 설정할 것:
    • Priority — 높은 값이 먼저 시도돼요. 페일오버를 위해 프로바이더마다 다른 우선순위를 사용하세요.
    • Weight — 같은 우선순위를 공유하는 프로바이더 사이에 사용되는 부하 분산 가중치.
    • Active — 비활성 프로바이더는 라우팅 중에 건너뛰어져요.

gateway 엔드포인트 사용

route 매개변수(엔드포인트의 슬러그)로 Gateway 프로바이더를 엔드포인트에 가리키세요:

from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel
from pydantic_ai.providers.gateway import gateway_provider

provider = gateway_provider(
    'anthropic',
    api_key='pylf_v...',
    route='anthropic-routing',  # (1)
)
model = AnthropicModel('claude-sonnet-4-6', 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.
"""

(Logfire에서 만든 gateway 엔드포인트의 슬러그.)

문제 해결

지출 산출 불가

Gateway는 지출 인사이트를 제공하고 지출 한도를 시행하기 위해 요청의 비용을 알아야 해요.

각 프로바이더는 설정에 Require pricing data 토글을 가져요. 활성화(기본)되면 게이트웨이는 가격 데이터가 없는 모델에 대한 요청을 업스트림으로 전달하기 전에 거부해요. 비활성화하면 그 요청은 통과되지만 비용이 추적되지 않고 지출 한도에 세지 않아요.

거부 응답은 프로바이더 타입에 따라 달라요:

  • 내장 프로바이더(Pydantic 관리): 404와 함께 우리가 모델을 추가할 수 있도록 Slack에서 알려 달라는 메시지.
  • 커스텀 프로바이더(당신의 자체 API 키): 가격 데이터가 필요하다는 400과, 그래도 요청을 통과시키려면 토글을 비활성화하라는 힌트.

우리는 더 많은 프로바이더와 모델을 지원하기 위해 적극적으로 작업 중이에요. 지원되길 원하는 특정 프로바이더나 모델이 있다면 Slack에서 알려주거나 genai-prices에 이슈 열기를 해 주세요.

더 알아보기 (Learn more)