AI项目博客
记录 AI 工程实践与大模型应用

Spring AI Alibaba 43|多智能体编排 · 交接(Handoffs):自定义(Customized)

Spring AI Alibaba 提供了 FlowAgent 抽象类,允许你创建自定义的Agent工作流模式。通过继承 FlowAgent 并实现特定的图构建逻辑,你可以实现任何复杂的多Agent协作模式。

FlowAgent 架构

FlowAgent 是所有流程型Agent(如 SequentialAgent、ParallelAgent、LlmRoutingAgent)的基类,它提供了以下核心能力:

public abstract class FlowAgent extends Agent {

  protected List<Agent> subAgents;  // 子Agent列表
  protected CompileConfig compileConfig;  // 编译配置

  // 核心抽象方法:子类必须实现具体的图构建逻辑
  protected abstract StateGraph buildSpecificGraph(
      FlowGraphBuilder.FlowGraphConfig config
  ) throws GraphStateException;

  // 提供给子类使用的工具方法
  public List<Agent> subAgents() { return this.subAgents; }
  public CompileConfig compileConfig() { return compileConfig; }
}

实现自定义FlowAgent

下面展示如何创建一个自定义的 ConditionalAgent,它根据条件选择不同的Agent分支:

import com.alibaba.cloud.ai.graph.agent.flow.agent.FlowAgent;
import com.alibaba.cloud.ai.graph.agent.flow.builder.FlowAgentBuilder;
import com.alibaba.cloud.ai.graph.agent.flow.builder.FlowGraphBuilder;
import com.alibaba.cloud.ai.graph.StateGraph;
import com.alibaba.cloud.ai.graph.CompileConfig;
import com.alibaba.cloud.ai.graph.agent.Agent;

import java.util.List;
import java.util.function.Predicate;

/**
* 条件路由Agent:根据条件函数选择不同的Agent分支
*/
public class ConditionalAgent extends FlowAgent {

  private final Predicate<Map<String, Object>> condition;
  private final Agent trueAgent;
  private final Agent falseAgent;

  protected ConditionalAgent(ConditionalAgentBuilder builder) throws GraphStateException {
      super(builder.name, builder.description, builder.compileConfig,
            List.of(builder.trueAgent, builder.falseAgent));
      this.condition = builder.condition;
      this.trueAgent = builder.trueAgent;
      this.falseAgent = builder.falseAgent;
  }

  @Override
  protected StateGraph buildSpecificGraph(FlowGraphBuilder.FlowGraphConfig config)
          throws GraphStateException {
      // 使用 FlowGraphBuilder 构建自定义图结构
      return FlowGraphBuilder.buildConditionalGraph(
          config,
          this.condition,
          this.trueAgent,
          this.falseAgent
      );
  }

  public static ConditionalAgentBuilder builder() {
      return new ConditionalAgentBuilder();
  }

  /**
   * Builder for ConditionalAgent
   */
  public static class ConditionalAgentBuilder
          extends FlowAgentBuilder<ConditionalAgent, ConditionalAgentBuilder> {

      private Predicate<Map<String, Object>> condition;
      private Agent trueAgent;
      private Agent falseAgent;

      public ConditionalAgentBuilder condition(Predicate<Map<String, Object>> condition) {
          this.condition = condition;
          return this;
      }

      public ConditionalAgentBuilder trueAgent(Agent trueAgent) {
          this.trueAgent = trueAgent;
          return this;
      }

      public ConditionalAgentBuilder falseAgent(Agent falseAgent) {
          this.falseAgent = falseAgent;
          return this;
      }

      @Override
      public ConditionalAgent build() throws GraphStateException {
          if (condition == null || trueAgent == null || falseAgent == null) {
              throw new IllegalStateException(
                  "Condition, trueAgent and falseAgent must be set");
          }
          return new ConditionalAgent(this);
      }

      @Override
      protected ConditionalAgentBuilder self() {
          return this;
      }
  }
}

使用自定义Agent

