Loading...

文章背景图

Pydantic AI:Pydantic 官方的类型安全 Python Agent 框架|部署与使用全指南

2026-10-27
0
- 字
- 分钟
|

Pydantic AI:Pydantic 官方的类型安全 Python Agent 框架|部署与使用全指南

适用版本段:本文基于 pydantic-ai 2.x(PyPI 最新 2.61.0,调研日期 2026 年 10 月)撰写。GitHub 仓库 pydantic/pydantic-ai 约 20.9k star,CI 覆盖率 100%,License 为 MIT。由 Pydantic 团队官方维护,迭代节奏很快,文中 API 以 v2 文档(pydantic.dev/docs/ai)为准;如与你安装的小版本有出入,以官方文档为准。

Pydantic AI 官方 Logo

Pydantic AI 是 Pydantic 团队出品的 Python Agent 框架:把「结构化输出、工具调用、依赖注入」全部做成端到端类型安全——IDE、mypy 和 LLM 看到的是同一份类型。换模型只需换一个字符串前缀(OpenAI、Anthropic、Google、Groq、Mistral、Cohere、Ollama 等数十家),同时原生支持 MCP、Graph 工作流、流式输出、Logfire/OpenTelemetry 可观测。它是纯 Python 库,不是服务器:用 pip install 装进你的项目即可,天然适合与 FastAPI 搭配。

一、项目介绍与适用场景

定位:「How Python does AI」——一个类型安全、可测试的 Agent 循环(agent loop)。它不替代 LangChain 式的编排全家桶,而是提供一个薄薄的、可组合的 Agent 抽象,加上官方的能力库(Harness)、评估库(Evals)、图控制流(Pydantic Graph)。

适用人群

典型用途

Python 后端工程师

在 FastAPI 里嵌入结构化输出/工具调用 Agent

数据工程 / 抽取任务

output_type 强约束的数据抽取与情感分析

AI 应用开发者

MCP 工具接入、多模型切换、A2A/Web/CLI 多种前端

对工程质量有要求的团队

类型检查 + Pydantic Evals + Logfire 追踪

不适合的场景:需要可视拖拽编排(用 Dify/n8n 更合适);需要现成服务器与记忆数据库(用 Letta 这类 Agent server);非 Python 技术栈(官方仅 Python,TypeScript 不在本项目内)。

二、核心功能逐条拆解

  1. 任意模型一个 API:Agent('openai:gpt-5')、Agent('anthropic:claude-sonnet-4-5')、Agent('google-gla:gemini-2.5-pro')、Agent('ollama:qwen3')……换模型就是换字符串,旗舰能力不被某一家锁定。

  2. 结构化输出(structured output):output_type=某个 Pydantic BaseModel,每次 run 返回通过校验的强类型对象;校验失败会自动重试。

  3. 工具调用(tool calling):@agent.tool 装饰器把普通函数变成工具,签名+docstring 自动生成 JSON schema,参数先校验再执行。

  4. 依赖注入:deps_type + RunContext[Deps],把数据库连接、HTTP client、用户上下文注入 tools 和 instructions。

  5. 流式输出:run_stream() / stream_text() 支持边生成边消费,含结构化输出的增量校验。

  6. 会话历史:message_history=result.all_messages() 把上一轮消息传给下一轮,实现多轮对话持久化。

  7. MCP 支持:mcp extra 后可直接挂载 MCP server(stdio / HTTP),把外部工具集喂给 Agent。

  8. Pydantic Graph:一个 agent loop 不够时,用类型化的图工作流表达复杂控制流。

  9. Logfire 可观测:两行代码接入 Pydantic Logfire(或任意 OpenTelemetry 后端),每次模型调用与工具调用都有 trace 和成本统计。

Logfire 中的 Agent 运行追踪
  1. 多前端:同一个 Agent 可跑在 CLI(clai)、内置 Web 聊天 UI、AG-UI/Vercel AI 事件流、A2A 协议后面。

  2. Durable execution:可挂到 Temporal、DBOS、Prefect 等引擎,实现跨重启的长时运行。

三、全套官方链接

资源

地址

GitHub 仓库

https://github.com/pydantic/pydantic-ai

官方文档

https://pydantic.dev/docs/ai/

安装文档

https://pydantic.dev/docs/ai/overview/install/

模型列表

https://pydantic.dev/docs/ai/models/overview/

PyPI

https://pypi.org/project/pydantic-ai/ | https://pypi.org/project/pydantic-ai-slim/

示例仓库(examples)

https://github.com/pydantic/pydantic-ai/tree/main/examples

Logfire

https://pydantic.dev/logfire

API Reference

https://pydantic.dev/docs/ai/api/agent/

License

MIT(仓库根目录 LICENSE)

社区

Slack: https://logfire.pydantic.dev/docs/join-slack/ | GitHub Issues

