mcpField
P
pydantic-ai-agent-creation

pydantic-ai-agent-creation

github.com/existential-birdsエージェントワークフロー85218 回インストール11 週間前に更新
リポジトリ

pydantic-ai-agent-creation について

PydanticAI で Agent を構築する開発者向けのリファレンスです。モデル選択、構造化出力、依存関係、実行方法に加え、本番利用前の確認手順を扱います。

主な機能

  1. 01モデルと Agent の動作設定
  2. 02型付き構造化出力の検証
  3. 03型付き依存関係の注入
  4. 04同期・非同期・ストリーム実行
  5. 05本番前の検証手順

活用シーン

  1. 01検証済みの Pydantic データを返す Agent の構築
  2. 02型付き依存関係によるアプリサービスの受け渡し
  3. 03Agent の実行方法の選択
  4. 04本番利用前の Agent の確認

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/existential-birds/beagle --skill pydantic-ai-agent-creation

インストール後、Claude Code で/pydantic-ai-agent-creationを入力して読み込まれたか確認します。

詳細

PydanticAI エージェントの作成

クイックスタート

from pydantic_ai import Agent

# Minimal agent (text output)
agent = Agent('openai:gpt-4o')
result = agent.run_sync('Hello!')
print(result.output)  # str

モデルの選択

モデル文字列は provider:model-name 形式です。

# OpenAI
agent = Agent('openai:gpt-4o')
agent = Agent('openai:gpt-4o-mini')

# Anthropic
agent = Agent('anthropic:claude-sonnet-4-5')
agent = Agent('anthropic:claude-haiku-4-5')

# Google
agent = Agent('google-gla:gemini-2.0-flash')
agent = Agent('google-vertex:gemini-2.0-flash')

# Others: groq:, mistral:, cohere:, bedrock:, etc.

構造化出力

検証済みの型付きレスポンスには、Pydantic モデルを使用します。

from pydantic import BaseModel
from pydantic_ai import Agent

class CityInfo(BaseModel):
    city: str
    country: str
    population: int

agent = Agent('openai:gpt-4o', output_type=CityInfo)
result = agent.run_sync('Tell me about Paris')
print(result.output.city)  # "Paris"
print(result.output.population)  # int, validated

エージェントの設定

from pydantic_ai import Agent
from pydantic_ai.settings import ModelSettings

agent = Agent(
    'openai:gpt-4o',
    output_type=MyOutput,           # Structured output type
    deps_type=MyDeps,               # Dependency injection type
    instructions='You are helpful.',  # Static instructions
    retries=2,                      # Retry attempts for validation
    name='my-agent',                # For logging/tracing
    model_settings=ModelSettings(   # Provider settings
        temperature=0.7,
        max_tokens=1000
    ),
    end_strategy='early',           # How to handle tool calls with results
)

エージェントの実行

実行方法は 3 つあります。

# Async (preferred)
result = await agent.run('prompt', deps=my_deps)

# Sync (convenience)
result = agent.run_sync('prompt', deps=my_deps)

# Streaming
async with agent.run_stream('prompt') as response:
    async for chunk in response.stream_output():
        print(chunk, end='')

指示とシステムプロンプトの違い

# Instructions: Concatenated, for agent behavior
agent = Agent(
    'openai:gpt-4o',
    instructions='You are a helpful assistant. Be concise.'
)

# Dynamic instructions via decorator
@agent.instructions
def add_context(ctx: RunContext[MyDeps]) -> str:
    return f"User ID: {ctx.deps.user_id}"

# System prompts: Static, for model context
agent = Agent(
    'openai:gpt-4o',
    system_prompt=['You are an expert.', 'Always cite sources.']
)

よくあるパターン

パラメーター化されたエージェント(型安全)
from dataclasses import dataclass
from pydantic_ai import Agent, RunContext

@dataclass
class Deps:
    api_key: str
    user_id: int

agent: Agent[Deps, str] = Agent(
    'openai:gpt-4o',
    deps_type=Deps,
)

# deps is now required and type-checked
result = agent.run_sync('Hello', deps=Deps(api_key='...', user_id=123))
依存関係なし(型チェッカーを満たす)
# Option 1: Explicit type annotation
agent: Agent[None, str] = Agent('openai:gpt-4o')

# Option 2: Pass deps=None
result = agent.run_sync('Hello', deps=None)

検証ゲート

本番コードでエージェントを使用する前に、以下を順番に実行してください。

  1. スモークテスト — agent.run_sync('Reply with OK.')(非同期コードの場合は await agent.run(...))を実行します。合格条件: 呼び出しが例外を発生させずに完了し、result.output が存在すること。
  2. 構造化出力 — output_type を設定している場合は、スキーマを満たすはずのレスポンスを求めるプロンプトを指定します。合格条件: result.output が Pydantic モデルのインスタンスであること。検証に繰り返し失敗する場合は、まだ機能を追加せず、指示または retries を調整してください。
  3. 依存関係 — deps_type を設定している場合は、その型の deps= を指定して run / run_sync を呼び出します。合格条件: 呼び出しの型チェックが通り、完了すること(または、モデル/API の理由でのみ失敗し、deps の値が欠落していたり、型が誤っていたりしないこと)。

判断基準

シナリオ設定
シンプルなテキストレスポンスAgent(model)
構造化データの抽出Agent(model, output_type=MyModel)
外部サービスが必要deps_type=MyDeps を追加
検証の再試行が必要retries=3 に増やす
デバッグ/モニタリングinstrument=True を設定

コメント