图片预览

滚轮缩放 · 拖动移动 · Esc 关闭

Skip to content

PlanExecutionNode 子工作流重构 ​

📋 重构概述 ​

将 PlanExecutionNode 中的 switch-case 硬编码逻辑重构为基于 LangGraph4j 的子工作流架构,使用 LLM 智能路由替代硬编码判断。

重构日期: 2026-01-24 状态: ✅ 已完成并编译通过 重构人员: Claude Opus 4.5


🎯 问题背景 ​

原有架构的问题 ​

  1. 硬编码路由逻辑: 使用 switch-case 判断 action Type,缺乏灵活性
  2. 默认值问题: actionType 默认为 llm_generate,即使任务需要RAG检索
  3. 智能修正局限: PlanningNode 的智能修正只能修复格式问题,无法动态调整执行路径
  4. 扩展性差: 新增执行类型需要修改核心代码
  5. 可测试性低: 各执行逻辑耦合在一个类中,难以独立测试

用户反馈 ​

用户输入:"帮我查看知识库中招标文件中的甲方是谁"

意图识别: ✅ 正确识别需要RAG
任务规划: ✅ 生成执行步骤
任务执行: ❌ 路由到 llm_generate,而不是 agentic_rag

即使意图识别和规划都正确,执行节点仍然使用默认的 llm_generate。


🏗️ 重构方案 ​

核心思想 ​

使用 LangGraph4j 子工作流 + LLM 智能路由,替代硬编码的 switch-case 逻辑。

架构设计 ​

PlanExecutionNode (重构版)
    ↓
启动子工作流 (TaskExecutionWorkflow)
    ↓
START → ActionRouterNode (LLM 智能判断) → 条件路由:
         ├─> AgenticRagNode      (智能RAG)
         ├─> RagQueryNode        (简单RAG)
         ├─> ToolCallNode        (工具调用)
         ├─> SubAgentCallNode    (子Agent)
         ├─> LlmGenerateNode     (LLM生成)
         ├─> McpCallNode         (MCP调用)
         └─> AggregateNode       (结果聚合)
              ↓
            END
    ↓
返回执行结果给 PlanExecutionNode

📁 新增文件结构 ​

1. 执行节点 (node/execution/) ​

文件职责状态
ActionRouterNode.javaLLM 智能路由,判断执行方式✅ 新增
AgenticRagNode.java执行 Agentic RAG 检索✅ 新增
RagQueryNode.java执行简单 RAG 检索✅ 新增
ToolCallNode.java执行工具调用✅ 新增
SubAgentCallNode.java执行子 Agent 调用✅ 新增
LlmGenerateNode.java执行 LLM 生成✅ 新增
McpCallNode.java执行 MCP 调用 (待实现)✅ 新增
AggregateNode.java聚合执行结果✅ 新增

2. 子工作流构建器 (workflow/) ​

文件职责状态
TaskExecutionWorkflow.java构建任务执行子工作流✅ 新增

3. 修改的文件 ​

文件修改内容状态
ChatbotAgentState.java新增子工作流状态字段✅ 修改
PlanExecutionNode.java重构为使用子工作流✅ 重构

🔧 关键实现 ​

1. ActionRouterNode - LLM 智能路由 ​

核心功能 ​

使用 LLM 分析任务上下文,智能判断应该使用哪种执行方式:

  • 输入: 任务名称、描述、用户问题、意图分析、可用资源
  • 输出: 推荐的动作类型 + 理由

路由提示词 ​

你是一个任务执行路由器。根据以下信息,判断当前任务应该使用哪种执行方式。

## 当前任务
- **名称**: {taskName}
- **描述**: {taskDescription}

## 用户原始问题
{userInput}

## 是否需要RAG检索
{needRag}

## 可用资源
### 知识库 (N 个)
- 知识库1 (ID: 1): 描述

### 子智能体 (N 个)
- AgenticRagAgent (ID: 10): 智能检索增强生成

