L4 策略层:管控是声明位,不是散落的 if¶
这一层回答「一次 run 里允许做什么、做到什么程度」。四种策略全部声明在 Agent 上,
由 Runner 在固定接缝执行——新增策略不改循环体。
Agent(
name="ops",
instructions="...",
model=model,
tools=[...],
hooks=[PermissionHook(["read_*", "search_docs"])], # 工具级权限
guardrails=[PromptInjectionGuardrail()], # 输入 / 输出内容
output_type=Ticket, # 结构化输出
context_policy=ContextPolicy(compact_threshold=0.8), # 上下文压缩
)
1. Hook:工具调用前后的三态裁决¶
Hook 是一个 Protocol,只有两个方法:
class Hook(Protocol):
name: str
async def pre_tool_use(self, call, ctx) -> HookVerdict: ...
async def post_tool_use(self, call, result, ctx) -> None: ...
HookVerdict.action 三态:
| 裁决 | 结果 |
|---|---|
allow |
正常执行 |
deny |
转 is_error=True 的工具结果回填,模型可改道重试 |
require_approval |
run 挂起为 pending,等人裁决(见 HITL) |
多 Hook 聚合:按声明序执行,deny 短路;优先级 deny > require_approval > allow。
Hook 自身抛异常按 deny 处理——策略不能因为一个钩子崩溃就静默失效。每次裁决落
hook 事件(带 call_id,审计能答「哪个调用被哪个 Hook 拦」)。
内置 PermissionHook 做工具白名单(精确名 + * / ? 通配符,未命中一律 deny);
它也可以直接通过 Agent.allowed_tools 声明。
2. Guardrail:输入 / 输出内容检查¶
InputGuardrail在用户输入进入模型前检查;OutputGuardrail在模型产出进入工具 / 会话前检查;- 同类护栏并行执行,fail-fast:首个 deny 立即取消其余在途检查;
- 护栏抛异常按 deny 处理;护栏不使用
require_approval(HITL 挂起点只在工具执行前); - 事件落
guardrail(带phase="input" / "output"),与hook事件分流; - 开箱可用的
PromptInjectionGuardrail用特征串匹配,确定性强、零额外成本。
护栏只能拒绝,不能改写内容(v1 边界):需要「改了再放行」时用 deny + reason 让模型改道自愈。
3. 结构化输出:声明 pydantic 模型即可¶
class Ticket(BaseModel):
title: str
priority: Literal["P0", "P1", "P2"]
summary: str
agent = Agent(..., output_type=Ticket)
result = runner.run_sync(agent, "...")
result.output # Ticket 实例(已校验)
- 策略由
ModelProfile.supports_json自动分派(原生 schema → prompt + 校验重试 → 工具折叠), 用户不需要知道自己落在哪一档; - 只约束终答:中间轮带工具调用时原样透传,不校验也不折叠;
- 校验失败带错误明细重试(≤2 次),每次重试的真实用量都计入
Usage,事件可见; - 流式模式下不重试:已推出的半个答案撤不回来,收尾校验一次、失败上抛。
4. 上下文压缩:默认关闭,两个开关¶
ContextPolicy(
compact_threshold=0.8, # 窗口占用 ≥80% 触发
keep_recent_turns=2, # 最近 N 轮保留原文
tool_result_max_chars=8000,
)
Agent.context_policy=None= 不压缩;yamlagent.context.enabled: false是运维止血开关;- 压缩只作用于本次请求视图,会话原文一字不改——每步从原文重算,换模型 / 崩溃恢复不会被 一份早期摘要锁死;
- 便宜的先做:先截断超长工具结果(头部 + 尾部 + 句柄),仍超阈值才摘要旧轮次;
- 压缩动作发
context_compact事件(before_tokens/after_tokens),trace 可复盘。
顺序关系¶
护栏与 Hook 是两套通道:内容检查走 guardrail 事件,工具权限走 hook 事件。