import com.alibaba.cloud.ai.graph.agent.ReactAgent;
import java.util.Map;

// 创建两个分支Agent
ReactAgent urgentAgent = ReactAgent.builder()
  .name("urgent_handler")
  .model(chatModel)
  .description("处理紧急请求")
  .instruction("你需要快速响应紧急情况...")
  .outputKey("urgent_result")
  .build();

ReactAgent normalAgent = ReactAgent.builder()
  .name("normal_handler")
  .model(chatModel)
  .description("处理常规请求")
  .instruction("你可以详细分析和处理常规请求...")
  .outputKey("normal_result")
  .build();

// 定义条件:检查输入是否包含"紧急"关键字
Predicate<Map<String, Object>> isUrgent = state -> {
  Object input = state.get("input");
  if (input instanceof String) {
      return ((String) input).contains("紧急") || ((String) input).contains("urgent");
  }
  return false;
};

// 创建条件路由Agent
ConditionalAgent conditionalAgent = ConditionalAgent.builder()
  .name("priority_router")
  .description("根据紧急程度路由请求")
  .condition(isUrgent) 
  .trueAgent(urgentAgent) 
  .falseAgent(normalAgent) 
  .build();

// 使用
Optional<OverAllState> result1 = conditionalAgent.invoke("这是一个紧急问题需要立即处理");
// 会路由到 urgentAgent

Optional<OverAllState> result2 = conditionalAgent.invoke("请帮我分析一下这个问题");
// 会路由到 normalAgent

实现复杂的循环Agent

你还可以创建更复杂的自定义Agent,例如带有循环逻辑的 LoopAgent:

/**
* 循环Agent:重复执行直到满足退出条件
*/
public class CustomLoopAgent extends FlowAgent {

  private final Predicate<Map<String, Object>> exitCondition;
  private final int maxIterations;

  protected CustomLoopAgent(CustomLoopAgentBuilder builder)
          throws GraphStateException {
      super(builder.name, builder.description, builder.compileConfig, builder.subAgents);
      this.exitCondition = builder.exitCondition;
      this.maxIterations = builder.maxIterations;
  }

  @Override
  protected StateGraph buildSpecificGraph(FlowGraphBuilder.FlowGraphConfig config)
          throws GraphStateException {
      // 构建带有循环逻辑的图
      return FlowGraphBuilder.buildLoopGraph(
          config,
          this.exitCondition,
          this.maxIterations
      );
  }

  // Builder implementation...
}

// 使用示例
CustomLoopAgent refinementAgent = CustomLoopAgent.builder()
  .name("iterative_refinement")
  .subAgents(List.of(drafterAgent, reviewerAgent))
  .exitCondition(state -> {
      // 当质量分数 >= 8 时退出循环
      Object score = state.get("quality_score");
      return score != null && (int) score >= 8;
  })
  .maxIterations(5) // 最多循环5次
  .build();

关键要点

扩展 FlowAgent 时需要注意:

  1. 实现 buildSpecificGraph:这是核心方法,定义了Agent的工作流逻辑
  2. 使用 FlowGraphBuilder:提供了构建图的工具方法
  3. 继承 FlowAgentBuilder:保持一致的构建器模式
  4. 管理子Agent:通过 subAgents 列表管理所有子Agent
  5. 状态传递:通过 StateGraph 控制状态在Agent之间的流动

通过自定义 FlowAgent,你可以实现任意复杂的多Agent协作模式,满足各种业务场景需求。

本文整理自 Spring AI Alibaba 官方文档《多智能体编排》:https://java2ai.com/docs/frameworks/agent-framework/advanced/multi-agent

赞(0)
未经允许不得转载:AI项目博客 » Spring AI Alibaba 43|多智能体编排 · 交接(Handoffs):自定义(Customized)

评论 抢沙发

AI项目博客

专注 AI 工程化落地 —— 覆盖智能体、大模型、Java AI 与 Python 的学习笔记,以及 AI 平台的项目实战记录。

关于本站文章归档

登录

找回密码

注册