## 判断规则
1. 如果涉及"知识库"、"文档"等,且有可用知识库 → agentic_rag
2. 如果需要特定工具且工具可用 → call_tool
3. 如果是简单问答 → llm_generate

请输出:
动作类型: <action_type>
理由: <reason>

默认路由逻辑 ​

当 LLM 不可用时,使用基于关键词的默认逻辑:

java
String combined = (taskName + " " + taskDescription).toLowerCase();

if (combined.contains("检索") || combined.contains("知识库") || combined.contains("文档")) {
    return "agentic_rag";
}

if (needRag && hasDatasets) {
    return "agentic_rag";
}

return "llm_generate";

验证机制 ​

路由决策后会验证可行性:

java
// 如果选择了 agentic_rag 但无可用知识库 → 降级到 llm_generate
if (actionType == ACTION_AGENTIC_RAG && datasetList.isEmpty()) {
    log.warn("选择了RAG但无可用知识库,降级到LLM生成");
    return ACTION_LLM_GENERATE;
}

2. TaskExecutionWorkflow - 子工作流构建器 ​

工作流定义 ​

java
StateGraph<ChatbotAgentState> workflow = new StateGraph<>(ChatbotAgentState.SCHEMA, ChatbotAgentState::new);

// 1. 动作路由节点
workflow.addNode(NODE_ACTION_ROUTER, node_async(actionRouterNode::apply));

// 2. 各执行节点
workflow.addNode(NODE_AGENTIC_RAG, node_async(agenticRagNode::apply));
workflow.addNode(NODE_TOOL_CALL, node_async(toolCallNode::apply));
// ... 其他节点

// 3. 路由边
workflow.addConditionalEdges(NODE_ACTION_ROUTER, edge_async(this::routeToExecutionNode),
    Map.of(
        ACTION_AGENTIC_RAG, NODE_AGENTIC_RAG,
        ACTION_CALL_TOOL, NODE_TOOL_CALL,
        ACTION_LLM_GENERATE, NODE_LLM_GENERATE,
        // ...
    ));

路由函数 ​

java
private String routeToExecutionNode(ChatbotAgentState state) {
    String actionType = state.taskAction();
    log.info("任务执行路由: actionType={}", actionType);

    // 如果为空或无效,默认使用 LLM 生成
    if (actionType == null || actionType.isEmpty()) {
        return ACTION_LLM_GENERATE;
    }

    return actionType;
}

3. ChatbotAgentState - 新增状态字段 ​

java
// ============ Task Execution Workflow Keys ============

/**
 * 当前正在执行的任务
 */
public static final String CURRENT_TASK_KEY = "currentTask";

/**
 * 任务动作类型(由 ActionRouterNode 判断)
 */
public static final String TASK_ACTION_KEY = "taskAction";

/**
 * 任务执行结果
 */
public static final String TASK_EXECUTION_RESULT_KEY = "taskExecutionResult";

/**
 * 任务路由理由
 */
public static final String TASK_ROUTER_REASON_KEY = "taskRouterReason";

Getter 方法 ​

java
public Map<String, Object> currentTask() {
    return this.<Map<String, Object>>value(CURRENT_TASK_KEY).orElse(new HashMap<>());
}

public String taskAction() {
    return this.<String>value(TASK_ACTION_KEY).orElse("");
}

public String taskExecutionResult() {
    return this.<String>value(TASK_EXECUTION_RESULT_KEY).orElse("");
}

public String taskRouterReason() {
    return this.<String>value(TASK_ROUTER_REASON_KEY).orElse("");
}

4. PlanExecutionNode - 重构版 ​

核心改变 ​

java
// ❌ 原有逻辑
private String executeTask(Map<String, Object> task, ...) {
    String actionType = (String) task.getOrDefault("actionType", TaskStep.ACTION_LLM_GENERATE);

    return switch (actionType) {
        case ACTION_CALL_TOOL -> executeToolCall(...);
        case ACTION_AGENTIC_RAG -> executeAgenticRag(...);
        // ...
        default -> executeLlmGenerate(...);
    };
}

