图片预览

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

Skip to content

AgentNode V2 设计方案 - 第四部分:服务层实现 ​


五、服务层实现 ​

5.1 AI Agent 服务 ​

文件: service/AiAgentService.java

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

import java.util.Map;

/**
 * AI Agent 服务接口
 *
 * @author willian fu
 * @since 2026-01-09
 */
public interface AiAgentService {

    /**
     * 异步分析审批请求
     *
     * @param processInstanceId 流程实例ID
     * @param taskId 任务ID
     * @param aiConfig AI配置
     * @param processVariables 流程变量
     */
    void analyzeAsync(String processInstanceId, String taskId,
                     Map<String, String> aiConfig, Map<String, Object> processVariables);

    /**
     * 同步分析审批请求
     *
     * @param processInstanceId 流程实例ID
     * @param taskId 任务ID
     * @param aiConfig AI配置
     * @param processVariables 流程变量
     * @return AI分析结果
     */
    AiAnalysisResult analyzeSync(String processInstanceId, String taskId,
                                 Map<String, String> aiConfig, Map<String, Object> processVariables);

    /**
     * 检查 AI 服务健康状态
     *
     * @param healthCheckUrl 健康检查URL
     * @return 是否健康
     */
    boolean checkHealth(String healthCheckUrl);
}

文件: service/impl/AiAgentServiceImpl.java

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

import cn.hutool.core.util.StrUtil;
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.FlowTaskService;
import com.pig4cloud.pigx.wflow.utils.AsyncTaskUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * AI Agent 服务实现
 *
 * @author willian fu
 * @since 2026-01-09
 */
@Slf4j
@Service
public class AiAgentServiceImpl implements AiAgentService {

    @Autowired
    private TaskService taskService;

    @Autowired
    private FlowTaskService flowTaskService;

    @Override
    public void analyzeAsync(String processInstanceId, String taskId,
                            Map<String, String> aiConfig, Map<String, Object> processVariables) {
        // 使用框架的异步工具执行
        AsyncTaskUtil.execute(true, 3, () -> {
            try {
                AiAnalysisResult result = analyzeSync(processInstanceId, taskId, aiConfig, processVariables);

                // 处理 AI 分析结果
                handleAiResult(taskId, result, aiConfig);

            } catch (Exception e) {
                log.error("AI 异步分析失败: taskId={}, error={}", taskId, e.getMessage(), e);
                // 设置错误标记
                Map<String, Object> errorVars = new HashMap<>();
                errorVars.put("aiProcessingError", e.getMessage());
                errorVars.put("aiProcessing", false);
                taskService.setVariables(taskId, errorVars);
            }
        });
    }

    @Override
    public AiAnalysisResult analyzeSync(String processInstanceId, String taskId,
                                       Map<String, String> aiConfig, Map<String, Object> processVariables) {
        String serviceUrl = aiConfig.get("serviceUrl");
        String modelName = aiConfig.get("modelName");
        String contextPrompt = aiConfig.get("contextPrompt");
        Integer timeout = Integer.parseInt(aiConfig.getOrDefault("timeout", "30000"));

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

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

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

            if (response.isOk()) {
                String body = response.body();
                AiAnalysisResult result = JSONUtil.toBean(body, AiAnalysisResult.class);

                log.info("AI 分析完成: taskId={}, suggestion={}, confidence={}",
                    taskId, result.getSuggestion(), result.getConfidence());

                return result;
            } else {
                throw new RuntimeException("AI 服务调用失败: " + response.getStatus());
            }

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

    @Override
    public boolean checkHealth(String healthCheckUrl) {
        if (StrUtil.isBlank(healthCheckUrl)) {
            return true; // 未配置健康检查,默认健康
        }

        try {
            HttpResponse response = HttpRequest.get(healthCheckUrl)
                .timeout(5000)
                .execute();

            return response.isOk();

        } catch (Exception e) {
            log.warn("AI 服务健康检查失败: url={}, error={}", healthCheckUrl, e.getMessage());
            return false;
        }
    }

    /**
     * 处理 AI 分析结果
     */
    private void handleAiResult(String taskId, AiAnalysisResult result, Map<String, String> aiConfig) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("aiSuggestion", result.getSuggestion());
        variables.put("aiConfidence", result.getConfidence());
        variables.put("aiReason", result.getReason());
        variables.put("aiAnalysisTime", System.currentTimeMillis());

        // 获取审批模式配置
        String mode = aiConfig.getOrDefault("mode", "AI_FIRST");
        Boolean requireHumanConfirm = Boolean.parseBoolean(
            aiConfig.getOrDefault("requireHumanConfirm", "true"));
        Double autoApproveThreshold = Double.parseDouble(
            aiConfig.getOrDefault("autoApproveThreshold", "0.95"));
        Double autoRejectThreshold = Double.parseDouble(
            aiConfig.getOrDefault("autoRejectThreshold", "0.05"));

        // 根据置信度和配置决定是否自动完成
        if (!requireHumanConfirm) {
            if (result.getConfidence() >= autoApproveThreshold && "APPROVE".equals(result.getSuggestion())) {
                // 自动通过
                variables.put("operation", "ai_suggest_approve");
                variables.put("approvalResult", "AI_AUTO_APPROVED");
                taskService.complete(taskId, variables);
                log.info("AI 自动通过: taskId={}, confidence={}", taskId, result.getConfidence());

            } else if (result.getConfidence() <= autoRejectThreshold && "REJECT".equals(result.getSuggestion())) {
                // 自动拒绝
                variables.put("operation", "ai_suggest_reject");
                variables.put("approvalResult", "AI_AUTO_REJECTED");
                taskService.complete(taskId, variables);
                log.info("AI 自动拒绝: taskId={}, confidence={}", taskId, result.getConfidence());

            } else {
                // 置信度不足,等待人工确认
                variables.put("aiProcessing", false);
                variables.put("requireHumanConfirm", true);
                taskService.setVariables(taskId, variables);
                log.info("AI 置信度不足,等待人工确认: taskId={}, confidence={}", taskId, result.getConfidence());
            }
        } else {
            // 需要人工确认
            variables.put("aiProcessing", false);
            taskService.setVariables(taskId, variables);
            log.info("AI 分析完成,等待人工确认: taskId={}", taskId);
        }
    }
}

