Note
本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
English · 原始项目 · 上游 README
原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
文档: ai.pydantic.dev
FastAPI 凭借基于 Pydantic Validation 与现代 Python 特性(如类型提示)的创新且符合人体工程学的设计,彻底改变了 Web 开发。
然而,尽管几乎每一个 Python 智能体框架和 LLM 库都在使用 Pydantic Validation,当我们在 Pydantic Logfire, 中开始使用 LLM 时,却找不到能带来同样体验的方案。
我们构建 Pydantic AI 只有一个简单目标:将那种 FastAPI 般的开发体验带给 GenAI 应用与智能体开发。
由 Pydantic 团队打造: Pydantic Validation 是 OpenAI SDK、Google ADK、Anthropic SDK、LangChain、LlamaIndex、AutoGPT、Transformers、CrewAI、Instructor 等众多项目的校验层。既然可以直接使用源头,何必使用衍生品? 😃
模型无关(Model-agnostic): 几乎支持所有 模型 与提供商:OpenAI、Anthropic、Gemini、DeepSeek、Grok、Cohere、Mistral、Perplexity;Azure AI Foundry、Amazon Bedrock、Google Cloud、Ollama、LiteLLM、Groq、OpenRouter、Together AI、Fireworks AI、Cerebras、Hugging Face、GitHub、Heroku、Vercel、Nebius、OVHcloud、Alibaba Cloud、SambaNova 和 Z.AI。若你偏爱的模型或提供商未在列表中,也可以轻松实现 自定义模型.
无缝可观测性(Observability): 与我们的通用 OpenTelemetry 可观测性平台 Pydantic Logfire, 深度 集成,用于实时调试、基于评估(evals)的性能监控,以及行为、追踪与成本跟踪。若你已有支持 OTel 的可观测性平台,也可以 直接使用.
完全类型安全(Type-safe): 旨在为 IDE 或 AI 编程助手提供尽可能多的上下文,以支持自动补全与 类型检查,,将整类错误从运行时前移到编写时,带来几分 Rust「编译通过即可运行」的体验。
强大的评估(Evals): 让你能够系统化地测试并 评估 所构建智能体系统的性能与准确性,并在 Pydantic Logfire 中持续监控其表现。
可扩展设计: 通过可组合的 能力(capabilities) 构建智能体,将工具、钩子、指令与模型设置打包为可复用单元。使用内置能力实现 网页搜索, 思考, 与 MCP,,从 Pydantic AI Harness 能力库中选取,自行构建,或安装 第三方能力包.。可完全通过 YAML/JSON 定义智能体——无需编写代码。
MCP 与 UI: 集成 Model Context Protocol 与多种 UI 事件流 标准,让智能体访问外部工具与数据,并以基于流式事件的方式构建交互式应用。
人机协同工具审批(Human-in-the-Loop Tool Approval): 可轻松标记某些工具调用在继续执行前 需要审批,并可依据工具调用参数、对话历史或用户偏好进行判断。
持久化执行(Durable Execution): 让你能够构建 持久化智能体,在瞬时 API 故障、应用错误或重启后仍能保留进度,并以生产级可靠性处理长时间运行、异步以及人机协同工作流。
流式输出(Streamed Outputs): 提供持续 流式传输 结构化输出的能力,并即时校验,确保实时访问生成的数据。
图(Graph)支持: 提供一种基于类型提示定义 图 的强大方式,适用于标准控制流容易退化为面条代码的复杂应用。
不过说实话,任何清单都不如 亲自试一试 来得有说服力——看看它给你的感受如何!
以下是 Pydantic AI 的最小示例:
from pydantic_ai import Agent
# Define a very simple agent including the model to use, you can also set the model when running the agent.
agent = Agent(
'anthropic:claude-sonnet-4-6',
# Register static instructions using a keyword argument to the agent.
# For more complex dynamically-generated instructions, see the example below.
instructions='Be concise, reply with one sentence.',
)
# Run the agent synchronously, conducting a conversation with the LLM.
result = agent.run_sync('Where does "hello world" come from?')
print(result.output)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language.
"""
(该示例完整可用,在假设你已 安装 pydantic_ai 包) 的前提下,可直接运行。)_
交互会非常简短:Pydantic AI 会将指令与用户提示发送给 LLM,模型再返回文本响应。
目前还不算有趣,但我们可以轻松添加 工具, 动态指令, 结构化输出, 或可组合的 能力,以构建更强大的智能体。
from pydantic_ai import Agent
from pydantic_ai.capabilities import Thinking, WebSearch
agent = Agent(
'anthropic:claude-sonnet-4-6',
instructions='Be concise, reply with one sentence.',
capabilities=[Thinking(), WebSearch()],
)
result = agent.run_sync('What was the mass of the largest meteorite found this year?')
print(result.output)
下面是一个使用 Pydantic AI 为银行构建支持智能体的简明示例:
(文档中有更完善的示例 请参阅文档)**
from dataclasses import dataclass
from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext
from bank_database import DatabaseConn
# SupportDependencies is used to pass data, connections, and logic into the model that will be needed when running
# instructions and tool functions. Dependency injection provides a type-safe way to customise the behavior of your agents.
@dataclass
class SupportDependencies:
customer_id: int
db: DatabaseConn
# This Pydantic model defines the structure of the output returned by the agent.
class SupportOutput(BaseModel):
support_advice: str = Field(description='Advice returned to the customer')
block_card: bool = Field(description="Whether to block the customer's card")
risk: int = Field(description='Risk level of query', ge=0, le=10)
# This agent will act as first-tier support in a bank.
# Agents are generic in the type of dependencies they accept and the type of output they return.
# In this case, the support agent has type `Agent[SupportDependencies, SupportOutput]`.
support_agent = Agent(
'openai:gpt-5.2',
deps_type=SupportDependencies,
# The response from the agent will be guaranteed to be a SupportOutput,
# if validation fails the agent is prompted to try again.
output_type=SupportOutput,
instructions=(
'You are a support agent in our bank, give the '
'customer support and judge the risk level of their query.'
),
)
# Dynamic instructions can make use of dependency injection.
# Dependencies are carried via the `RunContext` argument, which is parameterized with the `deps_type` from above.
# If the type annotation here is wrong, static type checkers will catch it.
@support_agent.instructions
async def add_customer_name(ctx: RunContext[SupportDependencies]) -> str:
customer_name = await ctx.deps.db.customer_name(id=ctx.deps.customer_id)
return f"The customer's name is {customer_name!r}"
# The `tool` decorator let you register functions which the LLM may call while responding to a user.
# Again, dependencies are carried via `RunContext`, any other arguments become the tool schema passed to the LLM.
# Pydantic is used to validate these arguments, and errors are passed back to the LLM so it can retry.
@support_agent.tool
async def customer_balance(
ctx: RunContext[SupportDependencies], include_pending: bool
) -> float:
"""Returns the customer's current account balance."""
# The docstring of a tool is also passed to the LLM as the description of the tool.
# Parameter descriptions are extracted from the docstring and added to the parameter schema sent to the LLM.
balance = await ctx.deps.db.customer_balance(
id=ctx.deps.customer_id,
include_pending=include_pending,
)
return balance
... # In a real use case, you'd add more tools and a longer system prompt
async def main():
deps = SupportDependencies(customer_id=123, db=DatabaseConn())
# Run the agent asynchronously, conducting a conversation with the LLM until a final response is reached.
# Even in this fairly simple case, the agent will exchange multiple messages with the LLM as tools are called to retrieve an output.
result = await support_agent.run('What is my balance?', deps=deps)
# The `result.output` will be validated with Pydantic to guarantee it is a `SupportOutput`. Since the agent is generic,
# it'll also be typed as a `SupportOutput` to aid with static type checking.
print(result.output)
"""
support_advice='Hello John, your current account balance, including pending transactions, is $123.45.' block_card=False risk=1
"""
result = await support_agent.run('I just lost my card!', deps=deps)
print(result.output)
"""
support_advice="I'm sorry to hear that, John. We are temporarily blocking your card to prevent unauthorized transactions." block_card=True risk=8
"""
若要亲自体验 Pydantic AI,请安装 并参阅示例中的说明.
阅读文档 以进一步了解如何使用 Pydantic AI 构建应用。
阅读 API Reference 以了解 Pydantic AI 的接口。
如有疑问,请加入 Slack 或在 GitHub 上提交 issue。
Pydantic Stack 汇集了交付生产级 AI 智能体所需的一切: