Files
myWiki/articles/pydantic-three-piece-suite.md

84 lines
4.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "Pydantic 三件套:从校验库到 AI 基础设施"
created: 2026-06-10
updated: 2026-06-10
type: article
tags: [pydantic, agent, observability, open-telemetry, validation]
sources: [raw/articles/pydantic-three-piece-suite-2026.md]
---
# Pydantic 三件套:从校验库到 AI 基础设施
> 微信公众号 | 2026年
> Pydantic 不只是 BaseModel——Rust 验证引擎 + OTel 可观测平台 + 类型安全 Agent 框架
## TL;DR
- [[pydantic]] 生态三层:[[pydantic-core|Rust 引擎]] + [[logfire|Logfire 可观测]] + [[pydantic-ai|Pydantic AI Agent 框架]]
- **strict + forbid + frozen 三配置零成本立即生效**
- Logfire 四行代码接入debug 从半天降到分钟级
- Pydantic AI 让类型系统约束 Agent 行为,而非仅事后校验
## 核心问题
LLM 时代的校验需求已经变了。人填的表单错误模式稳定LLM 输出的 JSON 错误模式**漂移**——同样的 prompt 跑 100 次,第 1 次可能字段名少了条下划线,第 47 次可能多了个字段,第 89 次可能把 str 塞了 None。
传统的 BaseModel 只能告诉你「第 47 次错了」,但你需要的是 [[drift-detection|漂移检测]]——哪个字段一直在漂哪个模型输出最不稳定token 成本是不是偷偷在涨?
## 三件套全景
| 层 | 解决的问题 | 不用的话 |
|---|-----------|---------|
| [[pydantic-core|pydantic-core (Rust)]] | 校验速度 / 脱离 GIL | 多线程校验串行 |
| [[logfire|Logfire (OTel)]] | 可观测 / 成本监控 / 漂移检测 | 只知"第 47 次错" |
| [[pydantic-ai|Pydantic AI]] | Agent 行为约束 / 类型安全 tool 调用 | 手写 JSON Schema + 事后校验 |
三层独立,共享同一套类型定义。可任意叠加。
## 第一件pydantic-core
Rust 写的物理引擎,通过 PyO3 绑定。`model_validate(data)` 的实际路径Python → CoreSchema JSON → Rust 层逐字段校验 → 返回。**步骤 2-4 全部在 Rust 侧完成,不走 GIL**。配合 `asyncio.gather()` 并发调 20 个 LLM API 时,每个回复的 JSON 解析可在不同线程并行跑 Rust 校验。
**[[typeadapter|TypeAdapter]]**同一份数据不同严格度——API 入口用 strictAgent 内部传递用宽松,不用写两套模型。
**三个零成本配置**
```python
model_config = {
"strict": True, # 空字符串不会变 0类型不匹配直接炸
"extra": "forbid", # LLM 多塞字段立刻报错
"frozen": True, # 模块间传递不可篡改
}
```
## 第二件Logfire
基于 [[open-telemetry|OpenTelemetry]] 标准的可观测平台。核心价值:
- **4 行代码**拿到完整 Agent span 树(根 → model request → tool 调用 → follow-up
- **OTel 标准**:数据不锁定厂商,可自托管或导出到 Grafana/Jaeger
- **SQL 查询 trace**:不是点按钮过滤,是写 SQL 查 [[drift-detection|漂移趋势]]
真实案例Sophos 安全团队发现 Agent 调用某个 tool 的频率从每 50 次推理 1 次涨到每 8 次 1 次——传统日志只看调用成功与否Logfire 的 SQL 查询揭示了频率异常。
## 第三件Pydantic AI
把 Pydantic 的类型系统直接嵌入 Agent 运行时——类型从"报错器"变成"编译器",在运行时之前就约束了 Agent 的行为空间。
- `@agent.tool` 自动从函数签名推断 tool schema不需手写 JSON Schema
- `result.data` 类型安全IDE 补全可用
- 多步 Agent 支持(多次推理 + 多次 tool 调用)
- `instrument=True` 自动接 Logfire trace
与 Instructor 的定位差异:单次 LLM 结构化输出 → Instructor多步推理 + 多 tool 调用的 Agent → Pydantic AI。
## 渐进路线图
1. **今天 (5min)**:所有 BaseModel 加 `strict=True, extra='forbid', validate_default=True`
2. **这周**:有 Agent 就加 Logfire4 行代码
3. **下次新 Agent 项目**tool > 3 就试 Pydantic AI
## 参考
- [[agent-observability|Agent 可观测性]]
- [[type-safety-in-agents|Agent 类型安全]]
- [原始存档](raw/articles/pydantic-three-piece-suite-2026.md)