Appearance
AgentNode V2 - 人机协同智能审批节点设计方案(修正版)
文档说明
版本: v2.0 (修正版) 创建日期: 2026-01-09 适配框架: Wflow-biz (基于 Flowable) 设计理念: AI 先处理,用户可介入,介入后以用户结果为准
一、核心设计理念
1.1 设计修正说明
原设计的问题:
- 只创建了一个 UserTask,AI 作为候选人
- 边界事件触发后返回 AI 任务(形成循环)
- 不符合"用户介入后以用户结果为准"的需求
修正后的设计:
- AiAgent 节点转换成 3 个 BPMN 元素:
- ServiceTask:AI 自动处理
- BoundaryEvent:用户介入触发器
- UserTask:用户审批任务
1.2 工作流程
前置节点
↓
ServiceTask (AI自动处理)
├─ 正常完成 → 后续节点
│
└─ BoundaryEvent (用户介入,cancelActivity=true)
↓
UserTask (用户审批)
↓
后续节点关键点:
- AI 先自动处理(ServiceTask)
- 用户可以随时介入(通过设置
humanInterventionRequested = true) - 边界事件触发后,中断 AI 处理(
cancelActivity=true) - 用户审批完成后,直接流转到后续节点(不返回 AI)
1.3 与 V1 版本的区别
| 特性 | V1 (Agent) | V2 (AiAgent) |
|---|---|---|
| 节点类型 | ServiceTask (自动执行) | ServiceTask + UserTask + BoundaryEvent |
| 执行方式 | 完全自动化 | AI 先处理,用户可介入 |
| 人工干预 | 不支持 | 支持随时介入 |
| 介入后处理 | N/A | 以用户结果为准,不返回 AI |
| 适用场景 | 简单自动化任务 | 需要人机协同的审批流程 |
二、节点类型定义
2.1 NodeType 枚举扩展
文件: core/bean/process/NodeType.java
java
/**
* AI智能审批节点 - 支持人机协同
*/
AiAgent {
@Override
public Class<? extends NodeProps> getPropsType() {
return AiAgentProps.class;
}
},2.2 节点属性配置类
文件: core/bean/process/props/AiAgentProps.java
java
package com.pig4cloud.pigx.wflow.core.bean.process.props;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.pig4cloud.pigx.wflow.core.bean.process.NodeProps;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.List;
/**
* AI智能审批节点属性配置
*
* @author willian fu
* @since 2026-01-09
*/
@Data
@EqualsAndHashCode(callSuper = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class AiAgentProps extends NodeProps {
/**
* AI Agent 配置
*/
private AiServiceConfig aiService;
/**
* 人工干预配置
*/
private HumanInterventionConfig humanIntervention;
/**
* 审批模式配置
*/
private ApprovalModeConfig approvalMode;
/**
* AI服务配置
*/
@Data
public static class AiServiceConfig {
/**
* AI 服务端点URL
*/
private String serviceUrl;
/**
* AI 服务调用超时时间(毫秒)
*/
private Integer timeout = 30000;
/**
* AI 模型名称
*/
private String modelName;
/**
* API Key
*/
private String apiKey;
/**
* 上下文提示词
*/
private String contextPrompt;
/**
* AI 服务健康检查URL
*/
private String healthCheckUrl;
}
/**
* 人工干预配置
*/
@Data
public static class HumanInterventionConfig {
/**
* 是否允许人工干预
*/
private Boolean enabled = true;
/**
* 可干预的用户列表(候选人)
*/
private List<String> allowedUsers;
/**
* 干预超时时间(分钟)
*/
private Integer timeoutMinutes = 60;
}
/**
* 审批模式配置
*/
@Data
public static class ApprovalModeConfig {
/**
* 自动通过阈值(AI置信度)
*/
private Double autoApproveThreshold = 0.95;
/**
* 自动拒绝阈值(AI置信度)
*/
private Double autoRejectThreshold = 0.05;
/**
* 是否需要记录AI决策
*/
private Boolean recordDecision = true;
}
}2.3 配置项说明
AI 服务配置
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| serviceUrl | String | null | AI 服务端点URL |
| timeout | Integer | 30000 | 调用超时时间(毫秒) |
| modelName | String | null | AI 模型名称 |
| apiKey | String | null | API 密钥 |
| contextPrompt | String | null | 上下文提示词 |
| healthCheckUrl | String | null | 健康检查URL |
人工干预配置
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| enabled | Boolean | true | 是否允许人工干预 |
| allowedUsers | List<String> | null | 可干预的用户列表 |
| timeoutMinutes | Integer | 60 | 干预超时时间(分钟) |
审批模式配置
| 字段 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| autoApproveThreshold | Double | 0.95 | 自动通过阈值 |
| autoRejectThreshold | Double | 0.05 | 自动拒绝阈值 |
| recordDecision | Boolean | true | 是否记录AI决策 |
三、节点转换逻辑(核心)
3.1 工厂方法注册
文件: core/bpmn/converter/WflowNodeHandlerFactory.java
在构造函数中注册 AiAgent 节点处理器:
java
public WflowNodeHandlerFactory(Process process, BpmnModel bpmnModel) {
this.process = process;
this.bpmnModel = bpmnModel;
// 注册现有节点类型
addCustomNodeType(NodeType.Gateway, this::createGatewayNode);
addCustomNodeType(NodeType.Start, this::createStartNode);
addCustomNodeType(NodeType.Approval, this::createApprovalNode);
// ... 其他节点 ...
// 注册 AI 智能审批节点
addCustomNodeType(NodeType.AiAgent, this::createAiAgentNode);
}3.2 核心转换方法
关键设计:
- 返回 ServiceTask(AI 处理任务)
- 同时创建 BoundaryEvent 和 UserTask
- 两条路径都指向同一个后续节点
java
/**
* 创建 AI 智能审批节点
* 转换成:ServiceTask (AI处理) + BoundaryEvent (用户介入) + UserTask (用户审批)
*
* @param node 节点数据对象
* @return AI 处理任务(ServiceTask)
*/
public ServiceTask createAiAgentNode(ProcNode node) {
AiAgentProps props = (AiAgentProps) node.getProps();
// 1. 创建 AI 自动处理任务(ServiceTask)
ServiceTask aiServiceTask = new ServiceTask();
aiServiceTask.setId(node.getId());
aiServiceTask.setName(node.getName());
aiServiceTask.setImplementationType("class");
aiServiceTask.setImplementation(AiAgentBehavior.class.getName());
// 2. 设置执行监听器
aiServiceTask.setExecutionListeners(nodeListeners);
// 3. 存储 AI 配置到扩展元素
storeAiConfigToExtension(aiServiceTask, props);
// 4. 创建用户介入机制(如果启用)
if (props.getHumanIntervention() != null &&
Boolean.TRUE.equals(props.getHumanIntervention().getEnabled())) {
createHumanInterventionMechanism(node, aiServiceTask, props);
}
return aiServiceTask;
}3.3 用户介入机制创建
关键点:
- BoundaryEvent 附加在 ServiceTask 上
cancelActivity=true中断 AI 处理- UserTask 完成后直接到
node.getChildId()
java
/**
* 创建用户介入机制
* 包括:BoundaryEvent + UserTask
*/
private void createHumanInterventionMechanism(ProcNode node, ServiceTask aiServiceTask,
AiAgentProps props) {
// 1. 创建边界事件(附加在 AI ServiceTask 上)
BoundaryEvent boundaryEvent = new BoundaryEvent();
boundaryEvent.setId(node.getId() + "-humanIntervention");
boundaryEvent.setName("用户介入");
boundaryEvent.setCancelActivity(true); // 关键:中断 AI 处理
boundaryEvent.setAttachedToRef(aiServiceTask);
// 2. 设置触发条件
ConditionalEventDefinition conditionalDef = new ConditionalEventDefinition();
conditionalDef.setConditionExpression("${humanInterventionRequested == true}");
boundaryEvent.addEventDefinition(conditionalDef);
// 3. 创建用户审批任务
UserTask userApprovalTask = new UserTask();
userApprovalTask.setId(node.getId() + "-userApproval");
userApprovalTask.setName(node.getName() + "-用户审批");
// 设置审批人(从配置中获取或使用动态表达式)
if (props.getHumanIntervention().getAllowedUsers() != null &&
!props.getHumanIntervention().getAllowedUsers().isEmpty()) {
userApprovalTask.setCandidateUsers(props.getHumanIntervention().getAllowedUsers());
} else {
userApprovalTask.setAssignee("${interventionUser}");
}
// 设置任务监听器
userApprovalTask.setTaskListeners(createUserApprovalTaskListeners());
userApprovalTask.setExecutionListeners(nodeListeners);
// 4. 创建连线:边界事件 → 用户审批任务
SequenceFlow toUserApproval = new SequenceFlow();
toUserApproval.setId(boundaryEvent.getId() + "_flow");
toUserApproval.setSourceRef(boundaryEvent.getId());
toUserApproval.setTargetRef(userApprovalTask.getId());
// 5. 创建连线:用户审批任务 → 后续节点
// 关键:连接到 node.getChildId(),即原 AiAgent 节点的下一个节点
SequenceFlow toNextNode = new SequenceFlow();
toNextNode.setId(userApprovalTask.getId() + "_next");
toNextNode.setSourceRef(userApprovalTask.getId());
toNextNode.setTargetRef(node.getChildId());
// 6. 添加到流程
process.addFlowElement(boundaryEvent);
process.addFlowElement(userApprovalTask);
process.addFlowElement(toUserApproval);
process.addFlowElement(toNextNode);
}
/**
* 创建用户审批任务监听器
*/
private List<FlowableListener> createUserApprovalTaskListeners() {
List<FlowableListener> listeners = new ArrayList<>();
// 任务创建监听器
FlowableListener createListener = new FlowableListener();
createListener.setEvent("create");
createListener.setImplementationType("delegateExpression");
createListener.setImplementation("${userApprovalTaskCreateListener}");
listeners.add(createListener);
// 任务完成监听器
FlowableListener completeListener = new FlowableListener();
completeListener.setEvent("complete");
completeListener.setImplementationType("delegateExpression");
completeListener.setImplementation("${userApprovalTaskCompleteListener}");
listeners.add(completeListener);
return listeners;
}3.4 扩展元素存储
java
/**
* 存储 AI 配置到扩展元素
*/
private void storeAiConfigToExtension(ServiceTask serviceTask, AiAgentProps props) {
Map<String, List<ExtensionElement>> extensionElements = serviceTask.getExtensionElements();
// AI 服务配置
if (props.getAiService() != null) {
AiAgentProps.AiServiceConfig aiService = props.getAiService();
addExtensionElement(extensionElements, "aiService", "serviceUrl",
aiService.getServiceUrl());
addExtensionElement(extensionElements, "aiService", "modelName",
aiService.getModelName());
addExtensionElement(extensionElements, "aiService", "timeout",
String.valueOf(aiService.getTimeout()));
addExtensionElement(extensionElements, "aiService", "apiKey",
aiService.getApiKey());
addExtensionElement(extensionElements, "aiService", "contextPrompt",
aiService.getContextPrompt());
}
// 审批模式配置
if (props.getApprovalMode() != null) {
AiAgentProps.ApprovalModeConfig mode = props.getApprovalMode();
addExtensionElement(extensionElements, "approvalMode", "autoApproveThreshold",
String.valueOf(mode.getAutoApproveThreshold()));
addExtensionElement(extensionElements, "approvalMode", "autoRejectThreshold",
String.valueOf(mode.getAutoRejectThreshold()));
addExtensionElement(extensionElements, "approvalMode", "recordDecision",
String.valueOf(mode.getRecordDecision()));
}
}
/**
* 添加扩展元素
*/
private void addExtensionElement(Map<String, List<ExtensionElement>> extensionElements,
String namespace, String name, String value) {
if (value == null) return;
List<ExtensionElement> elements = extensionElements.computeIfAbsent(
namespace, k -> new ArrayList<>());
ExtensionElement element = new ExtensionElement();
element.setName(name);
element.setElementText(value);
element.setNamespacePrefix("aiagent");
element.setNamespace(WFlowBpmnConvertCreator.NAME_SPACE + "/aiagent");
elements.add(element);
}四、生成的 BPMN 结构
4.1 完整的 BPMN XML
xml
<!-- AI 自动处理任务 (ServiceTask) -->
<serviceTask id="aiAgent_001" name="AI智能审批"
flowable:class="com.pig4cloud.pigx.wflow.core.bpmn.behavior.AiAgentBehavior">
<extensionElements>
<!-- AI 服务配置 -->
<aiagent:serviceUrl>http://ai-service:8080/api/analyze</aiagent:serviceUrl>
<aiagent:modelName>gpt-4</aiagent:modelName>
<aiagent:timeout>30000</aiagent:timeout>
<!-- 审批模式配置 -->
<aiagent:autoApproveThreshold>0.95</aiagent:autoApproveThreshold>
<aiagent:autoRejectThreshold>0.05</aiagent:autoRejectThreshold>
<!-- 执行监听器 -->
<flowable:executionListener event="end"
delegateExpression="${userTaskListener}"/>
</extensionElements>
</serviceTask>
<!-- 用户介入边界事件 -->
<boundaryEvent id="aiAgent_001-humanIntervention"
name="用户介入"
attachedToRef="aiAgent_001"
cancelActivity="true">
<conditionalEventDefinition>
<condition>${humanInterventionRequested == true}</condition>
</conditionalEventDefinition>
</boundaryEvent>
<!-- 用户审批任务 -->
<userTask id="aiAgent_001-userApproval"
name="AI智能审批-用户审批"
flowable:candidateUsers="admin,manager">
<extensionElements>
<flowable:taskListener event="create"
delegateExpression="${userApprovalTaskCreateListener}"/>
<flowable:taskListener event="complete"
delegateExpression="${userApprovalTaskCompleteListener}"/>
</extensionElements>
</userTask>
<!-- 连线:边界事件 → 用户审批 -->
<sequenceFlow id="aiAgent_001-humanIntervention_flow"
sourceRef="aiAgent_001-humanIntervention"
targetRef="aiAgent_001-userApproval"/>
<!-- 连线:AI 任务 → 后续节点 -->
<sequenceFlow id="aiAgent_001_next"
sourceRef="aiAgent_001"
targetRef="nextNode"/>
<!-- 连线:用户审批 → 后续节点 -->
<sequenceFlow id="aiAgent_001-userApproval_next"
sourceRef="aiAgent_001-userApproval"
targetRef="nextNode"/>4.2 流程图示
前置节点
↓
┌─────────────────────────────────┐
│ ServiceTask (AI自动处理) │
│ id: aiAgent_001 │
│ class: AiAgentBehavior │
└─────────────────────────────────┘
│ │
│ AI完成 │ 用户介入
│ │ (BoundaryEvent)
↓ ↓
后续节点 ┌─────────────────────────┐
│ UserTask (用户审批) │
│ id: aiAgent_001- │
│ userApproval │
└─────────────────────────┘
↓
后续节点五、AiAgentBehavior 实现
5.1 核心行为类
文件: core/bpmn/behavior/AiAgentBehavior.java
java
package com.pig4cloud.pigx.wflow.core.bpmn.behavior;
import com.pig4cloud.pigx.wflow.service.AiAgentService;
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;
/**
* AI Agent 行为处理器
* 负责 AI 自动审批的执行逻辑
*
* @author willian fu
* @since 2026-01-09
*/
@Slf4j
public class AiAgentBehavior extends AbstractBpmnActivityBehavior {
@Override
public void execute(DelegateExecution execution) {
String processInstanceId = execution.getProcessInstanceId();
String activityId = execution.getCurrentActivityId();
log.info("AI Agent 开始执行: processInstanceId={}, activityId={}",
processInstanceId, activityId);
try {
// 1. 提取 AI 配置
Map<String, String> aiConfig = extractAiConfig(execution);
// 2. 获取业务数据
Map<String, Object> processVariables = execution.getVariables();
// 3. 初始化流程变量
initializeProcessVariables(execution);
// 4. 调用 AI 服务进行分析
AiAgentService aiAgentService = SpringBeanUtil.getBean(AiAgentService.class);
aiAgentService.analyzeAndComplete(processInstanceId, activityId,
aiConfig, processVariables, execution);
log.info("AI Agent 执行完成: processInstanceId={}", processInstanceId);
} catch (Exception e) {
log.error("AI Agent 执行失败: processInstanceId={}, error={}",
processInstanceId, e.getMessage(), e);
// 设置错误标记
execution.setVariable("aiProcessingError", e.getMessage());
execution.setVariable("aiProcessingSuccess", false);
// 继续流程(或根据配置决定是否中断)
leave(execution);
}
}
/**
* 提取 AI 配置
*/
private Map<String, String> extractAiConfig(DelegateExecution execution) {
String processDefinitionId = execution.getProcessDefinitionId();
String activityId = execution.getCurrentActivityId();
FlowElement flowElement = ProcessDefinitionUtil.getBpmnModel(processDefinitionId)
.getFlowElement(activityId);
Map<String, String> config = new HashMap<>();
if (flowElement instanceof ServiceTask) {
ServiceTask serviceTask = (ServiceTask) flowElement;
Map<String, List<ExtensionElement>> extensionElements =
serviceTask.getExtensionElements();
// 提取 AI 服务配置
extractExtensionConfig(extensionElements, "aiService", config);
// 提取审批模式配置
extractExtensionConfig(extensionElements, "approvalMode", config);
}
return config;
}
/**
* 提取扩展配置
*/
private void extractExtensionConfig(
Map<String, List<ExtensionElement>> extensionElements,
String namespace, Map<String, String> config) {
List<ExtensionElement> elements = extensionElements.get(namespace);
if (elements != null) {
for (ExtensionElement element : elements) {
String name = element.getName();
String value = element.getElementText();
if (value != null && !value.isEmpty()) {
config.put(name, value);
}
}
}
}
/**
* 初始化流程变量
*/
private void initializeProcessVariables(DelegateExecution execution) {
// 设置人工干预标记(默认为 false)
if (execution.getVariable("humanInterventionRequested") == null) {
execution.setVariable("humanInterventionRequested", false);
}
// 记录 AI 处理开始时间
execution.setVariable("aiProcessingStartTime", System.currentTimeMillis());
}
}六、服务层实现(简化版)
6.1 AI Agent 服务接口
文件: service/AiAgentService.java
java
package com.pig4cloud.pigx.wflow.service;
import org.flowable.engine.delegate.DelegateExecution;
import java.util.Map;
public interface AiAgentService {
/**
* 分析并完成任务
*/
void analyzeAndComplete(String processInstanceId, String activityId,
Map<String, String> aiConfig,
Map<String, Object> processVariables,
DelegateExecution execution);
/**
* 请求人工介入
*/
void requestHumanIntervention(String processInstanceId, String userId, String reason);
}6.2 服务实现(核心逻辑)
文件: service/impl/AiAgentServiceImpl.java
关键点:
- AI 分析完成后,根据置信度决定是否自动完成
- 如果自动完成,调用
execution.leave()继续流程 - 如果需要人工介入,设置
humanInterventionRequested = true
java
@Service
public class AiAgentServiceImpl implements AiAgentService {
@Override
public void analyzeAndComplete(String processInstanceId, String activityId,
Map<String, String> aiConfig,
Map<String, Object> processVariables,
DelegateExecution execution) {
// 1. 调用 AI 服务
AiAnalysisResult result = callAiService(aiConfig, processVariables);
// 2. 保存 AI 分析结果
execution.setVariable("aiSuggestion", result.getSuggestion());
execution.setVariable("aiConfidence", result.getConfidence());
execution.setVariable("aiReason", result.getReason());
// 3. 根据置信度决定是否自动完成
Double autoApproveThreshold = Double.parseDouble(
aiConfig.getOrDefault("autoApproveThreshold", "0.95"));
if (result.getConfidence() >= autoApproveThreshold) {
// 自动完成,继续流程
execution.setVariable("approvalResult", "AI_AUTO_APPROVED");
((AbstractBpmnActivityBehavior) execution.getCurrentFlowElement()
.getBehavior()).leave(execution);
} else {
// 置信度不足,等待(不调用 leave,流程会自然等待)
execution.setVariable("aiWaitingForIntervention", true);
}
}
@Override
public void requestHumanIntervention(String processInstanceId, String userId, String reason) {
// 设置人工介入标记,触发边界事件
runtimeService.setVariable(processInstanceId, "humanInterventionRequested", true);
runtimeService.setVariable(processInstanceId, "interventionUser", userId);
runtimeService.setVariable(processInstanceId, "interventionReason", reason);
}
}七、完整工作流程
7.1 正常流程(AI 自动完成)
1. 流程到达 AiAgent 节点
↓
2. ServiceTask (AI处理) 开始执行
- AiAgentBehavior.execute() 被调用
↓
3. 调用 AI 服务分析
- 获取 AI 建议和置信度
↓
4. 判断置信度
├─ 置信度 >= 阈值
│ - 调用 leave(execution)
│ - 流程流转到后续节点 ✓
│
└─ 置信度 < 阈值
- 等待用户介入7.2 用户介入流程
1. 用户请求介入
- 设置 humanInterventionRequested = true
↓
2. 边界事件触发
- 中断 ServiceTask
↓
3. 流程转到 UserTask
- 用户审批
↓
4. 流程继续到后续节点 ✓八、设计检查与总结
8.1 核心需求验证
✅ 需求1:AI 先处理
- 通过 ServiceTask 实现
- AiAgentBehavior 自动执行
✅ 需求2:用户可介入
- 通过 BoundaryEvent 实现
- 条件触发:
humanInterventionRequested == true
✅ 需求3:介入后以用户结果为准
- BoundaryEvent 的
cancelActivity=true中断 AI - UserTask 完成后直接到后续节点
- 不返回 AI 处理
8.2 BPMN 结构验证
AiAgent 节点转换成:
├─ ServiceTask (AI处理)
│ └─ 正常完成 → 后续节点
│
├─ BoundaryEvent (用户介入触发器)
│ └─ 附加在 ServiceTask 上
│
└─ UserTask (用户审批)
└─ 完成后 → 后续节点关键点:
- ServiceTask 和 UserTask 都连接到同一个后续节点
- 边界事件中断 ServiceTask
- 用户审批后不返回 AI
8.3 与 wflow-biz 框架集成
✅ 复用现有组件:
- EventHandler(节点事件)
- SpringBeanUtil(Bean获取)
- nodeListeners(执行监听器)
- WFlowBpmnConvertCreator(命名空间)
✅ 遵循框架规范:
- 继承 AbstractBpmnActivityBehavior
- 使用扩展元素存储配置
- 使用 delegateExpression 注册监听器
8.4 关键文件清单
| 文件 | 说明 |
|---|---|
| NodeType.java | 添加 AiAgent 枚举 |
| AiAgentProps.java | 节点属性配置类 |
| WflowNodeHandlerFactory.java | 添加 createAiAgentNode 方法 |
| AiAgentBehavior.java | AI 处理行为类 |
| AiAgentService.java | AI 服务接口 |
| AiAgentServiceImpl.java | AI 服务实现 |
九、总结
9.1 设计亮点
- 符合核心需求:AI 先处理,用户可介入,介入后以用户为准
- BPMN 标准:使用标准的 ServiceTask + BoundaryEvent + UserTask
- 框架集成:完全适配 wflow-biz 框架
- 简洁高效:避免复杂的循环逻辑
9.2 适用场景
- 需要 AI 辅助决策的审批流程
- 允许人工随时介入的自动化流程
- 人机协同的智能审批场景
9.3 实施要点
- 在 NodeType 中添加 AiAgent 枚举
- 创建 AiAgentProps 配置类
- 在 WflowNodeHandlerFactory 中实现转换逻辑
- 实现 AiAgentBehavior 和 AiAgentService
- 测试 AI 自动完成和用户介入两种场景
文档版本: v2.0 (修正版) 创建日期: 2026-01-09 最后更新: 2026-01-09 适配框架: Wflow-biz (基于 Flowable)