pydantic-ai

Python 如何實現 AI。代理、即時語音、影像生成、嵌入。每個模型、每個介面,全程型別化。

pydantic-ai 是什麼?

Python 如何實現 AI。代理、即時語音、影像生成、嵌入。每個模型、每個介面,全程型別化。

pydantic-ai 概覽

這是什麼

Pydantic AI 是一個 Python AI SDK,其 README 描述為「How Python does AI. Agents, realtime voice, image generation, embeddings. Every model, every interface, typed end to end.」它提供一個型別化、可擴展的代理迴圈,每個模型只需切換字串即可更換,並可在提供者失敗時自動回退到另一個模型。同一個代理可以運行在網頁前端、終端機、語音通話、持久化背景佇列、GitHub Actions 或作為一個可呼叫 run() 的普通物件。該專案採用 MIT 授權,為開源軟體。

主要功能

  • 型別化代理迴圈,透過 Pydantic 模型進行結構化輸出驗證。
  • 模型切換與回退:每個模型只需切換字串即可更換,並在失敗時自動回退到另一個模型。
  • 即時語音會話,支援 OpenAI Realtime、Gemini Live、Azure 和 xAI Grok Voice。
  • 影像生成,使用專用影像模型,可獨立使用或作為代理執行的一部分。
  • 內建嵌入(embeddings)支援。
  • 持久化執行,整合 Temporal、DBOS、Prefect、Restate、AWS Lambda、Airflow 等。
  • 透過獨立的 Pydantic AI Harness 套件提供能力系統(記憶體、護欄、子代理、規劃、上下文管理、持久化)。

使用情境

  • 從文字中進行簡單的型別化資料提取。
  • 複雜、長時間運行的多代理協作。
  • 編碼代理,具備檔案存取、Shell、儲存庫上下文、規劃和上下文管理。
  • 能夠在重啟和失敗後存活下來的持久化工作流程。
  • 支援工具呼叫的即時語音助手。
  • 為需要產生視覺內容的應用程式進行影像生成。

快速開始

安裝套件並執行一個基本的資料提取代理:

uv add pydantic-ai
from typing import Literal
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext

class Sentiment(BaseModel):
    label: Literal['positive', 'negative', 'neutral']
    score: float = Field(ge=-1, le=1)

agent = Agent('openai:gpt-6.1-sol', output_type=Sentiment)

@agent.tool
def recent_reviews(ctx: RunContext, product: str) -> list[str]:
    """Fetch recent review snippets for a product."""
    return ['The new release fixed everything I complained about!']

result = agent.run_sync('How are people feeling about the Extract app?')
print(result.output)
### > label='positive' score=0.9

授權與價格

MIT 授權,開源軟體。

內容整理自該專案公開的 README 與儲存庫資訊。

將此徽章加入你的 README

Featured on YunoDB 徽章樣式與說明

你是這個專案的維護者嗎?展示它已收錄於 YunoDB。

Markdown[![Featured on YunoDB](https://yunodb.com/badge/pydanticpydantic-ai.svg)](https://yunodb.com/tools/pydanticpydantic-ai?utm_source=github&utm_medium=badge)
HTML<a href="https://yunodb.com/tools/pydanticpydantic-ai?utm_source=github&utm_medium=badge"><img src="https://yunodb.com/badge/pydanticpydantic-ai.svg" alt="Featured on YunoDB" height="20"></a>