Hooks 和 Interceptors
让开发者在每个步骤控制和自定义 Agent 执行。
Hooks 和 Interceptors 提供了一种更精细控制 Agent 内部行为的方式。
核心 Agent 循环涉及调用模型、让其选择要执行的工具,直到不需要调用工具时完成。
Hooks 和 Interceptors 在这些步骤的前后暴露了钩子点,允许你:
- 监控: 通过日志、分析和调试跟踪 Agent 行为;
- 修改: 转换提示、工具选择和输出格式;
- 控制: 添加重试、回退和提前终止逻辑;
- 强制执行: 应用速率限制、护栏和 PII 检测。
通过将它们传递给 ReactAgent.builder() 来添加 Hooks 和 Interceptors:
添加 Hooks 和 Interceptors 到 ReactAgent查看完整代码
import com.alibaba.cloud.ai.graph.agent.ReactAgent;
import com.alibaba.cloud.ai.graph.agent.hook.*;
import com.alibaba.cloud.ai.graph.agent.interceptor.*;
ReactAgent agent = ReactAgent.builder()
.name("my_agent")
.model(chatModel)
.tools(tools)
.hooks(loggingHook, messageTrimmingHook)
.interceptors(guardrailInterceptor, retryInterceptor)
.build();
Hooks 和 Interceptors 能做什么?
-
监控:使用日志、分析和调试跟踪 Agent 行为;
-
修改:转换提示、工具选择和输出格式;
-
控制:添加重试、回退和提前终止逻辑;
-
强制执行:应用速率限制、护栏和 PII 检测。
内置实现
Spring AI Alibaba 为常见用例提供了预构建的 Hooks 和 Interceptors 实现:
消息压缩(Summarization)
当接近 token 限制时自动压缩对话历史。
适用场景:
- 超出上下文窗口的长期对话;
- 具有大量历史记录的多轮对话;
- 需要保留完整对话上下文的应用程序。
SummarizationHook 消息压缩示例查看完整代码
import com.alibaba.cloud.ai.graph.agent.hook.summarization.SummarizationHook;
// 创建消息压缩 Hook
SummarizationHook summarizationHook = SummarizationHook.builder()
.model(chatModel)
.maxTokensBeforeSummary(4000)
.messagesToKeep(20)
.build();
// 使用
ReactAgent agent = ReactAgent.builder()
.name("my_agent")
.model(chatModel)
.hooks(summarizationHook)
.build();
配置选项:
model: 用于生成摘要的 ChatModel;maxTokensBeforeSummary: 触发摘要之前的最大 token 数;messagesToKeep: 摘要后保留的最 新消息数。
Human-in-the-Loop(人机协同)
暂停 Agent 执行以获得人工批准、编辑或拒绝工具调用。
适用场景:
- 需要人工批准的高风险操作(数据库写入、金融交易);
- 人工监督是强制性的合规工作流程;
- 长期对话,使用人工反馈引导 Agent。
HumanInTheLoopHook 人机协同示例查看完整代码
import com.alibaba.cloud.ai.graph.agent.hook.hip.HumanInTheLoopHook;
import com.alibaba.cloud.ai.graph.agent.hook.hip.ToolConfig;
// 创建 Human-in-the-Loop Hook
HumanInTheLoopHook humanReviewHook = HumanInTheLoopHook.builder()
.approvalOn("sendEmailTool", ToolConfig.builder().description("Please confirm sending the email.").build())
.approvalOn("deleteDataTool")
.build();
ReactAgent agent = ReactAgent.builder()
.name("supervised_agent")
.model(chatModel)
.tools(sendEmailTool, deleteDataTool)
.hooks(humanReviewHook)
.saver(new RedisSaver())
.build();