AI News HubLIVE
站內改寫2 分鐘閱讀

使用Pydantic AI在Python中構建AI代理

學習如何使用Pydantic AI框架在Python中構建生產級的AI代理,涵蓋結構化輸出、自定義工具和依賴注入,以及Web搜索和擴展推理等內置功能。

來源Machine Learning Mastery作者: Bala Priya C

本教程將指導你如何使用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,但模式適用於Anthropic Claude、Google Gemini等)。

安裝Pydantic AI

創建虛擬環境並安裝:

python -m venv venv
source venv/bin/activate
pip install pydantic-ai

然後設置API密鑰(如export OPENAI_API_KEY=...)。

構建第一個代理

只需幾行代碼:

from pydantic_ai import Agent
agent = Agent(
    "openai:gpt-4o-mini",
    instructions="You are a concise assistant. Answer in one or two sentences."
)
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. Only include what is explicitly stated."
)
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:
    """查詢每100克食材的營養信息"""
    data = NUTRITION_DB.get(ingredient.lower().strip())
    if data:
        return json.dumps({"ingredient": ingredient, **data})
    return f"Not found. Available: {', '.join(NUTRITION_DB)}"

代理調用工具後返回結構化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 and provide a verdict."
)
@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實例,測試時可輕鬆替換為mock。

內置功能

Pydantic AI還支持Web搜索和擴展推理,可通過配置啓用。本教程讓你掌握構建實用代理的基礎,完整Colab筆記本見GitHub。