結論: Pydantic AIは、PythonのデータバリデーションライブラリPydanticの作者Samuel Colvinが開発した「型安全AIエージェントFW」。FastAPIで人気のPydanticエコシステム親和性が高く、「型安全 × 構造化出力 × ストリーミング」を中核に設計されています。Mastra(TypeScript)に対するPython版の本命候補です。
この記事の要点:
- 要点1: Pydantic作者制作、FastAPIユーザーに馴染みやすいAPI設計
- 要点2: 構造化出力(structured output)を型注釈で定義、エージェントのレスポンス品質保証
- 要点3: マルチモデル対応(Anthropic/OpenAI/Gemini/Llama)、依存性注入パターン
Pydantic AI とは
2024年公開、2026年4月時点で v1.x 安定版。Python型システム + LLM + Pydantic を統合したFW。FastAPIライクな宣言的設計:
from pydantic_ai import Agent
from pydantic import BaseModel
class CustomerInfo(BaseModel):
name: str
age: int
is_premium: bool
agent = Agent(
"anthropic:claude-opus-4-7",
output_type=CustomerInfo, # ← 型で出力構造を定義
system_prompt="顧客情報を抽出してください",
)
result = agent.run_sync("田中太郎さん、35歳、プレミアム会員です")
print(result.data) # CustomerInfo(name='田中太郎', age=35, is_premium=True)
主要な特徴
1. 型安全な構造化出力
Pydanticモデルでエージェントの出力構造を定義。LLMのレスポンスを型保証:
class AnalysisResult(BaseModel):
summary: str
key_points: list[str]
confidence: float
class Config:
json_schema_extra = {
"example": {
"summary": "業績好調",
"key_points": ["売上+15%", "利益率改善"],
"confidence": 0.95,
}
}
agent = Agent(model="claude-opus-4-7", output_type=AnalysisResult)
result = agent.run_sync("Q1決算を分析")
# result.data は AnalysisResult として型保証
2. マルチモデル対応
| プロバイダ | モデル指定例 |
|---|---|
| Anthropic | anthropic:claude-opus-4-7 |
| OpenAI | openai:gpt-5.5 |
google:gemini-3.1-pro |
|
| Mistral | mistral:mistral-small-4 |
| Ollama | ollama:llama-4-maverick |
| Bedrock | bedrock:anthropic.claude-3-sonnet |
3. ツール統合(型安全)
from pydantic_ai import Agent, RunContext
class DBContext(BaseModel):
db_url: str
table: str
agent = Agent("claude-opus-4-7", deps_type=DBContext)
@agent.tool
async def query_db(ctx: RunContext[DBContext], query: str) -> list[dict]:
"""データベースをクエリして結果を返す"""
# ctx.deps.db_url を使ってDB操作
return [...]
result = await agent.run(
"顧客XXXの注文履歴を要約",
deps=DBContext(db_url="postgres://...", table="orders")
)
4. 依存性注入パターン
FastAPIライクな依存性注入で、ランタイム情報をエージェントに渡せる:
from fastapi import FastAPI, Depends
from pydantic_ai import Agent
app = FastAPI()
def get_db_url() -> str:
return "postgres://..."
@app.post("/ask")
async def ask_agent(question: str, db_url: str = Depends(get_db_url)):
agent = Agent("claude-opus-4-7", deps_type=str)
result = await agent.run(question, deps=db_url)
return {"answer": result.data}
5. ストリーミング対応
async def stream_response():
async with agent.run_stream("長い分析レポートを生成") as result:
async for text in result.stream():
print(text, end="", flush=True)
# 最終的な構造化データも取得
final = await result.get_data()
マルチエージェント実装例
from pydantic_ai import Agent
from pydantic import BaseModel
class ResearchResult(BaseModel):
sources: list[str]
summary: str
class ArticleDraft(BaseModel):
title: str
sections: list[str]
researcher = Agent("claude-opus-4-7", output_type=ResearchResult)
writer = Agent("gpt-5.5", output_type=ArticleDraft)
# 連携実行
research = await researcher.run("AI業界トレンド2026")
draft = await writer.run(
f"以下のリサーチをもとに記事構成: {research.data.summary}"
)
print(draft.data)
競合FWとの比較
| 特徴 | Pydantic AI | LangGraph | Mastra (TS) |
|---|---|---|---|
| 対応言語 | Python | Python | TypeScript |
| 設計思想 | 型安全+FastAPI流 | グラフ+永続化 | 型安全+本番志向 |
| 構造化出力 | 標準(Pydantic) | 対応 | 対応(Zod) |
| 学習コスト | 低(FastAPI経験者) | 高 | 中 |
| 本番ランタイム | Pydantic Logfire | LangGraph Cloud | Mastra Cloud |
| エコシステム | FastAPI / SQLAlchemy | LangChain | Vercel/Cloudflare |
Pydantic Logfire統合(観測ツール)
Pydantic AIは同じくPydantic製のLogfireと統合:
import logfire
from pydantic_ai import Agent
logfire.configure()
agent = Agent("claude-opus-4-7", output_type=AnalysisResult)
result = agent.run_sync("分析してください")
# 自動的にLogfireにトレース送信
レイテンシ・コスト・エラー・出力品質をリアルタイム可視化。
採用が向くシーン3つ
1. FastAPI / Pydanticエコシステム企業
既にPydanticでバリデーション、FastAPIでAPI実装している企業。学習コスト最小。
2. 構造化出力が品質要件
「JSONスキーマ通りの出力が絶対必要」な金融・医療・法務系。型保証で品質担保。
3. PythonエンジニアのチームでマルチLLM運用
Claude/GPT/Gemini を切り替えながら使う研究・実験・スタートアップ。
セットアップ(5分で動く)
# 1. インストール
pip install pydantic-ai
# 2. 環境変数
export ANTHROPIC_API_KEY="sk-ant-..."
# 3. 最小エージェント
from pydantic_ai import Agent
agent = Agent(
"anthropic:claude-opus-4-7",
system_prompt="あなたはPythonエキスパートです",
)
result = agent.run_sync("リスト内包表記を解説")
print(result.data)
失敗パターン3つ
- ❌ Pydanticの型を複雑にしすぎ → LLMが従えない、シンプル設計
- ❌ 巨大エージェントを1つで解決 → 役割分担で複数エージェント連携
- ❌ 構造化出力に頼りすぎ → 一部用途では自由形式の方が品質高い
まとめ:Python+型安全環境ではトップ候補
Pydantic AIは「FastAPI流のシンプルさ」と「型安全」を両立する稀有なFW。Pythonエンジニアなら学習コスト最小、品質保証も担保できる本命候補です。
Pydantic AI導入を本格化したい方へ
UravationではPython AIエージェント設計コンサルを実施。実装支援もご相談ください。
出典
関連記事: