1.7 KiB
1.7 KiB
source_url, ingested
| source_url | ingested |
|---|---|
| https://mp.weixin.qq.com/s/jg6lW3ObZooBsrWTGwIcRg | 2026-06-10 |
用了两年 Pydantic,我只碰了三分之一
微信公众号文章 | 2026年 拆解 Pydantic 生态三件套:pydantic-core (Rust 验证引擎) + Logfire (OTel 可观测) + Pydantic AI (类型安全 Agent 框架)
核心观点
Pydantic 不是校验库——是一个由三层组成的生态:
- pydantic-core (Rust):校验速度 / 脱离 GIL / 多线程并发
- Logfire (OTel):可观测性 / 成本监控 / 漂移检测
- Pydantic AI:Agent 行为约束 / 类型安全的 tool 调用
关键洞察
- 数据源变了:2018 年校验的是人填的表单(错误模式稳定),2026 年校验的是 LLM 生成的 JSON(错误模式漂移)
- 从"校验"到"可观测":不能只看单次报错,要看趋势——哪些字段在漂移、哪个模型输出最不稳定、token 成本是否在涨
- 工厂质检类比:手工抽检(V1)→ 传送带自动扫描(strict=True)→ IoT 传感器 + 实时看板(三件套全开)
- TypeAdapter:同一份数据,不同严格度——API 入口用 strict,Agent 内部传递用宽松
- strict/forbid/frozen 三配置零成本:不需要装新包,只改 model_config
- 类型从"报错器"变"编译器":Pydantic AI 的类型系统在运行时之前就约束了 Agent 的行为空间
- 诚实边界:只做 API 校验 → 继续用 pydantic;排障靠 print → 加 Logfire;5+ tool Agent → 考虑 Pydantic AI
渐进路线图
- 今天:所有 BaseModel 加 strict + forbid + validate_default
- 这周(如有 Agent):装 Logfire,4 行代码
- 下次新 Agent 项目:tool > 3 时用 Pydantic AI