四、硬件与环境前置要求

项目

要求

操作系统

Linux / macOS / Windows 均可

Python

3.11+(官方硬性要求)

包管理

pip 或 uv(官方文档首推 uv)

CPU / 内存 / GPU

库本身无特殊要求;GPU 只在本地跑 Ollama 等推理时才需要

磁盘

视所装 extra 而定(boto3、anthropic 等 SDK 体积不一),全量约数百 MB

网络与账号

能访问 PyPI;所用模型厂商的 API key(OpenAI/Anthropic/Google 等),或本地 Ollama 服务

端口

库本身不监听端口;跑 Web UI / FastAPI 示例时用 8000 等常规端口

五、多平台部署步骤

Pydantic AI 是库而非服务,「部署」即在项目环境中安装。官方未提供 Docker 镜像(无服务端进程),容器化就是把依赖装进你自己的应用镜像,第六章给出 Dockerfile 示例。

5.1 Linux

python3.11 -m venv .venv && source .venv/bin/activate
pip install "pydantic-ai"            # 全量(含 OpenAI/Anthropic/Google 依赖 + CLI + MCP + Evals + Logfire 集成)
# 或精简安装(推荐生产):
pip install "pydantic-ai-slim[openai]"

验证:

python -c "import pydantic_ai; print(pydantic_ai.__version__)"

5.2 macOS

brew install python@3.12
python3.12 -m venv .venv && source .venv/bin/activate
pip install "pydantic-ai-slim[anthropic]"

5.3 Windows

PowerShell:

py -3.12 -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install "pydantic-ai-slim[openai]"

注意 extra 列表必须加引号,防止 PowerShell 把方括号当通配符。

5.4 用 uv(官方推荐)

uv init my-agent && cd my-agent
uv add "pydantic-ai-slim[openai]"
uv run python -c "import pydantic_ai; print(pydantic_ai.__version__)"

5.5 安装官方示例

pip install "pydantic-ai[examples]"
# 或直接跑示例源码
git clone https://github.com/pydantic/pydantic-ai.git
cd pydantic-ai/examples

5.6 免安装体验内置 test 模型

不写 key 也能跑通类型链路:

from pydantic_ai import Agent
agent = Agent('test')
print(agent.run_sync('hello').output)

六、配置文件全部参数解释

没有配置文件,一切通过环境变量与代码参数配置。

6.1 模型接入全表(以官方 models.md / models overview 为准)

Provider

前缀写法

环境变量

slim extra

OpenAI

openai:gpt-5、openai-chat:、openai-responses:

OPENAI_API_KEY(兼容端点加 OPENAI_BASE_URL)

openai

Anthropic

anthropic:claude-sonnet-4-5

ANTHROPIC_API_KEY

anthropic

Google / Gemini

google-gla:gemini-2.5-pro、google-vertex:

GEMINI_API_KEY / GOOGLE_API_KEY

google

Groq

groq:llama-3.3-70b-versatile

GROQ_API_KEY

groq

Mistral

mistral:mistral-large-latest

MISTRAL_API_KEY

mistral

Cohere

cohere:command-r-plus

CO_API_KEY

cohere

Ollama

ollama:qwen3

