跳转到内容

介绍

Pydantic AI
Pydantic AI

以 Pydantic 方式构建的 GenAI Agent 框架

CI Coverage PyPI versions license Join Slack

Pydantic AI 是一个 Python Agent 框架,旨在帮助您快速、自信且轻松地构建生产级的生成式 AI 应用程序和工作流。

FastAPI 通过提供创新且符合人体工程学的设计,革新了 Web 开发,其基础是 Pydantic 验证和类型提示等现代 Python 特性。

然而,尽管几乎所有的 Python Agent 框架和 LLM 库都使用 Pydantic 验证,但当我们在 Pydantic Logfire 中开始使用 LLM 时,却找不到任何能给我们带来同样感觉的东西。

我们构建 Pydantic AI 的目标很简单:将 FastAPI 的那种感觉带到 GenAI 应用和 Agent 开发中。

为何使用 Pydantic AI

  1. 由 Pydantic 团队打造Pydantic 验证是 OpenAI SDK、Google ADK、Anthropic SDK、LangChain、LlamaIndex、AutoGPT、Transformers、CrewAI、Instructor 等众多工具的验证层。既然能直取源头,何必使用衍生品? 😃

  2. 模型无关:支持几乎所有模型和提供商:OpenAI、Anthropic、Gemini、DeepSeek、Grok、Cohere、Mistral 和 Perplexity;Azure AI Foundry、Amazon Bedrock、Google Vertex AI、Ollama、LiteLLM、Groq、OpenRouter、Together AI、Fireworks AI、Cerebras、Hugging Face、GitHub、Heroku、Vercel。如果您喜欢的模型或提供商未列出,您可以轻松实现一个自定义模型

  3. 无缝的可观测性:与我们的通用 OpenTelemetry 可观测性平台 Pydantic Logfire 紧密集成,用于实时调试、基于评估的性能监控,以及行为、追踪和成本跟踪。如果您已有支持 OTel 的可观测性平台,您也可以使用它

  4. 完全类型安全:旨在为您的 IDE 或 AI 编码 Agent 提供尽可能多的上下文,以进行自动补全和类型检查,将整类错误从运行时转移到编写时,带来一点 Rust 那种“如果能编译,就能运行”的感觉。

  5. 强大的评估功能:使您能够系统地测试和评估您构建的 Agent 系统的性能和准确性,并在 Pydantic Logfire 中监控其长期性能。

  6. MCP、A2A 和 AG-UI:集成了模型上下文协议 (Model Context Protocol)Agent2AgentAG-UI 标准,使您的 Agent 能够访问外部工具和数据,与其他 Agent 互操作,并构建具有流式事件通信的交互式应用程序。

  7. 人在回路的工具审批:轻松让您标记某些工具调用在执行前需要审批,这可能取决于工具调用参数、对话历史或用户偏好。

  8. 持久化执行:使您能够构建持久化 Agent,这些 Agent 可以在短暂的 API 故障、应用程序错误或重启后保持其进度,并以生产级的可靠性处理长时间运行、异步和人在回路的工作流。

  9. 流式输出:提供流式传输结构化输出的能力,并进行即时验证,确保实时访问生成的数据。

  10. 图支持:提供一种强大的方式,使用类型提示来定义,用于复杂的应用程序中,在这些应用里,标准控制流可能会退化为意大利面条式代码。

但说实话,再多的清单也不如亲手一试,看看它给您带来的感觉来得有说服力!

订阅我们的新闻通讯 The Pydantic Stack,获取关于 Pydantic AI、Logfire 和 Pydantic 的更新与教程

Hello World 示例

这是一个 Pydantic AI 的极简示例

hello_world.py
from pydantic_ai import Agent

agent = Agent(  # (1)!
    'anthropic:claude-sonnet-4-0',
    instructions='Be concise, reply with one sentence.',  # (2)!
)

result = agent.run_sync('Where does "hello world" come from?')  # (3)!
print(result.output)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language.
"""
  1. 我们将 Agent 配置为使用 Anthropic 的 Claude Sonnet 4.0 模型,但您也可以在运行 Agent 时设置模型。
  2. 使用 Agent 的关键字参数注册静态指令
  3. 同步运行 Agent,与 LLM 开始一次对话。

(此示例是完整的,假设您已经安装了 pydantic_ai,便可“按原样”运行)

这次交流会非常简短:Pydantic AI 会将指令和用户提示发送给 LLM,模型将返回一个文本响应。

目前还不是很有趣,但我们可以轻松添加工具动态指令结构化输出来构建更强大的 Agent。

工具与依赖注入示例

这是一个使用 Pydantic AI 为银行构建支持 Agent 的简洁示例

bank_support.py
from dataclasses import dataclass

from pydantic import BaseModel, Field
from pydantic_ai import Agent, RunContext

from bank_database import DatabaseConn


@dataclass
class SupportDependencies:  # (3)!
    customer_id: int
    db: DatabaseConn  # (12)!


class SupportOutput(BaseModel):  # (13)!
    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)


support_agent = Agent(  # (1)!
    'openai:gpt-5',  # (2)!
    deps_type=SupportDependencies,
    output_type=SupportOutput,  # (9)!
    instructions=(  # (4)!
        'You are a support agent in our bank, give the '
        'customer support and judge the risk level of their query.'
    ),
)


@support_agent.instructions  # (5)!
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}"


@support_agent.tool  # (6)!
async def customer_balance(
    ctx: RunContext[SupportDependencies], include_pending: bool
) -> float:
    """Returns the customer's current account balance."""  # (7)!
    return await ctx.deps.db.customer_balance(
        id=ctx.deps.customer_id,
        include_pending=include_pending,
    )


