Hooks 和 Interceptors
让开发者在每个步骤控制和自定义 Agent 执行
Hooks 和 Interceptors 提供了一种更精细控制 Agent 内部行为的方式。
核心 Agent 循环涉及调用模型、让其选择要执行的工具,直到不需要调用工具时完成。
Hooks 和 Interceptors 在这些步骤的前后暴露了钩子点,允许你:
- 监控: 通过日志、分析和调试跟踪 Agent 行为
- 修改: 转换提示、工具选择和输出格式
- 控制: 添加重试、回退和提前终止逻辑
- 强制执行: 应用速率限制、护栏和 PII 检测
通过将它们传递给 ReactAgent.builder() 来添加 Hooks 和 Interceptors:
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 限制时自动压缩对话历史。
适用场景:
- 超出上下文窗口的长期对话
- 具有大量历史记录的多轮对话
- 需要保留完整对话上下文的应用程序
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: 用于生成摘要的 ChatModelmaxTokensBeforeSummary: 触发摘要之前的最大 token 数messagesToKeep: 摘要后保留的 最新消息数
Human-in-the-Loop(人机协同)
暂停 Agent 执行以获得人工批准、编辑或拒绝工具调用。
适用场景:
- 需要人工批准的高风险操作(数据库写入、金融交易)
- 人工监督是强制性的合规工作流程
- 长期对话,使用人工反馈引导 Agent
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();
重要提示:Human-in-the-loop Hook 需要 checkpointer 来维护跨中断的状态。示例中我们演示用了 RedisSaver。
模型调用限制(Model Call Limit)
限制模型调用次数以防止无限循环或过度成本。
适用场景:
- 防止失控的 Agent 进行太多 API 调用
- 在生产部署中强制执行成本控制
- 在特定调用预算内测试 Agent 行为
ReactAgent agent = ReactAgent.builder()
.name("my_agent")
.model(chatModel)
.maxIterations(10) // 最多 10 次迭代(默认为 10)
.saver(new MemorySaver())
.build();
工具调用限制(Tool Call Limit)
使用自定义停止条件限制工具调用:
import com.alibaba.cloud.ai.graph.OverAllState;
import java.util.function.Function;
Function<OverAllState, Boolean> customStopCondition = state -> {
// 如果找到答案或错误过多则停止
Optional<Object> foundAnswer = state.value("answer_found");
if (foundAnswer.isPresent() && (Boolean) foundAnswer.get()) {
return false; // 停止执行
}
Optional<Object> errorCount = state.value("error_count");
if (errorCount.isPresent() && (Integer) errorCount.get() > 3) {
return false; // 停止执行
}
return true; // 继续执行
};
ReactAgent agent = ReactAgent.builder()
.name("controlled_agent")
.model(chatModel)
.shouldContinueFunction(customStopCondition)
.saver(new MemorySaver())
.build();
PII 检测(Personally Identifiable Information)
检测和处理对话中的个人身份信息。
适用场景:
- 具有合规要求的医疗保健和金融应用
- 需要清理日志的客户服务 Agent
- 任何处理敏感用户数据的应用程序
import com.alibaba.cloud.ai.graph.agent.interceptor.PIIDetectionInterceptor;
// 使用
ReactAgent agent = ReactAgent.builder()
.name("secure_agent")
.model(chatModel)
.modelInterceptors(new PIIDetectionInterceptor())
.build();