简体中文
钩子
每个智能体都持有一个 Hooks 对象。每个钩子都是回调的注册表,按注册顺序调用;回调会被包装,抛异常的处理器会被静默吞掉而不会破坏运行 ——失败是无声的,若要看到它请在处理器内部自行记录(CancelledError / Ctrl-C 仍会向上传播)。
python
from xun import Agent, Hooks
hooks = Hooks()
hooks.after_initialize.add(lambda a: print("initialized:", a.agent.name))
hooks.before_tool_call.add(lambda a: print(a.tool_calls))
agent = Agent(name="HookAgent", hooks=hooks).initialize()子智能体不继承钩子 —— 子智能体得到全新的 Hooks。扩展在初始化时为每个智能体添加钩子。
添加处理器
| 调用 | 生命周期 |
|---|---|
registry.add(fn) → 签名 | 常驻,每次发生都会触发;返回的签名可用于再次移除 |
registry.add_once(fn) → 签名 | 首次调用后移除(例如图片工具的步骤清理就是这样用的) |
registry.remove(signature) | 按注册时返回的签名移除回调;若它已经触发或已被移除,则什么都不做 |
registry.invoke(args) | 框架调用的入口;你想自己触发钩子时也可以用它。在钩子触发过程中注册的一次性回调留到下一次触发;若本次触发被取消打断,本批尚未执行的一次性回调会被消费掉而不再运行。 |
处理器接收一个 dataclass 参数,可以就地修改它 —— 这才是主要的作用机制,而不是返回值。
钩子点
| 钩子 | 参数 | 说明 |
|---|---|---|
run_start / run_end | RunArgs(agent) | 只在真正的 空闲 → 运行 → 空闲 转换时触发,不含嵌套作用域;run_end 对成功、出错与取消都会触发。 |
after_initialize | AfterInitializeArgs(agent) | 扩展、工具与命令都已就位。 |
before_execution | BeforeExecutionArgs(agent, schema, max_iterations, context_value, takeover_result) | 每次 execute() 触发一次,在首次模型调用之前。见下文的接管。 |
before_execution_step | BeforeExecutionStepArgs(agent) | 每次循环迭代,在模型调用之前;自动压缩器挂在这里。 |
after_execution_step | AfterExecutionStepArgs(agent, should_continue) | 工具结果写入会话之后、下一次模型调用之前。把 should_continue 改为 False 会就此结束本次运行 —— 见下文。 |
before_tool_call | BeforeToolCallArgs(agent, tool_calls) | tool_calls 可编辑 —— 可改写参数、丢弃调用。 |
after_tool_call | AfterToolCallArgs(agent, tool_results) | (tool_id, result) 对,可编辑。 |
before_command / after_command | CommandArgs(agent, command, arguments) | 在命令解析完成之后触发(未知名称不会触发);arguments 可编辑。 |
model_text_delta / model_reasoning_delta | TextDelta(agent, model_call_id, content) | 在流式增量生效之前调用;改写 content 会改变被记录与被显示的内容。 |
completion_token_update | TokenMetrics(model_call_id, completion_tokens, prompt_tokens, total_tokens, prompt_tokens_cached) | 每次模型调用触发,用于统计。 |
before_display_info / before_display_warning / before_display_error | AgentMessageArgs(agent, message) | 脱敏或改写智能体的消息;修改 message 会改变用户看到的内容。 |
before_finalize | BeforeFinalizeArgs(agent) | 在此释放资源 —— 显示层此时仍然绑定。 |
提前结束运行
after_execution_step 决定是否继续循环。把 should_continue 置为 False 会当场结束运行, 并把最后一条模型消息作为答案(带 schema 时同样会校验):
python
def budget_cap(args):
if (args.agent.conversation.total_tokens or 0) > 200_000:
args.should_continue = False # 就地停止,就用现有结果
agent.hooks.after_execution_step.add(budget_cap)接管一次运行
before_execution 可以替换整个执行循环:
python
def short_circuit(args):
if args.max_iterations < 0:
args.takeover_result = "cancelled by policy"
agent.hooks.before_execution.add(short_circuit)只要设置了 takeover_result,循环就被完全跳过:不调用模型,循环内不再触发其他钩子或事件,并且不写入会话历史。若本次执行带有 schema,字符串会按该 schema 校验 —— 不合法的接管会让本次运行失败。
对缓存、回放与测试而言,这是开销最小的拦截点:模拟的模型提供方就是一个返回预设答案的 before_execution 处理器。