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。