...  # (11)!


async def main():
    deps = SupportDependencies(customer_id=123, db=DatabaseConn())
    result = await support_agent.run('What is my balance?', deps=deps)  # (8)!
    print(result.output)  # (10)!
    """
    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
    """
  1. 这个 Agent 将作为银行的一线支持。Agent 在接受的依赖项类型和返回的输出类型上是通用的。在本例中,支持 Agent 的类型为 Agent[SupportDependencies, SupportOutput]
  2. 这里我们将 Agent 配置为使用 OpenAI 的 GPT-5 模型,您也可以在运行 Agent 时设置模型。
  3. SupportDependencies 数据类用于向模型传递在运行指令工具函数时需要的数据、连接和逻辑。Pydantic AI 的依赖注入系统提供了一种类型安全的方式来定制 Agent 的行为,在运行单元测试和评估时尤其有用。
  4. 静态指令可以通过 Agent 的 instructions 关键字参数进行注册。
  5. 动态指令可以使用 @agent.instructions 装饰器注册,并且可以利用依赖注入。依赖项通过 RunContext 参数传递,该参数使用上面的 deps_type 进行参数化。如果这里的类型注解错误,静态类型检查器会捕获它。
  6. @agent.tool 装饰器让你注册函数,LLM 在响应用户时可能会调用这些函数。同样,依赖项通过 RunContext 传递,任何其他参数都将成为传递给 LLM 的工具模式。Pydantic 用于验证这些参数,错误会返回给 LLM,以便它重试。
  7. 工具的文档字符串(docstring)也会作为工具的描述传递给 LLM。参数描述会从文档字符串中提取并添加到发送给 LLM 的参数模式中。
  8. 异步运行 Agent,与 LLM 进行对话,直到获得最终响应。即使在这个相当简单的案例中,Agent 也会随着工具的调用以获取输出而与 LLM 进行多次消息交换。
  9. Agent 的响应将保证是 SupportOutput 类型。如果验证失败,通过反思,Agent 会被提示重试。
  10. 输出将使用 Pydantic 进行验证,以确保它是一个 SupportOutput。由于 Agent 是通用的,它也会被类型化为 SupportOutput,以帮助进行静态类型检查。
  11. 在实际用例中,您会向 Agent 添加更多的工具和更长的指令,以扩展其具备的上下文和能提供的支持。
  12. 这是一个数据库连接的简单示意,用于保持示例简短易读。在现实中,您会连接到外部数据库(例如 PostgreSQL)以获取客户信息。
  13. 这个 Pydantic 模型用于约束 Agent 返回的结构化数据。从这个简单的定义中,Pydantic 构建了 JSON Schema,告诉 LLM 如何返回数据,并在运行结束时执行验证,以保证数据的正确性。

完整的 bank_support.py 示例

为简洁起见,此处包含的代码不完整(缺少 DatabaseConn 的定义);您可以在这里找到完整的 bank_support.py 示例。

使用 Pydantic Logfire 进行监测

即使是一个只有少数几个工具的简单 Agent,也可能导致与 LLM 大量来回交互,这使得仅通过阅读代码就想确信发生了什么几乎是不可能的。为了理解上述运行的流程,我们可以使用 Pydantic Logfire 观察 Agent 的实际动作。

为此,我们需要设置 Logfire,并将以下代码添加到我们的代码中

bank_support_with_logfire.py
...
from pydantic_ai import Agent, RunContext

from bank_database import DatabaseConn

import logfire

logfire.configure()  # (1)!
logfire.instrument_pydantic_ai()  # (2)!
logfire.instrument_asyncpg()  # (3)!

...

support_agent = Agent(
    'openai:gpt-4o',
    deps_type=SupportDependencies,
    output_type=SupportOutput,
    system_prompt=(
        'You are a support agent in our bank, give the '
        'customer support and judge the risk level of their query.'
    ),
)
  1. 配置 Logfire SDK,如果项目未设置,此步骤将失败。
  2. 这将监测从此处开始使用的所有 Pydantic AI Agent。如果您只想监测特定的 Agent,可以向该 Agent 传递 instrument=True 关键字参数
  3. 在我们的演示中,DatabaseConn 使用 asyncpg 连接到 PostgreSQL 数据库,因此使用 logfire.instrument_asyncpg() 来记录数据库查询。

这样就足以让您看到如下 Agent 运行的视图

请参阅监控与性能以了解更多信息。

llms.txt

Pydantic AI 文档以 llms.txt 格式提供。该格式在 Markdown 中定义,适用于 LLM、AI 编码助手和 Agent。

提供两种格式

  • llms.txt:一个包含项目简要描述以及文档不同部分链接的文件。该文件的结构在这里有详细描述。
  • llms-full.txt:与 llms.txt 文件类似,但包含了所有链接的内容。请注意,此文件对于某些 LLM 可能过大。

截至今日,这些文件尚未被 IDE 或编码 Agent 自动利用,但如果您提供链接或全文,它们将会使用。

后续步骤

要亲自尝试 Pydantic AI,请安装它并按照示例中的说明进行操作。

阅读文档以了解更多关于使用 Pydantic AI 构建应用程序的信息。

阅读 API 参考以理解 Pydantic AI 的接口。

如果您有任何问题,请加入 Slack 或在 GitHub 上提交问题。