图片预览

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

Skip to content

AgentNode V1 修正方案 ​

修正说明 ​

原问题:

  • ❌ 调用 terminateInstance 终止流程
  • ❌ 硬编码 InstanceStatus.PASS

修正目标:

  • ✅ 根据 AI 返回结果设置流程变量
  • ✅ 调用 leave(execution) 继续流程
  • ✅ 支持通过/驳回两种结果

修正后的 AgentBehavior 实现 ​

文件: core/bpmn/behavior/AgentBehavior.java

java
package com.pig4cloud.pigx.wflow.core.bpmn.behavior;

import com.pig4cloud.pigx.wflow.core.bean.HandlerAction;
import com.pig4cloud.pigx.wflow.core.event.EventHandler;
import com.pig4cloud.pigx.wflow.service.AiAgentService;
import com.pig4cloud.pigx.wflow.utils.FlowContextUtil;
import com.pig4cloud.pigx.wflow.utils.SpringBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.ServiceTask;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.bpmn.behavior.AbstractBpmnActivityBehavior;
import org.flowable.engine.impl.util.ProcessDefinitionUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Agent 行为处理器(修正版)
 * 负责 AI 自动审批的执行逻辑
 *
 * @author willian fu
 * @since 2026-01-09
 */
@Slf4j
public class AgentBehavior extends AbstractBpmnActivityBehavior {

    @Override
    public void execute(DelegateExecution execution) {
        String processInstanceId = execution.getProcessInstanceId();
        String activityId = execution.getCurrentActivityId();

        log.info("Agent 节点开始执行: processInstanceId={}, activityId={}",
            processInstanceId, activityId);

        try {
            // 1. 提取预设属性值
            Map<String, Object> paramsMap = getAgentFromExecution(execution);

            // 2. 获取业务数据
            Map<String, Object> variables = execution.getVariables();

            // 3. 设置自动处理标记
            FlowContextUtil.TASK_AUTO_FLAG.set(true);

            // 4. 调用 AI 服务进行分析
            AiAgentService aiAgentService = SpringBeanUtil.getBean(AiAgentService.class);
            AiAnalysisResult result = aiAgentService.analyze(paramsMap, variables);

            // 5. 根据 AI 返回结果设置流程变量
            HandlerAction action;
            if (result.isApproved()) {
                action = HandlerAction.agree;
                execution.setVariable("approvalResult", "APPROVED");
                execution.setVariable("aiDecision", "PASS");
            } else {
                action = HandlerAction.reject;
                execution.setVariable("approvalResult", "REJECTED");
                execution.setVariable("aiDecision", "FAIL");
            }

            // 保存 AI 分析详情
            execution.setVariable("aiConfidence", result.getConfidence());
            execution.setVariable("aiReason", result.getReason());

            // 6. 触发节点离开事件
            SpringBeanUtil.getBean(EventHandler.class).nodeLeave(
                execution.getProcessInstanceId(),
                execution.getProcessDefinitionId(),
                execution.getCurrentActivityId(),
                "serviceTask"
            );

            // 7. 继续流程(关键修改!)
            leave(execution);

            log.info("Agent 节点执行完成: processInstanceId={}, decision={}",
                processInstanceId, action);

        } catch (Exception e) {
            log.error("Agent 节点执行失败: processInstanceId={}, error={}",
                processInstanceId, e.getMessage(), e);

            // 设置错误标记
            execution.setVariable("aiProcessingError", e.getMessage());
            execution.setVariable("approvalResult", "ERROR");

            // 即使出错也继续流程,由后续节点处理
            leave(execution);
        } finally {
            FlowContextUtil.TASK_AUTO_FLAG.remove();
        }
    }

    /**
     * 提取预设的属性值
     */
    private Map<String, Object> getAgentFromExecution(DelegateExecution execution) {
        String activityId = execution.getCurrentActivityId();
        String processDefinitionId = execution.getProcessDefinitionId();

        FlowElement flowElement = ProcessDefinitionUtil.getBpmnModel(processDefinitionId)
            .getFlowElement(activityId);

        return getParamsByFlowElement(flowElement);
    }

    /**
     * 提取预设值并将其组装成为Map
     */
    private static Map<String, Object> getParamsByFlowElement(FlowElement flowElement) {
        Map<String, Object> params = new HashMap<>();

        if (flowElement instanceof ServiceTask) {
            ServiceTask serviceTask = (ServiceTask) flowElement;
            Map<String, List<ExtensionElement>> extensionElements =
                serviceTask.getExtensionElements();

            extensionElements.forEach((k, v) -> {
                v.forEach(o -> {
                    String name = o.getName();
                    String text = o.getElementText();
                    params.put(name, text);
                });
            });
        }
        return params;
    }
}

AI 服务接口 ​

文件: service/AiAgentService.java

java
package com.pig4cloud.pigx.wflow.service;

import java.util.Map;

/**
 * AI Agent 服务接口
 */
public interface AiAgentService {

    /**
     * 分析审批请求
     *
     * @param aiConfig AI配置参数
     * @param businessData 业务数据
     * @return AI分析结果
     */
    AiAnalysisResult analyze(Map<String, Object> aiConfig,
                             Map<String, Object> businessData);
}

文件: service/dto/AiAnalysisResult.java

java
package com.pig4cloud.pigx.wflow.service.dto;

import lombok.Builder;
import lombok.Data;

/**
 * AI 分析结果
 */
@Data
@Builder
public class AiAnalysisResult {

    /**
     * 是否通过
     */
    private boolean approved;

