【No.152】Python × PydanticAI 実務パック — 型付き Agent 出力
Python AI の出力が dict 化・JSON パース地獄になりがちな問題に、PydanticAI は Agent + BaseModel で structured output を固定します。Agent(deps_type, output_type)、@agent.tool と RunContext で DI、result.output は Pydantic オブジェクトそのもの。
FastAPI と同じ DI の感覚で書けます。
SupportResponse テンプレを Snippets に保存するのが今週の一手です。
この記事に含まれるもの
PydanticAI の位置づけ — JSON パース不要の structured output
SupportResponse テンプレ — BaseModel + Agent コピペ用
@agent.tool + RunContext DI メモ — deps_type 設定
失敗時フォールバックチェック — バリデーションエラー時
7日 型付き Agent チェックリスト — 完了定義付き
この記事で持ち帰れること
pip install pydantic-ai 後、Agent に output_type=BaseModel サブクラスを渡すと result.output が型付きオブジェクトになります。deps_type で依存注入、@agent.tool と RunContext で FastAPI 系 DI。JSON パース地獄を避ける最短ルートです。
今週試す1手: SupportResponse テンプレを Snippets に保存する。
PydanticAI — Agent + BaseModel で structured output
Pydantic AI 公式(ai.pydantic.dev / pydantic.dev)によると、Agent + Pydantic モデルで structured output。FastAPI 系 DI。Python 3.10+。Agent(deps_type, output_type)、@agent.tool と RunContext で DI。result.output は Pydantic オブジェクトそのものです。
例えば、カスタマーサポート Bot が返答とエスカレーション要否を毎回 JSON 文字列で返し、パース失敗が起きる場合、output_type=SupportResponse のように BaseModel で固定するとバリデーションが SDK 側で行われます。FastAPI 経験者なら deps_type に DB セッションや設定オブジェクトを載せ、@agent.tool 内で RunContext 経由参照する流れが馴染みやすいです。一次情報は Pydantic 公式 docs を正としてください。
SDK の要点(Pydantic 公式ベース)
要件: Python 3.10+
インストール: pip install pydantic-ai
定義: Agent(deps_type, output_type)
ツール: @agent.tool + RunContext
出力: result.output が Pydantic オブジェクト
感覚: FastAPI と同じ DI
JSON パース不要 — 型付き Agent の3要素
型付き Agent の3要素
output_type — BaseModel サブクラスで出力スキーマ固定
deps_type — 依存(DB クライアント等)を型で注入
@agent.tool — RunContext 経由で deps にアクセス
影響1 — Python エンジニア: LLM 出力の dict 化を構造体に固定
影響2 — FastAPI 利用者: DI 感覚がそのまま使える
影響3 — 本番 Agent: バリデーション失敗を早期検知
よくある誤解と切り返し
誤解1: 「Pydantic v2 だけあれば同じ」→ 切り返し: PydanticAI は Agent ループと tool DI 込み。
誤解2: 「output は dict で十分」→ 切り返し: result.output を BaseModel に固定するとパース不要。
誤解3: 「deps は global でよい」→ 切り返し: deps_type + RunContext が公式パターン。
SupportResponse テンプレ — BaseModel + Agent
括弧を埋めて Snippets に保存する骨格です(ラベル形式)。
SupportResponse テンプレ
インストール: pip install pydantic-ai
import: Agent, RunContext(公式 docs 参照), BaseModel from pydantic
出力モデル SupportResponse:
reply: str — ユーザー向け返答文
needs_escalation: bool — 人間エスカレーション要否
category: str — 問い合わせ分類(例: billing / technical)
依存 Deps(任意):
deps_type 名: Deps
フィールド例: user_id: str
Agent 定義:
agent = Agent(model='(モデル名)', deps_type=Deps, output_type=SupportResponse, system_prompt='(1行)')
@agent.tool 例:
関数名: fetch_user_context
引数: ctx: RunContext[Deps]
本文: ctx.deps.user_id を参照(1行処理)
実行:
result = agent.run_sync('(ユーザー問い合わせ1行)', deps=Deps(user_id='(id)'))
取得: result.output.reply, result.output.needs_escalation
期待: result.output が SupportResponse 型、JSON 手パースなし
完了定義: run_sync 1回で result.output.category が str として取れる。
バリデーション失敗時チェック — フォールバック1枚
フォールバックチェック
症状: ValidationError / output 型不一致
確認1: output_type が BaseModel サブクラスか
確認2: system_prompt に出力フィールド名を明示したか
確認3: モデル名が公式対応一覧にあるか
フォールバック: プロンプトに JSON 例1行追加 → 再 run
ログ: 失敗入力1行、修正後 output 1行をメモ
本番: 3回失敗で人間エスカレーション — needs_escalation=True 固定
完了定義: 意図的に曖昧入力1件でフォールバック手順を1回試した。
7日 型付き Agent チェックリスト — SupportResponse から拡張
Day 1 — install
pip install pydantic-ai、Python 3.10+ 確認
完了定義: import 成功
Day 2 — BaseModel
SupportResponse 3フィールド定義
完了定義: モデルが1ファイルにある
Day 3 — Agent 最小
output_type=SupportResponse の Agent 1本、tool なしで run
完了定義: result.output が3フィールド取れる
Day 4 — deps + tool
deps_type と @agent.tool 1本追加
完了定義: RunContext 経由で deps 参照成功
Day 5 — Snippets
SupportResponse テンプレを Snippets 保存
完了定義: エディタ登録済み
Day 6 — フォールバック
バリデーション失敗時チェックを1回実行
完了定義: フォールバックメモ1行
Day 7 — README
実行手順と output 型説明を README に3行
完了定義: README に pip install と output_type 記載
✅ 今日は SupportResponse の3フィールドだけ定義して保存する。
ペルソナ別の使い方
Python エンジニア: 既存 dict パース Agent を output_type 固定に置換。SupportResponse から開始。
FastAPI 開発者: deps_type を DB セッション等に合わせ、@agent.tool で RunContext DI。
受託エンジニア: クライアント向け「structured output 仕様書」として SupportResponse テンプレを提出。
参照
Pydantic AI 公式。Agent + Pydantic モデルで structured output。FastAPI 系 DI。Python 3.10+。
免責
本記事は Pydantic 公式情報ベースの二次解説です。API 形状・対応モデルは公式 docs を正としてください。テンプレは案件の機密・契約に合わせて改変してください。娯楽・要約向けであり、本番利用判断は自己責任で行ってください。
江戸テック瓦版 — AI 時代の生存戦略
