1.4 KiB
1.4 KiB
title, created, updated, type, tags, sources
| title | created | updated | type | tags | sources | |||||
|---|---|---|---|---|---|---|---|---|---|---|
| Agent 类型安全 (Type Safety in Agents) | 2026-06-10 | 2026-06-10 | concept |
|
|
Agent 类型安全 (Type Safety in Agents)
将类型系统嵌入 Agent 运行时,使类型在运行前就约束 Agent 的行为空间——类型从"报错器"进化为"编译器"。
两种范式
事后校验(传统)
LLM 输出 → model_validate → 错了 → 重试
类型只是最后的守门员。改了 tool 参数但忘了改校验逻辑 → 运行时 bug。
事前约束(Pydantic AI)
Agent 定义时类型已写入 tool schema → LLM 按 schema 输出 → 自动校验 → 框架重试
pydantic-ai 中,@agent.tool 装饰器自动从函数签名推断 tool schema,框架层保证一致性。
三个维度的类型安全
| 维度 | 机制 | 效果 |
|---|---|---|
| 输入安全 | tool schema 自动推断 | LLM 调用 tool 时参数自动校验 |
| 输出安全 | result_type |
Agent 最终输出强制符合类型 |
| 传递安全 | frozen=True |
模块间传递不可篡改 |
零成本起步配置
model_config = {
"strict": True,
"extra": "forbid",
"frozen": True,
}