OLLAMA_BASE_URL(默认 http://localhost:11434/v1)、云端另需 OLLAMA_API_KEY

复用 openai

DeepSeek

deepseek:deepseek-chat

DEEPSEEK_API_KEY

复用 openai

OpenRouter

openrouter:...

OPENROUTER_API_KEY

openrouter

xAI (Grok)

grok:grok-4

XAI_API_KEY / GROK_API_KEY

复用 openai

Bedrock

bedrock:...

AWS 凭证链(AWS_ACCESS_KEY_ID 等)

bedrock

Azure

azure:gpt-5

AZURE_OPENAI_API_KEY 等

复用 openai

Hugging Face

huggingface:...

HF_TOKEN

huggingface

Pydantic AI Gateway

gateway/<provider>:<model>

PYDANTIC_AI_GATEWAY_API_KEY

—

6.2 Ollama 本地模型(OpenAI 兼容 base_url 写法)

export OLLAMA_BASE_URL='http://localhost:11434/v1'
from pydantic_ai import Agent
agent = Agent('ollama:qwen3')   # 走环境变量

# 或显式指定 base_url:
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.ollama import OllamaProvider
model = OpenAIChatModel('qwen3', provider=OllamaProvider(base_url='http://localhost:11434/v1'))
agent = Agent(model)

(较新版本还提供 pydantic_ai.models.ollama.OllamaModel 与 pydantic_ai.providers.ollama.OllamaProvider,写法等价,以官方文档为准。)

6.3 Agent 常用构造参数(带注释示例)

from pydantic import BaseModel
from pydantic_ai import Agent

class Result(BaseModel):
    answer: str
    confidence: float

agent = Agent(
    'openai:gpt-5-mini',      # 模型:'provider:model' 字符串或模型实例
    instructions='你是严谨的助手。',   # 系统指令(可用函数动态生成)
    deps_type=None,           # 依赖类型,见第八章场景 4
    output_type=Result,       # 结构化输出类型
    retries=2,                # 校验失败重试次数
    model_settings={'temperature': 0.2},
)

其他常见环境变量:LOGFIRE_TOKEN(Logfire)、PYDANTIC_AI_GATEWAY_API_KEY(Gateway)。

七、启动、后台常驻、开机自启、改端口

库本身没有「启动」概念,常驻与否取决于你的应用:

  • 脚本:python main.py 前台跑;nohup python main.py & 或 systemd 常驻(把 ExecStart 指向你的脚本,写法与常规 Python 服务相同)。

  • Web 服务(FastAPI 集成,见第八章场景 6):uvicorn app:app --host 0.0.0.0 --port 8000,改端口即改 --port;systemd / Supervisor / Docker 均按常规 Python Web 服务处理。

  • 内置 Web 聊天 UI:agent.to_web()(web extra 提供 starlette+uvicorn)直接起本地聊天页。

官方内置 Web 聊天 UI
  • CLI:pip install "pydantic-ai-slim[cli,openai]" 后运行 clai,进入交互终端。

  • Windows:用计划任务或打包为 Windows 服务(NSSM 非官方方案,需自行评估)。

八、功能实操教程

场景 1:最小 Agent + 结构化输出

from pydantic import BaseModel, Field
from pydantic_ai import Agent

class Sentiment(BaseModel):
    label: str            # 'positive' / 'negative' / 'neutral'
    score: float = Field(ge=-1, le=1)

agent = Agent('openai:gpt-5-mini', output_type=Sentiment)
result = agent.run_sync('这个产品太好用了!')
print(result.output)      # Sentiment(label='positive', score=0.9)
print(result.usage())     # token 用量

场景 2:工具调用(@agent.tool)

from pydantic_ai import Agent

agent = Agent('openai:gpt-5-mini', instructions='用工具回答天气问题。')

@agent.tool
def get_weather(ctx, city: str) -> str:
    """查询指定城市的当前天气。"""
    return f'{city}: 晴,26℃'

print(agent.run_sync('北京今天天气?').output)

场景 3:流式输出

import asyncio
from pydantic_ai import Agent

async def main():
    agent = Agent('openai:gpt-5-mini')
    async with agent.run_stream('写一句关于秋天的诗') as result:
        async for chunk in result.stream_text(delta=True):
            print(chunk, end='', flush=True)
    print()

asyncio.run(main())

场景 4:依赖注入(RunContext + deps_type)

from dataclasses import dataclass
import httpx
from pydantic_ai import Agent, RunContext

@dataclass
class Deps:
    http: httpx.AsyncClient
    user_id: int

agent = Agent('openai:gpt-5-mini', deps_type=Deps)

@agent.tool
async def profile(ctx: RunContext[Deps]) -> str:
    """返回当前用户的资料。"""
    r = await ctx.deps.http.get(f'https://api.example.com/users/{ctx.deps.user_id}')
    return r.text

# async with httpx.AsyncClient() as http:
#     await agent.run('我是谁?', deps=Deps(http=http, user_id=42))

场景 5:多轮对话(message_history 持久化)

result1 = agent.run_sync('我叫小林。')
result2 = agent.run_sync('我叫什么名字?', message_history=result1.all_messages())
# 持久化:把 result1.all_messages() 序列化(如 all_messages_json())存入数据库,下次读回传入即可

场景 6:FastAPI / A2A 集成

官方示例里的 chat app 用 FastAPI 提供 SSE 流:

from fastapi import FastAPI
from pydantic_ai import Agent

app = FastAPI()
agent = Agent('openai:gpt-5-mini')

@app.post('/chat')
async def chat(q: str):
    return {'output': (await agent.run(q)).output}
# 官方还提供 to_web() / AG-UI / A2A 等集成,见 docs 的 UI integrations 章节
uvicorn app:app --port 8000
官方 chat app 示例界面

场景 7:MCP server 接入

pip install "pydantic-ai-slim[openai,mcp]"
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio

fs = MCPServerStdio('npx', args=['-y', '@modelcontextprotocol/server-filesystem', '/tmp'])
agent = Agent('openai:gpt-5-mini', toolsets=[fs])
print(agent.run_sync('列出 /tmp 下的文件').output)

(新版文档推荐通过 capabilities=[MCP(url)] 挂载,具体以官方 MCP 文档为准。)

场景 8:Logfire 可观测(可选)

pip install "pydantic-ai-slim[logfire]"
logfire auth   # 首次
import logfire
logfire.configure()
logfire.instrument_pydantic_ai()
# 之后每次 run 的模型调用、工具调用、token 成本都会出现在 Logfire 控制台

九、全套报错故障排查

现象

原因

解决

ModuleNotFoundError: pydantic_ai

装错环境 / venv 未激活

pip show pydantic-ai 检查

SyntaxError/安装解析失败

Python < 3.11

升级 Python(官方硬性要求 3.11+)

UserError: ... model ... requires ... package

用了 slim 但没装对应 extra

如 pip install "pydantic-ai-slim[openai]"

ModelHTTPError 401 / status_code=401

API key 缺失或错误

检查 OPENAI_API_KEY 等环境变量是否 export 且在当前 shell

401 但 key 正确(代理/网关)

base_url 未指向代理

设 OPENAI_BASE_URL 或自定义 Provider

模型名报 UnknownModel

前缀或模型名拼错

对照官方 models 列表,如 google-gla: 而非 google:(旧版)

Ollama 连不上

服务未启动或地址错

curl http://localhost:11434/v1/models;设 OLLAMA_BASE_URL

Ollama 结构化输出不稳定

小模型 + 默认 ToolOutput

用 NativeOutput(Ollama v0.5+ 本地支持 schema 约束)或换大模型

UnexpectedModelBehavior: exceeded maximum retries

模型反复输出不合 schema 的内容 / 工具死循环

简化 schema 与 docstring;增大 retries;换更强模型;查看 Logfire trace 定位失败步

结构化输出校验失败(ValidationError)

模型给了非法字段

同上;或放宽字段约束(Optional、默认值)

pip install "pydantic-ai[xxx]" 报 extras 不存在

extra 名拼错

对照官方 slim extras 列表(本文第六章)

流式时拿不到结构化结果

只用 stream_text

结构化增量用 stream_output() / 结束后 result.output

多轮对话丢记忆

没传 message_history

传上一轮 all_messages()

MCP server 起不来

依赖 mcp extra / npx 不存在

装 [mcp] extra;确认 Node/npx 或改 HTTP MCP

Windows 安装命令报错

方括号被 PowerShell 解释

给包名加引号

代理环境 TLS 报错

企业 CA / 最小镜像缺证书

装 ca-certificates 与私有根证书,或传自定义 http_client

token 费用暴涨

长 message_history 反复全量发送

裁剪历史、用摘要、在 Logfire 监控 usage

十、升级、回滚与卸载

  • 查看版本:pip show pydantic-ai 或 python -c "import pydantic_ai; print(pydantic_ai.__version__)"。

  • 升级:pip install -U "pydantic-ai"(或 uv add -U);大版本间(如 v1→v2)有 breaking changes,务必读官方 changelog(GitHub Releases)。

  • 回滚:pip install "pydantic-ai==1.0.20"(指定历史版本号);建议锁版本(pip freeze > requirements.txt / uv.lock)。

  • Docker 化应用:重建镜像并固定 tag 即可回滚到旧镜像。

  • 卸载:pip uninstall pydantic-ai pydantic-ai-slim pydantic-graph pydantic-evals(按需),删除 venv 即彻底清理;库本身不在系统里留任何状态。

十一、商用许可与合规风险提示

  • License:MIT,商用、修改、闭源再分发均允许,只需保留版权与许可声明。

  • 商标:「Pydantic」「Logfire」为 Pydantic Services Inc. 商标,产品命名避免暗示官方背书。

  • API 费用:框架免费,模型调用费自理;推荐接 Logfire(有免费档)或 genai-prices 监控成本。

  • 数据隐私:提示词与工具数据会发往所选模型厂商;敏感场景用 Ollama 本地模型或确认厂商 DPA。

  • 出网:库只访问你配置的模型端点与(可选)Logfire;企业内网注意代理与白名单。

  • 生产风险:框架迭代快、大版本有 breaking changes,上线前锁版本并跑 Pydantic Evals 回归;工具函数会在本进程内执行真实逻辑,注意权限隔离与输入校验。

附录:命令速查

# 安装
pip install "pydantic-ai"                       # 全量
pip install "pydantic-ai-slim[openai]"          # 精简 + OpenAI
pip install "pydantic-ai-slim[openai,mcp,logfire]"
uv add "pydantic-ai-slim[anthropic]"
# 环境变量
export OPENAI_API_KEY=sk-xxx
export OLLAMA_BASE_URL='http://localhost:11434/v1'
# CLI
pip install "pydantic-ai-slim[cli,openai]" && clai
# 版本 / 升级 / 回滚
python -c "import pydantic_ai; print(pydantic_ai.__version__)"
pip install -U pydantic-ai
pip install "pydantic-ai==1.0.20"
# Logfire
logfire auth && logfire projects new

评论交流

文章目录