// ✅ 新逻辑
private String executeTaskWithWorkflow(Map<String, Object> task, ChatbotAgentState state, ...) {
    // 1. 构建子工作流
    CompiledGraph<ChatbotAgentState> subGraph = taskExecutionWorkflow.build();

    // 2. 准备状态(继承主工作流)
    Map<String, Object> subInitData = new HashMap<>();
    subInitData.put(CURRENT_TASK_KEY, task);
    subInitData.put(AGENT_ID_KEY, state.agentId());
    subInitData.put(USER_INPUT_KEY, state.userInput());
    // ... 复制其他关键状态

    // 3. 执行子工作流
    Optional<ChatbotAgentState> finalStateOpt = subGraph.invoke(subInitData, config);

    // 4. 提取结果
    ChatbotAgentState finalState = finalStateOpt.get();
    String result = finalState.taskExecutionResult();
    String actionType = finalState.taskAction();
    String routerReason = finalState.taskRouterReason();

    return result;
}

状态继承 ​

子工作流继承主工作流的关键状态:

  • Agent 配置
  • 用户输入和意图
  • LLM 模型配置
  • 知识库列表
  • RAG 判断结果
  • 任务执行结果

📊 执行流程示例 ​

场景:查询知识库中的甲方信息 ​

用户输入: "帮我查看知识库中招标文件中的甲方是谁"

执行过程 ​

1. IntentRecognitionNode
   └─> 识别: needRag=true, intent="查询知识库文档"

2. PlanningNode
   └─> 生成计划:
       步骤1: "检索招标文件并识别甲方"
       原始 actionType: llm_generate (默认值)

3. PlanExecutionNode (重构版)
   ├─> 启动子工作流
   └─> TaskExecutionWorkflow
       │
       ├─> START → ActionRouterNode
       │   ├─> LLM 分析:
       │   │   - 任务名称: "检索招标文件并识别甲方"
       │   │   - 用户问题: "帮我查看知识库中..."
       │   │   - 需要RAG: true
       │   │   - 可用知识库: 招标文档知识库 (ID: 1)
       │   │
       │   └─> 判断结果:
       │       动作类型: agentic_rag
       │       理由: 任务涉及知识库检索,且用户明确提到"知识库中"
       │
       ├─> 条件路由 → AgenticRagNode
       │   ├─> 查找 AgenticRagAgent (ID: 10)
       │   ├─> 调用: executeAgent(10, "检索招标文件并识别甲方")
       │   └─> 返回结果 → taskExecutionResult
       │
       └─> END

4. PlanExecutionNode 收到结果
   └─> taskResults.add(result)

5. ReflectionNode
   └─> 评估执行结果

6. FinalResponseNode
   └─> 生成最终响应

关键日志 ​

[INFO] PlanExecutionNode - 执行任务 1/1: name=检索招标文件并识别甲方, originalActionType=llm_generate
[INFO] PlanExecutionNode - === 启动任务执行子工作流 ===
[INFO] ActionRouterNode - === 动作路由节点开始 ===
[INFO] ActionRouterNode - 动作路由结果: actionType=agentic_rag, reason=任务涉及知识库检索
[INFO] TaskExecutionWorkflow - 任务执行路由: actionType=agentic_rag
[INFO] AgenticRagNode - === Agentic RAG 执行节点开始 ===
[INFO] AgenticRagNode - 找到 Agentic RAG Agent: name=Agentic RAG智能检索增强生成智能体, id=10
[INFO] AgenticRagNode - Agentic RAG 执行成功,结果长度: 856
[INFO] PlanExecutionNode - 子工作流执行完成: actionType=agentic_rag, resultLength=856
[INFO] PlanExecutionNode - 任务执行成功: name=检索招标文件并识别甲方, resultLength=856

