找回密码
 立即注册
首页 业界区 业界 Spring AI Alibaba 项目源码学习(六)-Agent Framework ...

Spring AI Alibaba 项目源码学习(六)-Agent Framework 工作原理与使用

溥价 2025-11-14 22:40:05
Agent Framework 工作原理与使用

请关注微信公众号:阿呆-bot
概述

Spring AI Alibaba Agent Framework 是一个基于 ReAct(Reasoning + Acting)模式的智能 Agent 开发框架,为 Java 开发者提供了快速构建、编排和部署 AI Agent 的能力。该框架构建在 Graph Runtime 之上,支持多 Agent 编排、上下文工程等核心特性。
整体架构

Agent Framework 采用分层架构设计:

  • Agent 基类层:Agent 提供所有 Agent 的通用能力
  • BaseAgent 抽象层:BaseAgent 提供输入输出管理和节点转换能力
  • 具体实现层

    • ReactAgent:实现 ReAct 模式的单 Agent
    • FlowAgent 系列:实现多 Agent 编排(Sequential、Parallel、Loop、Routing)
    • A2aRemoteAgent:实现 Agent-to-Agent 远程调用

  • 扩展机制层

    • Hook:在 Agent 执行的关键点插入自定义逻辑
    • Interceptor:拦截和修改模型调用、工具调用
    • Tool:扩展 Agent 的能力

工作原理

ReAct 模式

ReactAgent 实现了经典的 ReAct(Reasoning + Acting)模式:

  • Reasoning(推理):LLM 节点分析当前状态,决定下一步行动
  • Acting(行动):根据决策执行工具调用
  • Observing(观察):收集工具执行结果,更新状态
  • 循环:重复上述过程,直到达到终止条件
Graph 执行流程

Agent Framework 基于 Graph Runtime 执行:
  1. public abstract class Agent {
  2.         /** The agent's name. Must be a unique identifier within the graph. */
  3.         protected String name;
  4.         /**
  5.          * One line description about the agent's capability. The system can use this for
  6.          * decision-making when delegating control to different agents.
  7.          */
  8.         protected String description;
  9.         protected CompileConfig compileConfig;
  10.         protected volatile CompiledGraph compiledGraph;
  11.         protected volatile StateGraph graph;
  12.         /**
  13.          * Protected constructor for initializing all base agent properties.
  14.          * @param name the unique name of the agent
  15.          * @param description the description of the agent's capability
  16.          */
  17.         protected Agent(String name, String description) throws GraphStateException {
  18.                 this.name = name;
  19.                 this.description = description;
  20.         }
  21.         /**
  22.          * Default protected constructor for subclasses that need to initialize properties
  23.          * differently.
  24.          */
  25.         protected Agent() {
  26.                 // Allow subclasses to initialize properties through other means
  27.         }
  28.         /**
  29.          * Gets the agent's unique name.
  30.          * @return the unique name of the agent.
  31.          */
  32.         public String name() {
  33.                 return name;
  34.         }
  35.         /**
  36.          * Gets the one-line description of the agent's capability.
  37.          * @return the description of the agent.
  38.          */
  39.         public String description() {
  40.                 return description;
  41.         }
  42.         public StateGraph getGraph() {
  43.                 if (this.graph == null) {
  44.                         try {
  45.                                 this.graph = initGraph();
  46.                         }
  47.                         catch (GraphStateException e) {
  48.                                 throw new RuntimeException(e);
  49.                         }
  50.                 }
  51.                 return this.graph;
  52.         }
  53.         public synchronized CompiledGraph getAndCompileGraph() {
  54.                 if (compiledGraph != null) {
  55.                         return compiledGraph;
  56.                 }
  57.                 StateGraph graph = getGraph();
  58.                 try {
  59.                         if (this.compileConfig == null) {
  60.                                 this.compiledGraph = graph.compile();
  61.                         }
  62.                         else {
  63.                                 this.compiledGraph = graph.compile(this.compileConfig);
  64.                         }
  65.                 } catch (GraphStateException e) {
  66.                         throw new RuntimeException(e);
  67.                 }
  68.                 return this.compiledGraph;
  69.         }
复制代码
执行流程

  • 初始化 Graph:调用 initGraph() 创建状态图
  • 编译 Graph:将状态图编译为可执行的 CompiledGraph
  • 执行 Graph:通过 invoke() 或 stream() 方法执行
  • 状态管理:使用 OverAllState 在节点间传递数据
使用示例

ReactAgent 基本使用
  1. // 1. 创建 ReactAgent Builder
  2. ReactAgent agent = ReactAgent.builder()
  3.     .name("assistant")
  4.     .description("A helpful assistant")
  5.     .instruction("You are a helpful assistant.")
  6.     .chatModel(chatModel)  // 设置 LLM 模型
  7.     .tools(tools)          // 设置工具列表
  8.     .maxIterations(10)     // 设置最大迭代次数
  9.     .build();
  10. // 2. 同步调用
  11. AssistantMessage response = agent.call("What's the weather today?");
  12. // 3. 流式调用
  13. Flux<NodeOutput> stream = agent.stream("Tell me a story");
  14. stream.subscribe(output -> {
  15.     // 处理流式输出
  16. });
复制代码
FlowAgent 使用示例
  1. // 1. 创建 SequentialAgent(顺序执行)
  2. SequentialAgent sequentialAgent = SequentialAgent.builder()
  3.     .name("sequential")
  4.     .agents(agent1, agent2, agent3)
  5.     .build();
  6. // 2. 创建 ParallelAgent(并行执行)
  7. ParallelAgent parallelAgent = ParallelAgent.builder()
  8.     .name("parallel")
  9.     .agents(agent1, agent2, agent3)
  10.     .build();
  11. // 3. 创建 LoopAgent(循环执行)
  12. LoopAgent loopAgent = LoopAgent.builder()
  13.     .name("loop")
  14.     .agent(agent)
  15.     .loopStrategy(new CountLoopStrategy(5))
  16.     .build();
  17. // 4. 创建 RoutingAgent(路由选择)
  18. LlmRoutingAgent routingAgent = LlmRoutingAgent.builder()
  19.     .name("routing")
  20.     .agents(agent1, agent2, agent3)
  21.     .chatModel(chatModel)
  22.     .build();
复制代码
Hook 使用示例
  1. // 创建 HumanInTheLoop Hook
  2. HumanInTheLoopHook hook = HumanInTheLoopHook.builder()
  3.     .name("human-feedback")
  4.     .interactionHandler(new ConsoleInteractionHandler())
  5.     .build();
  6. // 添加到 ReactAgent
  7. ReactAgent agent = ReactAgent.builder()
  8.     .name("assistant")
  9.     .chatModel(chatModel)
  10.     .tools(tools)
  11.     .hooks(hook)  // 添加 Hook
  12.     .build();
复制代码
Interceptor 使用示例
  1. // 创建 Model Fallback Interceptor
  2. ModelFallbackInterceptor fallbackInterceptor = ModelFallbackInterceptor.builder()
  3.     .primaryModel(primaryModel)
  4.     .fallbackModel(fallbackModel)
  5.     .build();
  6. // 创建 Tool Retry Interceptor
  7. ToolRetryInterceptor retryInterceptor = ToolRetryInterceptor.builder()
  8.     .maxRetries(3)
  9.     .build();
  10. // 添加到 ReactAgent
  11. ReactAgent agent = ReactAgent.builder()
  12.     .name("assistant")
  13.     .chatModel(chatModel)
  14.     .tools(tools)
  15.     .modelInterceptors(fallbackInterceptor)  // 添加 Model Interceptor
  16.     .toolInterceptors(retryInterceptor)     // 添加 Tool Interceptor
  17.     .build();
复制代码
Tool 扩展示例
  1. // 1. 实现自定义 Tool
  2. @Bean
  3. public Function<String, String> weatherTool() {
  4.     return (location) -> {
  5.         // 调用天气 API
  6.         return "Sunny, 25°C";
  7.     };
  8. }
  9. // 2. 注册为 Spring AI Tool
  10. @Bean
  11. public Tool weatherToolBean() {
  12.     return Tool.builder()
  13.         .name("get_weather")
  14.         .description("Get weather for a location")
  15.         .function("weatherTool")
  16.         .build();
  17. }
  18. // 3. 在 ReactAgent 中使用
  19. ReactAgent agent = ReactAgent.builder()
  20.     .name("assistant")
  21.     .chatModel(chatModel)
  22.     .tools(weatherToolBean)  // 使用自定义工具
  23.     .build();
复制代码
核心特性

1. Context Engineering(上下文工程)

Agent Framework 自动管理对话上下文:

  • 自动维护消息历史
  • 支持多轮对话
  • 智能上下文压缩
2. Human In The Loop

通过 HumanInTheLoopHook 实现:

  • 在执行关键步骤前暂停
  • 等待人工确认或输入
  • 支持继续或中断执行
3. Multi-Agent Orchestration(多 Agent 编排)

支持多种编排模式:

  • Sequential:顺序执行多个 Agent
  • Parallel:并行执行多个 Agent
  • Loop:循环执行 Agent
  • Routing:根据条件路由到不同 Agent
4. A2A(Agent-to-Agent)

支持 Agent 之间的远程调用:

  • 通过 A2aRemoteAgent 实现
  • 支持分布式 Agent 部署
  • 支持 Agent 发现和注册
最佳实践

1. Agent 设计原则


  • 单一职责:每个 Agent 专注于特定任务
  • 清晰描述:提供准确的 description 帮助路由选择
  • 合理迭代:设置合适的 maxIterations 避免无限循环
2. Tool 设计建议


  • 工具粒度:保持工具功能单一、明确
  • 错误处理:工具应妥善处理异常情况
  • 文档完善:提供清晰的工具描述和参数说明
3. Hook 使用场景


  • HumanInTheLoopHook:需要人工审核的场景
  • PIIDetectionHook:敏感信息检测和处理
  • ModelCallLimitHook:控制模型调用成本
4. Interceptor 使用场景


  • ModelFallbackInterceptor:提高系统可用性
  • ToolRetryInterceptor:提高工具调用成功率
  • ContextEditingInterceptor:动态调整上下文
注意事项


  • 状态管理:理解 OverAllState 的键策略,避免状态覆盖
  • 异步执行:使用 stream() 方法实现流式响应
  • 错误处理:合理处理 GraphRunnerException 和工具调用异常
  • 性能优化:合理设置 maxIterations 和工具超时时间
  • 资源清理:及时释放 Graph 和 CompiledGraph 资源
总结

Spring AI Alibaba Agent Framework 提供了一个完整、灵活的 Agent 开发框架,通过 ReAct 模式、Graph Runtime 和丰富的扩展机制,使开发者能够快速构建智能 Agent 应用。框架的核心优势在于:

  • 易用性:简洁的 Builder API,快速上手
  • 灵活性:支持多种 Agent 类型和编排模式
  • 可扩展性:通过 Hook、Interceptor、Tool 机制轻松扩展
  • 生产就绪:完善的错误处理和状态管理
通过合理使用框架提供的各种能力,开发者可以构建出功能强大、稳定可靠的 AI Agent 应用。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

2025-11-27 17:15:31

举报

您需要登录后才可以回帖 登录 | 立即注册