> ## Content Index
> Fetch the complete content index at: https://www.hubwiz.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# PydanticAI支持验证的代理框架
- URL: https://www.hubwiz.com/blog/pydanticai-agent-framework-with-validation/
- Published: 2024-12-07T17:50:53.000Z
- Updated: 2024-12-07T17:51:10.000Z
- Description: PydanticAI是Pydantic作者推出的多代理开发框架，它利用Pydantic 验证静态和流式响应，确保可靠的数据处理，与 OpenAI、Gemini 和 Groq 模型兼容。
- Author: admin
- Tags: LIBRARY, PYDANTICAI, PYDANTIC, OPENAI, GEMINI, GROQ, #Import 2026-10-14 14:41

生成式AI领域是人类历史上发展最快的领域之一。正如你可能听到的那样，2025 年将是人工智能代理/多人工智能代理的一年，从单纯的LLM转变而来。目前的发展显示出同样的趋势：AWS、OpenAI、微软等巨头纷纷发布AI代理框架。

在迄今为止的所有版本中，PydanticAI 代理框架似乎是最有用和最重要的版本，因为它支持LLM的 Pydantic。

在我们理解为什么 PydanticAI 是一个关键框架之前，我们必须了解：

## 1、Pydantic

Pydantic 是一个用于轻松验证和解析数据的 Python 库。它有助于确保你的数据准确无误并遵循预期的结构。它在处理外部输入（如 JSON 文件、用户数据或 API 响应）时特别有用。

Pydantic 无需手动为每个字段编写检查（例如，“这是一个整数吗？这个字符串是否太长？”），而是使用模型自动执行这些检查。

假设你正在制作一个应用程序，用户可提交其姓名、年龄和电子邮件。你想确保：

- 姓名是字符串。
- 年龄是数字。
- 电子邮件的格式有效。

以下是 Pydantic 简化此操作的方法：

```
from pydantic import BaseModel, EmailStr

# Define the model
class User(BaseModel):
    name: str
    age: int
    email: EmailStr

# Example input
user_data = {
    "name": "Alice",
    "age": 25,
    "email": "alice@example.com"
}

# Validate the input
user = User(**user_data)

print(user.name)  # Alice
print(user.age)   # 25
print(user.email) # alice@example.com
```

如果数据有误怎么办？

如果用户提交了无效数据（例如“age”：“twenty-five”），Pydantic 将自动抛出错误：

```
user_data = {
    "name": "Alice",
    "age": "twenty-five",  # Invalid
    "email": "alice@example.com"
}

user = User(**user_data)
# Error: value is not a valid integer
```

Pydantic 在部署中起着关键作用，因为大多数情况下必须遵循，因为

- 大规模数据验证：Pydantic 会自动验证大规模输入数据以确保其符合预期结构，从而减少错误。
- 错误处理和调试：它为无效数据提供清晰的错误消息，使生产调试更快、更容易。
- 自动解析和序列化：Pydantic 自动将原始数据转换为可用格式，简化数据处理。
- 与 FastAPI 良好集成：它与 FastAPI 无缝协作，定义用于在生产中处理 HTTP 数据的输入/输出模型。
- 确保微服务的稳健性：Pydantic 确保微服务之间一致且有效的数据交换，以避免集成问题。
- 预防安全问题：它在入口点验证数据以阻止恶意输入并增强应用程序安全性。

## 2、PydanticAI

现在，我们了解了 Pydantic 的重要性，让我们回到 PydanticAI。

PydanticAI 的主要功能：

- 结构化响应处理：利用 Pydantic 验证静态和流式响应，确保可靠的数据处理。
- 多功能模型支持：与 OpenAI、Gemini 和 Groq 模型兼容，具有用于集成其他模型的简单界面。
- 植根于 Pydantic 专业知识：由 Pydantic 创建者开发，Pydantic 是LangChain、OpenAI SDK 等流行框架的支柱。
- 简化的依赖管理：引入类型安全的依赖注入系统以简化测试和迭代开发。
- Pythonic 设计：采用标准 Python 编程实践进行代理组合和控制流，使开发人员能够直观地使用它。
- 使用 Logfire 进行监控：包括与 Logfire 集成，用于跟踪和调试 AI 驱动的应用程序的性能。
- 类型安全操作：确保稳健、类型检查的工作流程，最大限度地减少运行时错误。
- 活跃测试版：目前处于测试阶段，为持续增强和反馈驱动的更新提供了空间。

## 2、代码和设置

让我们快速构建一个虚拟的 PydanticAI 代理并了解它的工作原理

使用Pip 安装：

```
pip install 'pydantic-ai-slim[openai,vertexai,logfire]'
```

为你的 LLM 提供商设置 API 令牌。Pydantic 可以直接与 OpenAI、Groq 和 VertexAI 配合使用。

创建 PydanticAI 代理。此代码使用 PydanticAI 实现银行支持代理。它利用结构化的依赖关系、定义的结果模式以及用于与数据库中的客户数据交互的工具。

```
from dataclasses import dataclass

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

from bank_database import DatabaseConn

@dataclass
class SupportDependencies:  
    customer_id: int
    db: DatabaseConn  

class SupportResult(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)

support_agent = Agent(  
    'openai:gpt-4o',  
    deps_type=SupportDependencies,
    result_type=SupportResult,  
    system_prompt=(  
        'You are a support agent in our bank, give the '
        'customer support and judge the risk level of their query.'
    ),
)

@support_agent.system_prompt  
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  
async def customer_balance(
    ctx: RunContext[SupportDependencies], include_pending: bool
) -> float:
    """Returns the customer's current account balance."""  
    return await ctx.deps.db.customer_balance(
        id=ctx.deps.customer_id,
        include_pending=include_pending,
    )

async def main():
    deps = SupportDependencies(customer_id=123, db=DatabaseConn())
    result = await support_agent.run('What is my balance?', deps=deps)  
    print(result.data)  
    """
    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.data)
    """
    support_advice="I'm sorry to hear that, John. We are temporarily blocking 
    your card to prevent unauthorized transactions." block_card=True risk=8
    """
```

下面我们解释代码。

- `Dataclass`类装饰器（支持依赖项）定义代理所需的依赖项，例如客户 ID 和数据库连接 (db)。其用途是传递给代理以在查询期间访问特定于客户的数据
- `SupportResult`：指定代理输出的结构化格式。
- `support_advice`：为客户提供的文本建议。
- `block_card`：是否应封锁客户的卡。
- `risk`：查询中描述的情况的风险级别（0-10）。
- `Validation`：强制数据完整性（例如，风险必须介于 0 和 10 之间）。

代理设置：

- 使用 openai:gpt-4o 模型生成响应。
- 指定依赖项（deps\_type）和预期输出（result\_type）。
- 包含一个系统提示，用于设置代理的上下文，指示其提供支持并评估查询风险。

`System Prompt` 函数：

通过查询数据库，动态地用客户名称丰富系统提示。

工作原理：使用客户 ID (ctx.deps.customer\_id) 访问数据库 (ctx.deps.db)。返回带有客户名称的字符串以个性化交互。

自定义工具

添加一个工具来获取客户的帐户余额，可选择包括待处理交易。

工作原理：使用客户 ID 和 include\_pending 标志查询数据库。以浮点数形式返回余额。

## 3、运行代理

目的：演示如何通过传递查询和依赖项与代理交互。

步骤：

- 使用客户 ID 和数据库连接创建 SupportDependencies 对象。
- 使用查询（“我的余额是多少？”）调用代理的运行方法。
- 代理根据查询、依赖项和工具生成响应。

你可能已经注意到，输出采用 SupportResult（Risk 为 int，Block\_card 为 Bool）类中提到的定义格式，因此解决了 LLM 结构化输出的一大问题。

## 4、结束语

PydanticAI 提供了一个强大的框架，用于使用生成式 AI 构建强大的生产级应用程序。

通过利用 Pydantic 的数据验证功能并与 LLM 无缝集成，它可确保结构化、类型安全且安全的交互。它的易用性以及对多种 AI 模型的支持使其成为开发人员构建 AI 代理的宝贵工具。

随着 PydanticAI 的不断发展，它有望简化 AI 驱动应用程序的开发并增强其可靠性和可扩展性。

---

原文链接：[PydanticAI: Pydantic AI Agent Framework for LLMs](https://medium.com/data-science-in-your-pocket/pydanticai-pydantic-ai-agent-framework-for-llms-6c60c86e0e48?ref=hubwiz.com)

汇智网翻译整理，转载请标明出处