🎯 重构优势 ​

1. 智能路由 ​

  • ✅ 使用 LLM 动态判断,而非硬编码规则
  • ✅ 分析上下文(任务、意图、可用资源)做决策
  • ✅ 提供判断理由,便于调试
  • ✅ 有降级机制(LLM不可用时使用关键词匹配)

2. 高扩展性 ​

  • ✅ 新增执行类型只需添加新节点,无需修改核心代码
  • ✅ 各节点独立实现,符合单一职责原则
  • ✅ 子工作流模式易于组合和复用

3. 可测试性 ​

  • ✅ 每个执行节点可独立单元测试
  • ✅ ActionRouterNode 可独立测试路由逻辑
  • ✅ 子工作流可独立集成测试

4. 可观测性 ​

  • ✅ 每个节点有独立日志
  • ✅ 路由决策有详细理由记录
  • ✅ 子工作流执行过程可追踪

5. 解决原有问题 ​

原有问题重构方案效果
硬编码 switch-caseLLM 智能路由✅ 动态判断
默认值 llm_generateActionRouterNode 分析上下文✅ 准确路由
智能修正局限执行时再次判断✅ 双重保障
扩展性差节点化架构✅ 易于扩展
可测试性低各节点独立✅ 易于测试

🧪 测试建议 ​

单元测试 ​

java
@Test
void testActionRouterNode_withRagRequirement() {
    // 准备状态
    Map<String, Object> initData = new HashMap<>();
    initData.put(USER_INPUT_KEY, "查看知识库中的招标文件");
    initData.put(NEED_RAG_KEY, true);
    initData.put(CURRENT_TASK_KEY, Map.of(
        "name", "检索招标文件",
        "description", "从知识库检索招标文档"
    ));

    ChatbotAgentState state = new ChatbotAgentState(initData);

    // 执行
    Map<String, Object> updates = actionRouterNode.apply(state);

    // 验证
    assertEquals("agentic_rag", updates.get(TASK_ACTION_KEY));
    assertNotNull(updates.get(TASK_ROUTER_REASON_KEY));
}

集成测试 ​

java
@Test
void testTaskExecutionWorkflow_agenticRagPath() {
    // 构建子工作流
    CompiledGraph<ChatbotAgentState> subGraph = taskExecutionWorkflow.build();

    // 准备状态
    Map<String, Object> initData = prepareStateWithRagTask();

    // 执行
    Optional<ChatbotAgentState> finalState = subGraph.invoke(initData);

    // 验证
    assertTrue(finalState.isPresent());
    assertEquals("agentic_rag", finalState.get().taskAction());
    assertFalse(finalState.get().taskExecutionResult().isEmpty());
}

端到端测试 ​

java
@Test
void testAutoPlanningAgent_withRagQuery() {
    // 发送请求
    autoPlanningAgent.autonomousPlanning(
        agentId, userId, sessionId,
        "帮我查看知识库中招标文件中的甲方是谁",
        handler
    );

    // 验证执行路径
    verify(agenticRagAgent, times(1)).execute(any());
    verify(handler, atLeast(1)).onThinkingContent(contains("Agentic RAG"));
}

📝 部署步骤 ​

1. 编译验证 ​

bash
cd muotai-ai/muotai-ai-biz
mvn clean compile -DskipTests

预期输出:

[INFO] BUILD SUCCESS

2. 运行测试 ​

bash
mvn test -Dtest="*ActionRouter*,*TaskExecution*"

3. 重启服务 ​

bash
./restart.sh muotai-ai

4. 查看日志 ​

bash
tail -f logs/muotai-ai/info.log | grep -E "(ActionRouterNode|TaskExecutionWorkflow|agentic_rag)"

预期日志:

