Pydantic AIでPythonでAIエージェントを構築する
Pydantic AIフレームワークを使用して、構造化出力、カスタムツール、依存性注入、Web検索や拡張推論などの組み込み機能を備えた本番環境対応のAIエージェントをPythonで構築する方法を学びます。
このチュートリアルでは、Pydantic AIを使用してPythonで本番環境対応のAIエージェントを構築する方法を解説します。Pydantic AIは、強い型付け、検証、明確な構造をエージェント開発にもたらし、信頼性と保守性を向上させます。
なぜPydantic AIか?
LLMを直接呼び出すと応答は文字列であり、構造化オブジェクトへの解析が必要でエラーが発生しやすいです。Pydantic AIは以下の方法で解決します:型安全な構造化出力(BaseModelを定義し、フレームワークが自動検証・リトライ);関数ツール(Python関数を登録し、LLMが型ヒントとdocstringから呼び出しを判断);依存性注入(RunContextを介して実行時依存性を注入し、グローバル状態を回避)。
前提条件
Python 3.9+、Pydantic BaseModelと型ヒントの知識、LLMプロンプトの基本理解、サポートプロバイダのAPIキー(本チュートリアルではopenai:gpt-4o-miniを使用)。
インストール
仮想環境を作成しインストール:
python -m venv venv
source venv/bin/activate
pip install pydantic-aiAPIキーを設定(例:export OPENAI_API_KEY=...)。
最初のエージェント
数行で作成可能:
from pydantic_ai import Agent
agent = Agent(
"openai:gpt-4o-mini",
instructions="You are a concise assistant."
)
result = agent.run_sync("What is a large language model?")
print(result.output)モデル文字列は"provider:model-name"形式。
構造化検証出力
出力モデルを定義:
from pydantic import BaseModel, Field
class JobPosting(BaseModel):
job_title: str
company_name: str
required_skills: list[str]
seniority_level: str
is_remote: boolエージェント作成時にoutput_typeを設定:
agent = Agent(
"openai:gpt-4o-mini",
output_type=JobPosting,
instructions="Extract structured job posting information."
)
result = agent.run_sync("...")
posting = result.outputフレームワークが自動検証し、エラー時にリトライ。
ツールの追加
ツールで外部データにアクセス。例:栄養データベース:
NUTRITION_DB = {"chicken breast": {...}, ...}
class MealSummary(BaseModel):
total_calories: int
total_protein_g: float
# ...
@agent.tool_plain
def get_ingredient_nutrition(ingredient: str) -> str:
"""100gあたりの栄養情報を検索"""
data = NUTRITION_DB.get(ingredient.lower().strip())
if data:
return json.dumps({"ingredient": ingredient, **data})
return f"Not found."エージェントがツールを呼び出し、構造化されたMealSummaryを返す。
依存性注入
データソースをサービスラスにラップ:
@dataclass
class NutritionService:
database: dict
def lookup(self, ingredient: str) -> dict | None:
return self.database.get(ingredient.lower().strip())エージェントのdeps_typeを宣言し、ツールでRunContextを使用:
agent = Agent(
"openai:gpt-4o-mini",
output_type=MealSummary,
deps_type=NutritionService,
instructions="Use tools to compute meal totals."
)
@agent.tool
def get_ingredient_nutrition(ctx: RunContext[NutritionService], ingredient: str) -> str:
data = ctx.deps.lookup(ingredient)
return json.dumps({"ingredient": ingredient, **data}) if data else "Not found."実行時にNutritionServiceインスタンスを渡し、テスト時はモックに置き換え可能。
組み込み機能
Web検索や拡張推論も利用可能。このチュートリアルで実用的なエージェント構築の基礎を習得できます。完全なColabノートブックはGitHubで入手可能。