    /**
     * 置信度 (0.0 - 1.0)
     */
    private Double confidence;

    /**
     * 分析原因
     */
    private String reason;

    /**
     * 详细分析结果
     */
    private Object details;
}

AI 服务实现示例 ​

文件: service/impl/AiAgentServiceImpl.java

java
package com.pig4cloud.pigx.wflow.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.pig4cloud.pigx.wflow.service.AiAgentService;
import com.pig4cloud.pigx.wflow.service.dto.AiAnalysisResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * AI Agent 服务实现
 */
@Slf4j
@Service
public class AiAgentServiceImpl implements AiAgentService {

    @Override
    public AiAnalysisResult analyze(Map<String, Object> aiConfig,
                                    Map<String, Object> businessData) {
        String serviceUrl = (String) aiConfig.get("serviceUrl");
        String modelName = (String) aiConfig.get("modelName");
        Integer timeout = Integer.parseInt(
            aiConfig.getOrDefault("timeout", "30000").toString());

        log.info("开始 AI 分析: serviceUrl={}, modelName={}", serviceUrl, modelName);

        // 构建请求数据
        Map<String, Object> requestData = new HashMap<>();
        requestData.put("modelName", modelName);
        requestData.put("businessData", businessData);

        try {
            // 调用 AI 服务
            HttpResponse response = HttpRequest.post(serviceUrl)
                .body(JSONUtil.toJsonStr(requestData))
                .timeout(timeout)
                .execute();

            if (response.isOk()) {
                String body = response.body();
                Map<String, Object> resultMap = JSONUtil.toBean(body, Map.class);

                // 解析 AI 返回结果
                boolean approved = Boolean.parseBoolean(
                    resultMap.getOrDefault("approved", "false").toString());
                Double confidence = Double.parseDouble(
                    resultMap.getOrDefault("confidence", "0.0").toString());
                String reason = (String) resultMap.get("reason");

                return AiAnalysisResult.builder()
                    .approved(approved)
                    .confidence(confidence)
                    .reason(reason)
                    .details(resultMap.get("details"))
                    .build();
            } else {
                throw new RuntimeException("AI 服务调用失败: " + response.getStatus());
            }

        } catch (Exception e) {
            log.error("AI 服务调用异常: error={}", e.getMessage(), e);
            throw new RuntimeException("AI 服务调用异常", e);
        }
    }
}

工作流程 ​

正常流程 ​

1. 流程到达 Agent 节点
   ↓
2. AgentBehavior.execute() 被调用
   ↓
3. 提取 AI 配置和业务数据
   ↓
4. 调用 AiAgentService.analyze()
   ↓
5. AI 返回分析结果
   ├─ approved = true
   │  - 设置 approvalResult = "APPROVED"
   │  - 设置 aiDecision = "PASS"
   │
   └─ approved = false
      - 设置 approvalResult = "REJECTED"
      - 设置 aiDecision = "FAIL"
   ↓
6. 触发节点离开事件
   ↓
7. 调用 leave(execution) 继续流程 ✓
   ↓
后续节点(可以根据 approvalResult 判断)

关键流程变量 ​

变量名类型说明
approvalResultString审批结果(APPROVED/REJECTED/ERROR)
aiDecisionStringAI决策(PASS/FAIL)
aiConfidenceDoubleAI置信度(0.0-1.0)
aiReasonStringAI分析原因
aiProcessingErrorString错误信息(如果有)

修正后的 V1 与 V2 对比 ​

核心差异 ​

特性V1 (修正后)V2
节点结构单一 ServiceTaskServiceTask + BoundaryEvent + UserTask
执行方式AI 自动决策AI 先处理,用户可介入
人工干预❌ 不支持✅ 支持
流程控制调用 leave() 继续两条路径都可继续
复杂度低(~150行)中(~470行)
适用场景简单自动化复杂人机协同

使用场景建议 ​

V1 适合:

  • ✅ 低风险的自动化审批(如:日常报销 < 500元)
  • ✅ 规则明确的判断(如:格式校验)
  • ✅ 不需要人工确认的场景
  • ✅ 高频次、标准化的流程

V2 适合:

  • ✅ 中高风险的审批(如:采购 > 1万元)
  • ✅ 需要人工最终确认的场景
  • ✅ 复杂决策需要 AI 辅助
  • ✅ 需要审计追踪的流程

总结 ​

修正要点 ​

已修复的问题:

  1. ✅ 移除 terminateInstance 调用
  2. ✅ 移除硬编码的 InstanceStatus.PASS
  3. ✅ 根据 AI 结果动态设置流程变量
  4. ✅ 调用 leave(execution) 继续流程

修正后的优势:

  • ✅ 可作为流程中间节点使用
  • ✅ 支持通过/驳回两种结果
  • ✅ 流程可正常继续
  • ✅ 代码逻辑完整

仍然的局限:

  • ❌ 不支持人工干预
  • ❌ AI 出错无法补救
  • ❌ 不适合高风险场景

最终建议 ​

修正后的 V1 方案:

  • 适合简单、低风险的自动化场景
  • 开发成本低,维护简单
  • 功能有限,扩展性一般

V2 方案:

  • 适合企业级应用
  • 功能完整,扩展性强
  • 开发成本略高,但长期 ROI 更好

推荐策略:

  • 简单场景:使用修正后的 V1
  • 复杂场景:使用 V2
  • 企业应用:优先选择 V2

文档版本: v1.0 (修正版) 创建日期: 2026-01-09 修正内容: 移除 terminateInstance,改为 leave(execution)