[INFO] ActionRouterNode - === 动作路由节点开始 ===
[INFO] ActionRouterNode - 动作路由结果: actionType=agentic_rag, reason=...
[INFO] TaskExecutionWorkflow - 任务执行路由: actionType=agentic_rag
[INFO] AgenticRagNode - === Agentic RAG 执行节点开始 ===
[INFO] AgenticRagNode - Agentic RAG 执行成功

5. 测试验证 ​

发送测试请求:

json
{
  "agentId": 1,
  "message": "帮我查看知识库中招标文件中的甲方是谁"
}

预期响应流程:

🎯 意图识别
- RAG: 需要检索知识库

📋 任务规划
- 步骤1: 检索招标文件并识别甲方

⚡ 执行任务 1/1
🔀 动作路由分析
- 任务: 检索招标文件并识别甲方
→ 路由决策: 智能RAG
→ 理由: 任务涉及知识库检索,且用户明确提到"知识库中"

🧠 Agentic RAG 智能检索
- 查询: 检索招标文件并识别甲方
📞 调用 Agentic RAG Agent (ID: 10)...
✓ Agentic RAG Agent 执行完成

✓ 任务完成

🚀 未来扩展 ​

新增执行类型 ​

如需添加新的执行类型(如数据库查询),只需:

  1. 创建新节点类 DatabaseQueryNode.java
  2. 在 TaskExecutionWorkflow 中注册节点
  3. 在 ActionRouterNode 的提示词中添加判断规则
  4. 在 TaskStep 中添加动作类型常量
java
// 1. 新节点
@Component
public class DatabaseQueryNode implements NodeAction<ChatbotAgentState> {
    @Override
    public Map<String, Object> apply(ChatbotAgentState state) {
        // 实现数据库查询逻辑
    }
}

// 2. 注册节点
workflow.addNode(NODE_DATABASE_QUERY, node_async(databaseQueryNode::apply));

// 3. 添加路由
workflow.addConditionalEdges(NODE_ACTION_ROUTER, ...,
    Map.of(
        // ... 其他路由
        ACTION_DATABASE_QUERY, NODE_DATABASE_QUERY
    ));

智能缓存 ​

可以缓存 ActionRouterNode 的路由决策,避免重复调用 LLM:

java
@Service
public class ActionRoutingCache {
    private final Cache<String, String> cache = CacheBuilder.newBuilder()
        .maximumSize(1000)
        .expireAfterWrite(1, TimeUnit.HOURS)
        .build();

    public String getOrCompute(String taskKey, Supplier<String> computer) {
        return cache.get(taskKey, computer::get);
    }
}

多轮对话优化 ​

记录历史路由决策,优化后续判断:

java
// 在状态中添加路由历史
public static final String ROUTING_HISTORY_KEY = "routingHistory";

// ActionRouterNode 中参考历史
List<Map<String, Object>> history = state.routingHistory();
if (!history.isEmpty()) {
    // 分析历史路由,优化当前决策
}

📚 相关文档 ​


🎓 技术要点总结 ​

关键设计模式 ​

  1. 子工作流模式: 将复杂逻辑封装为独立的子图
  2. 策略模式: ActionRouterNode 动态选择执行策略
  3. 责任链模式: 任务通过各节点依次处理
  4. 状态机模式: 使用 ChatbotAgentState 管理执行状态

LangGraph4j 核心概念 ​

  1. StateGraph: 状态图定义
  2. CompiledGraph: 编译后的可执行图
  3. ConditionalEdges: 条件路由边
  4. NodeAction: 节点执行动作
  5. State Channels: 状态通道(base, appender)

最佳实践 ​

  1. ✅ 使用 LLM 辅助决策,而非完全依赖
  2. ✅ 提供降级机制(默认逻辑)
  3. ✅ 详细日志记录,便于调试
  4. ✅ 状态继承,避免重复传递
  5. ✅ 节点独立化,易于测试和维护

创建时间: 2026-01-24 版本: 1.0.0 状态: ✅ 已完成并编译通过 重构人员: Claude Opus 4.5