5.2 AI 分析结果类 ​

文件: service/dto/AiAnalysisResult.java

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

import lombok.Data;

/**
 * AI 分析结果
 *
 * @author willian fu
 * @since 2026-01-09
 */
@Data
public class AiAnalysisResult {

    /**
     * AI 建议:APPROVE(通过), REJECT(拒绝), UNCERTAIN(不确定)
     */
    private String suggestion;

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

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

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

    /**
     * 分析耗时(毫秒)
     */
    private Long duration;
}

5.3 人工干预服务 ​

文件: service/HumanInterventionService.java

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

/**
 * 人工干预服务接口
 *
 * @author willian fu
 * @since 2026-01-09
 */
public interface HumanInterventionService {

    /**
     * 请求人工干预
     *
     * @param processInstanceId 流程实例ID
     * @param userId 干预用户ID
     * @param reason 干预原因
     */
    void requestIntervention(String processInstanceId, String userId, String reason);

    /**
     * 完成干预,返回 AI 任务
     *
     * @param taskId 干预任务ID
     * @param interventionResult 干预结果
     */
    void completeIntervention(String taskId, String interventionResult);

    /**
     * 终止流程
     *
     * @param taskId 干预任务ID
     * @param reason 终止原因
     */
    void terminateProcess(String taskId, String reason);
}

文件: service/impl/HumanInterventionServiceImpl.java

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

import com.pig4cloud.pigx.wflow.service.HumanInterventionService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 人工干预服务实现
 *
 * @author willian fu
 * @since 2026-01-09
 */
@Slf4j
@Service
@Transactional
public class HumanInterventionServiceImpl implements HumanInterventionService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Override
    public void requestIntervention(String processInstanceId, String userId, String reason) {
        log.info("请求人工干预: processInstanceId={}, userId={}, reason={}",
            processInstanceId, userId, reason);

        Map<String, Object> variables = new HashMap<>();
        variables.put("humanInterruptRequested", true);
        variables.put("interruptedByUser", userId);
        variables.put("interruptionTime", new Date());
        variables.put("interruptionReason", reason);
        variables.put("aiProcessing", false); // 暂停 AI 处理

        runtimeService.setVariables(processInstanceId, variables);

        log.info("人工干预请求已设置: processInstanceId={}", processInstanceId);
    }

    @Override
    public void completeIntervention(String taskId, String interventionResult) {
        log.info("完成人工干预: taskId={}, result={}", taskId, interventionResult);

        Map<String, Object> variables = new HashMap<>();
        variables.put("operation", "intervention_complete");
        variables.put("interventionComment", interventionResult);
        variables.put("humanInterruptRequested", false);
        variables.put("interventionResult", interventionResult);
        variables.put("aiProcessing", true);
        variables.put("lastInterventionTime", new Date());

        taskService.complete(taskId, variables);

        log.info("人工干预已完成,返回 AI 处理: taskId={}", taskId);
    }

    @Override
    public void terminateProcess(String taskId, String reason) {
        log.info("终止流程: taskId={}, reason={}", taskId, reason);

        Map<String, Object> variables = new HashMap<>();
        variables.put("operation", "terminate_process");
        variables.put("processTerminated", true);
        variables.put("terminationReason", reason);

        taskService.complete(taskId, variables);

        log.info("流程已终止: taskId={}", taskId);
    }
}