successIds;
+
+ /**
+ * 错误信息
+ */
+ private String errorMessage;
+
+ /**
+ * RAG 服务禁用时的默认响应
+ */
+ public static RagUpdQVResponse disabled() {
+ RagUpdQVResponse r = new RagUpdQVResponse();
+ r.setSuccess(false);
+ r.setErrorMessage("RAG service disabled");
+ return r;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/ichangzuo/system/model/dto/RagUpdateVectorResultVO.java b/src/main/java/com/ichangzuo/system/model/dto/RagUpdateVectorResultVO.java
new file mode 100644
index 0000000..ea3a7a5
--- /dev/null
+++ b/src/main/java/com/ichangzuo/system/model/dto/RagUpdateVectorResultVO.java
@@ -0,0 +1,21 @@
+package com.ichangzuo.system.model.dto;
+
+import lombok.Data;
+import java.util.List;
+
+/**
+ * RAG 更新向量库结果(前端视图)
+ *
+ * 与内部契约 {@link RagUpdateVectorResponse}(Python↔Java,含 details)不同,
+ * 该 VO 仅向前端暴露成功 help_id 数组,不暴露 details 明细。
+ *
+ * @author haoxr
+ */
+@Data
+public class RagUpdateVectorResultVO {
+
+ /**
+ * 成功的 help_id 数组(条数即数组长度)
+ */
+ private List successIds;
+}
\ No newline at end of file
diff --git a/src/main/java/com/ichangzuo/system/model/entity/KbFile.java b/src/main/java/com/ichangzuo/system/model/entity/KbFile.java
new file mode 100644
index 0000000..b0444bb
--- /dev/null
+++ b/src/main/java/com/ichangzuo/system/model/entity/KbFile.java
@@ -0,0 +1,40 @@
+package com.ichangzuo.system.model.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.time.LocalDateTime;
+
+/**
+ * RAG 知识库文件记录
+ *
+ * @author haoxr
+ */
+@Data
+@TableName("mc_kb_files")
+public class KbFile {
+
+ @TableId(type = IdType.INPUT)
+ private Long fileId;
+
+ /** 原始文件名 */
+ private String fileName;
+
+ /** 帮助类型 ID,逗号分隔(如 "0,3") */
+ private String helpTypeId;
+
+ /** 分块数 */
+ private Integer chunkCount;
+
+ /** 上传时间(Unix 秒级时间戳) */
+ private Long uploadTime;
+
+ /** 文件分类:0=manual(手册·说明), 1=faq */
+ private Integer fileCategory;
+
+ private LocalDateTime createTime;
+
+ private LocalDateTime updateTime;
+}
diff --git a/src/main/java/com/ichangzuo/system/model/entity/QnA.java b/src/main/java/com/ichangzuo/system/model/entity/QnA.java
index 305af18..ac257a8 100644
--- a/src/main/java/com/ichangzuo/system/model/entity/QnA.java
+++ b/src/main/java/com/ichangzuo/system/model/entity/QnA.java
@@ -17,6 +17,8 @@ public class QnA {
private Integer state; //编辑状态
private String question;
private String answer;
+ private Integer confidence; // AI回复置信度 (0-10000, 即0.0000-1.0000)
private Integer editTime; //编辑时间
private Integer answerTime; //回应时间
+ private Integer embedded; // 是否已加入问题向量库 0=未入库 1=已入库
}
diff --git a/src/main/java/com/ichangzuo/system/service/IKbFileService.java b/src/main/java/com/ichangzuo/system/service/IKbFileService.java
new file mode 100644
index 0000000..3d8734b
--- /dev/null
+++ b/src/main/java/com/ichangzuo/system/service/IKbFileService.java
@@ -0,0 +1,7 @@
+package com.ichangzuo.system.service;
+
+import com.baomidou.mybatisplus.extension.service.IService;
+import com.ichangzuo.system.model.entity.KbFile;
+
+public interface IKbFileService extends IService {
+}
diff --git a/src/main/java/com/ichangzuo/system/service/RagClientService.java b/src/main/java/com/ichangzuo/system/service/RagClientService.java
new file mode 100644
index 0000000..1a161af
--- /dev/null
+++ b/src/main/java/com/ichangzuo/system/service/RagClientService.java
@@ -0,0 +1,335 @@
+package com.ichangzuo.system.service;
+
+import com.ichangzuo.config.property.RagProperties;
+import com.ichangzuo.system.model.dto.*;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.classic.methods.HttpDelete;
+import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.io.entity.StringEntity;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * RAG 客户端服务 - 调用 FastAPI RAG 服务
+ *
+ * @author haoxr
+ * @since 2024/8/21
+ */
+@Service
+public class RagClientService {
+
+ /**
+ * 允许上传的文档扩展名(小写,不含点)。
+ */
+ private static final java.util.Set ALLOWED_EXTENSIONS = java.util.Set.of("txt", "md");
+
+ private final CloseableHttpClient httpClient;
+ private final RagProperties ragProperties;
+ private final com.fasterxml.jackson.databind.ObjectMapper objectMapper;
+
+ public RagClientService(CloseableHttpClient httpClient, RagProperties ragProperties) {
+ this.httpClient = httpClient;
+ this.ragProperties = ragProperties;
+ this.objectMapper = new com.fasterxml.jackson.databind.ObjectMapper()
+ .configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ }
+
+ /**
+ * RAG 智能问答
+ */
+ public RagQueryResponse query(RagQueryRequest request) throws IOException {
+ if (!ragProperties.isEnabled()) {
+ return RagQueryResponse.disabled();
+ }
+ String url = ragProperties.getBaseUrl() + "/rag/query";
+ return executePost(url, request, RagQueryResponse.class);
+ }
+
+ /**
+ * 更新向量库(分批处理)
+ */
+ public List addQV(RagAddQVRequest request) throws IOException {
+ String url = ragProperties.getBaseUrl() + "/rag/addQV";
+ List allItems = request.getItems();
+ int batchSize = ragProperties.getBatchSize();
+ List totalSuccessIds = new ArrayList<>();
+
+ for (int i = 0; i < allItems.size(); i += batchSize) {
+ List batch = allItems.subList(i, Math.min(i + batchSize, allItems.size()));
+ RagAddQVRequest batchRequest = new RagAddQVRequest();
+ batchRequest.setItems(batch);
+
+ RagUpdQVResponse batchResp = executePost(url, batchRequest, RagUpdQVResponse.class);
+ if (!batchResp.isSuccess()) {
+ return List.of(); // 失败快速返回
+ }
+
+ if (batchResp.getSuccessIds() != null) {
+ totalSuccessIds.addAll(batchResp.getSuccessIds());
+ }
+ }
+
+ return totalSuccessIds;
+ }
+
+ /**
+ * 批量删除向量库问题
+ */
+ public List delQV(List helpIds) throws IOException {
+ if (!ragProperties.isEnabled()) {
+ return List.of();
+ }
+
+ String url = ragProperties.getBaseUrl() + "/rag/delQV";
+ RagDelQVRequest request = new RagDelQVRequest();
+ request.setHelpIds(helpIds);
+
+ RagUpdQVResponse response = executePost(url, request, RagUpdQVResponse.class);
+ if (response != null && response.isSuccess()) {
+ return response.getSuccessIds();
+ }
+ return List.of();
+ }
+
+ /**
+ * 相似问题搜索
+ *
+ * @param question 问题内容
+ * @param helpTypeId 帮助类型 ID
+ * @return 匹配结果列表
+ */
+ public RagSearchResponse searchSimilarQuestions(String question, String helpTypeId) throws IOException {
+ if (!ragProperties.isEnabled()) {
+ return RagSearchResponse.disabled();
+ }
+
+ RagSearchRequest request = new RagSearchRequest();
+ request.setQuestion(question);
+ request.setHelpTypeId(helpTypeId);
+ request.setTopK(5);
+ request.setThreshold(0.9);
+
+ String url = ragProperties.getBaseUrl() + "/questions/search";
+ RagSearchResponse response = executePost(url, request, RagSearchResponse.class);
+ return response != null ? response : RagSearchResponse.empty();
+ }
+
+ /**
+ * 生成 RAG 回答
+ *
+ * @param question 问题内容
+ * @param helpTypeId 帮助类型 ID
+ * @return 回答结果
+ */
+ public RagGenerateResponse generateRagAnswer(String question, String helpTypeId) throws IOException {
+ if (!ragProperties.isEnabled()) {
+ return RagGenerateResponse.disabled();
+ }
+
+ RagGenerateRequest request = new RagGenerateRequest();
+ request.setQuestion(question);
+ request.setHelpTypeId(helpTypeId);
+
+ String url = ragProperties.getBaseUrl() + "/rag/generate";
+ return executePost(url, request, RagGenerateResponse.class);
+ }
+
+ /**
+ * 上传知识库文档(仅允许 .txt / .md)
+ *
+ * 在网关层做扩展名白名单校验(统一小写,拒绝无扩展名),
+ * 合法格式以 multipart/form-data 转发到 Python
+ * {@code /knowledge/upload},字段契约与 Python 一致(file + help_type_id)。
+ *
+ * @param file 上传的文件
+ * @param helpTypeId 帮助类型 ID(逗号分隔字符串)
+ * @return 上传结果
+ */
+ public RagKBUploadResponse addKF(MultipartFile file, String helpTypeId) throws IOException {
+ if (!ragProperties.isEnabled()) {
+ return RagKBUploadResponse.disabled();
+ }
+
+ String filename = file.getOriginalFilename();
+ String ext = extractExtension(filename);
+ if (!isAllowedExtension(ext)) {
+ RagKBUploadResponse resp = new RagKBUploadResponse();
+ resp.setSuccess(false);
+ resp.setErrorMessage("不支持的文件类型:" + (ext.isEmpty() ? "无扩展名" : ext) + ",仅支持 .txt 和 .md");
+ return resp;
+ }
+
+ String url = ragProperties.getBaseUrl() + "/rag/addKF";
+ return executeMultipartPost(url, file, helpTypeId);
+ }
+
+ /**
+ * 上传 FAQ 文档(仅允许 .txt / .md)
+ *
+ * @param file 上传的文件
+ * @param helpTypeId 帮助类型 ID(逗号分隔字符串)
+ * @return 上传结果
+ */
+ public RagKBUploadResponse addQAF(MultipartFile file, String helpTypeId) throws IOException {
+ if (!ragProperties.isEnabled()) {
+ return RagKBUploadResponse.disabled();
+ }
+
+ String filename = file.getOriginalFilename();
+ String ext = extractExtension(filename);
+ if (!isAllowedExtension(ext)) {
+ RagKBUploadResponse resp = new RagKBUploadResponse();
+ resp.setSuccess(false);
+ resp.setErrorMessage("不支持的文件类型:" + (ext.isEmpty() ? "无扩展名" : ext) + ",仅支持 .txt 和 .md");
+ return resp;
+ }
+
+ String url = ragProperties.getBaseUrl() + "/rag/addQAF";
+ return executeMultipartPost(url, file, helpTypeId);
+ }
+
+ /**
+ * 删除 FAQ 文件,返回是否成功
+ *
+ * @param fileId 文件 ID
+ */
+ public boolean delQAF(Long fileId) throws IOException {
+ if (!ragProperties.isEnabled()) {
+ throw new IOException("RAG service disabled");
+ }
+ String url = ragProperties.getBaseUrl() + "/rag/delQAF/" + fileId;
+ executeDelete(url);
+ return true;
+ }
+
+ /**
+ * 提取文件扩展名(统一小写),无扩展名返回空字符串。
+ */
+ private String extractExtension(String filename) {
+ if (filename == null) {
+ return "";
+ }
+ int idx = filename.lastIndexOf('.');
+ if (idx < 0 || idx == filename.length() - 1) {
+ return "";
+ }
+ return filename.substring(idx + 1).toLowerCase(Locale.ROOT);
+ }
+
+ /**
+ * 是否允许的扩展名(.txt / .md)。
+ */
+ private boolean isAllowedExtension(String ext) {
+ return ALLOWED_EXTENSIONS.contains(ext);
+ }
+
+ /**
+ * 执行 multipart/form-data POST 请求(转发文件到 Python)。
+ */
+ private RagKBUploadResponse executeMultipartPost(String url, MultipartFile file, String helpTypeId)
+ throws IOException {
+ HttpPost post = new HttpPost(url);
+ MultipartEntityBuilder builder = MultipartEntityBuilder.create();
+ // Pass the filename directly in addBinaryBody — this sets the
+ // Content-Disposition filename parameter correctly. The Python
+ // endpoint reads file.filename (which is always correct when sent
+ // this way) and ignores original_filename.
+ builder.addBinaryBody("file", file.getBytes(),
+ ContentType.APPLICATION_OCTET_STREAM, file.getOriginalFilename());
+ builder.addTextBody("help_type_id", helpTypeId, ContentType.TEXT_PLAIN);
+ post.setEntity(builder.build());
+
+ String body = executeAndCheckStatus(httpClient, post);
+ return objectMapper.readValue(body, RagKBUploadResponse.class);
+ }
+
+ /**
+ * 获取知识库统计信息
+ */
+ public RagKnowledgeStatsResponse getStats() throws IOException {
+ if (!ragProperties.isEnabled()) {
+ return RagKnowledgeStatsResponse.disabled();
+ }
+ String url = ragProperties.getBaseUrl() + "/rag/stats";
+ return executeGet(url, RagKnowledgeStatsResponse.class);
+ }
+
+ /**
+ * 获取知识库文件列表
+ */
+ public RagKnowledgeFileListResponse getFiles() throws IOException {
+ if (!ragProperties.isEnabled()) {
+ return RagKnowledgeFileListResponse.disabled();
+ }
+ String url = ragProperties.getBaseUrl() + "/knowledge/files";
+ return executeGet(url, RagKnowledgeFileListResponse.class);
+ }
+
+ /**
+ * 删除知识库文件,返回是否成功
+ *
+ * @param fileId 文件 ID
+ */
+ public boolean delKF(Long fileId) throws IOException {
+ if (!ragProperties.isEnabled()) {
+ throw new IOException("RAG service disabled");
+ }
+ String url = ragProperties.getBaseUrl() + "/rag/delKF/" + fileId;
+ executeDelete(url);
+ return true;
+ }
+
+ /**
+ * 执行 POST 请求
+ */
+ private T executePost(String url, Object request, Class responseType) throws IOException {
+ HttpPost post = new HttpPost(url);
+ post.setHeader("Content-Type", "application/json");
+ post.setEntity(new StringEntity(objectMapper.writeValueAsString(request), ContentType.APPLICATION_JSON));
+ String body = executeAndCheckStatus(httpClient, post);
+ return objectMapper.readValue(body, responseType);
+ }
+
+ /**
+ * 执行 GET 请求
+ */
+ private T executeGet(String url, Class responseType) throws IOException {
+ HttpGet get = new HttpGet(url);
+ String body = executeAndCheckStatus(httpClient, get);
+ return objectMapper.readValue(body, responseType);
+ }
+
+ /**
+ * 执行 DELETE 请求
+ */
+ private void executeDelete(String url) throws IOException {
+ HttpDelete delete = new HttpDelete(url);
+ executeAndCheckStatus(httpClient, delete);
+ }
+
+ /**
+ * 执行 HTTP 请求,检查状态码,返回响应体。
+ * 如果状态码 ≥ 400,抛出 IOException(包含前 500 字符的响应摘要)。
+ */
+ private String executeAndCheckStatus(CloseableHttpClient client,
+ org.apache.hc.core5.http.ClassicHttpRequest request) throws IOException {
+ try (var response = client.execute(request)) {
+ int statusCode = response.getCode();
+ String body = new String(response.getEntity().getContent().readAllBytes(), StandardCharsets.UTF_8);
+ if (statusCode >= 400) {
+ String snippet = body.substring(0, Math.min(body.length(), 500));
+ throw new IOException("RAG service error (HTTP " + statusCode + "): " + snippet);
+ }
+ return body;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/ichangzuo/system/service/alipay/Base64.java b/src/main/java/com/ichangzuo/system/service/alipay/Base64.java
index b7b1203..e54dc3c 100644
--- a/src/main/java/com/ichangzuo/system/service/alipay/Base64.java
+++ b/src/main/java/com/ichangzuo/system/service/alipay/Base64.java
@@ -1,4 +1,4 @@
-package com.datao.service.alipay;
+package com.ichangzuo.system.service.alipay;
import java.util.Arrays;
diff --git a/src/main/java/com/ichangzuo/system/service/alipay/SignUtils.java b/src/main/java/com/ichangzuo/system/service/alipay/SignUtils.java
index 33fafdd..e0adff3 100644
--- a/src/main/java/com/ichangzuo/system/service/alipay/SignUtils.java
+++ b/src/main/java/com/ichangzuo/system/service/alipay/SignUtils.java
@@ -1,4 +1,4 @@
-package com.datao.service.alipay;
+package com.ichangzuo.system.service.alipay;
import java.io.UnsupportedEncodingException;
import java.security.*;
diff --git a/src/main/java/com/ichangzuo/system/service/impl/KbFileServiceImpl.java b/src/main/java/com/ichangzuo/system/service/impl/KbFileServiceImpl.java
new file mode 100644
index 0000000..74fb39c
--- /dev/null
+++ b/src/main/java/com/ichangzuo/system/service/impl/KbFileServiceImpl.java
@@ -0,0 +1,11 @@
+package com.ichangzuo.system.service.impl;
+
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.ichangzuo.system.mapper.KbFileMapper;
+import com.ichangzuo.system.model.entity.KbFile;
+import com.ichangzuo.system.service.IKbFileService;
+import org.springframework.stereotype.Service;
+
+@Service
+public class KbFileServiceImpl extends ServiceImpl implements IKbFileService {
+}
diff --git a/src/main/java/com/ichangzuo/system/service/impl/QnAServiceImpl.java b/src/main/java/com/ichangzuo/system/service/impl/QnAServiceImpl.java
index b3d0fe3..a3bbbc0 100644
--- a/src/main/java/com/ichangzuo/system/service/impl/QnAServiceImpl.java
+++ b/src/main/java/com/ichangzuo/system/service/impl/QnAServiceImpl.java
@@ -6,19 +6,40 @@ import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.ichangzuo.config.property.RagProperties;
import com.ichangzuo.system.mapper.QnAMapper;
import com.ichangzuo.system.model.bo.QnABO;
import com.ichangzuo.system.model.bo.QnAFullBO;
import com.ichangzuo.system.model.bo.QnAUpdateBO;
+import com.ichangzuo.system.model.dto.RagAddQVRequest;
import com.ichangzuo.system.model.entity.QnA;
import com.ichangzuo.system.model.query.QnAPageQuery;
+import com.ichangzuo.system.service.RagClientService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
-import java.util.Arrays;
-import java.util.List;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.StandardOpenOption;
+import java.util.*;
+import java.util.stream.Collectors;
@Service
public class QnAServiceImpl extends ServiceImpl {
+
+ private static final Logger log = LoggerFactory.getLogger(QnAServiceImpl.class);
+
+ private final RagClientService ragClientService;
+ private final RagProperties ragProperties;
+
+ public QnAServiceImpl(RagClientService ragClientService, RagProperties ragProperties) {
+ this.ragClientService = ragClientService;
+ this.ragProperties = ragProperties;
+ }
+
public List listByType(Integer typeId){
return baseMapper.listByType(typeId);
}
@@ -32,8 +53,11 @@ public class QnAServiceImpl extends ServiceImpl {
public boolean updateOrSave(QnAUpdateBO bo){
QnA qna = null;
- if(bo.getHelpId()==null || bo.getHelpId()==0)
+ if(bo.getHelpId()==null || bo.getHelpId()==0) {
qna = new QnA();
+ qna.setEditTime((int)(System.currentTimeMillis()/1000));
+ qna.setUserId(0L);
+ }
else
qna = getById(bo.getHelpId());
@@ -43,6 +67,9 @@ public class QnAServiceImpl extends ServiceImpl {
qna.setQuestion(bo.getQuestion());
qna.setAnswer(bo.getAnswer());
qna.setState(bo.getState());
+ if (bo.getConfidence() != null) {
+ qna.setConfidence(bo.getConfidence());
+ }
qna.setHelpTypeId(bo.getHelpTypeId());
qna.setAnswerTime((int)(System.currentTimeMillis()/1000));
@@ -67,4 +94,150 @@ public class QnAServiceImpl extends ServiceImpl {
}
return result;
}
+
+ /**
+ * 批量更新 embedded 字段
+ */
+ public void updateEmbeddedBatch(List ids, Integer embedded) {
+ if (ids == null || ids.isEmpty()) return;
+ update(new LambdaUpdateWrapper()
+ .in(QnA::getHelpId, ids)
+ .set(QnA::getEmbedded, embedded));
+ }
+
+ /**
+ * 统一向量库同步接口
+ * embedded=1: 入库 (仅处理 embedded=0 的记录)
+ * embedded=0: 移出 (仅处理 embedded=1 的记录)
+ */
+ public List updateVectors(List helpIds, Integer embedded) {
+ // 1. 查询选中的 QnA 实体
+ List qnaList = listByIds(helpIds);
+
+ // 2. 幂等过滤:入库取 embedded=0,移出取 embedded=1
+ List targetList = qnaList.stream()
+ .filter(q -> !Objects.equals(q.getEmbedded(), embedded))
+ .toList();
+
+ if (targetList.isEmpty()) {
+ return List.of();
+ }
+
+ List successIds;
+
+ if (embedded == 1) {
+ // 入库:复用现有逻辑,调用 FastAPI batch add
+ List items = targetList.stream()
+ .filter(q -> q.getEmbedded()==0
+ && (q.getState() == 3 || q.getState() == 4
+ || q.getState() == 5 || q.getState() == 6)) // 仅同步 3/4/5/6
+ .map(q -> {
+ RagAddQVRequest.QnAItem item = new RagAddQVRequest.QnAItem();
+ item.setHelpId(q.getHelpId());
+ item.setQuestion(q.getQuestion());
+ item.setHelpTypeId(q.getHelpTypeId());
+ item.setState(q.getState());
+ return item;
+ })
+ .collect(Collectors.toList());
+
+ if (items.isEmpty()) {
+ return List.of();
+ }
+
+ RagAddQVRequest request = new RagAddQVRequest();
+ request.setItems(items);
+
+ try {
+ successIds = ragClientService.addQV(request);
+ } catch (java.io.IOException e) {
+ throw new RuntimeException("向量库更新失败: " + e.getMessage(), e);
+ }
+
+ // 入库成功后导出问答到文本文件
+ exportQnAToFiles(targetList, successIds);
+ } else {
+ // 移出:调用 FastAPI batch delete
+ List targetIds = targetList.stream()
+ .filter(q -> q.getEmbedded()==1)
+ .map(QnA::getHelpId)
+ .collect(Collectors.toList());
+
+ try {
+ successIds = ragClientService.delQV(targetIds);
+ } catch (java.io.IOException e) {
+ throw new RuntimeException("向量库删除失败: " + e.getMessage(), e);
+ }
+ }
+
+ // 批量更新 MySQL embedded 字段
+ if (!successIds.isEmpty()) {
+ updateEmbeddedBatch(successIds, embedded);
+ }
+
+ return successIds;
+ }
+
+ /**
+ * 将入库成功的问答导出到文本文件
+ */
+ private void exportQnAToFiles(List qnaList, List successIds) {
+ try {
+ Set successSet = new HashSet<>(successIds);
+
+ // 按 helpTypeId 分组
+ Map> grouped = qnaList.stream()
+ .filter(q -> successSet.contains(q.getHelpId()))
+ .collect(Collectors.groupingBy(QnA::getHelpTypeId));
+
+ String exportDir = ragProperties.getExportPath();
+
+ for (Map.Entry> entry : grouped.entrySet()) {
+ String helpTypeId = entry.getKey();
+ List items = entry.getValue();
+
+ StringBuilder sb = new StringBuilder();
+ for (QnA qna : items) {
+ if (qna.getQuestion() == null || qna.getAnswer() == null) {
+ continue;
+ }
+ sb.append("问:").append(qna.getQuestion()).append("\n");
+ sb.append("答:").append(qna.getAnswer()).append("\n\n");
+ }
+
+ if (sb.isEmpty()) {
+ continue;
+ }
+
+ File dir = new File(exportDir);
+ if (!dir.exists()) {
+ Files.createDirectories(dir.toPath());
+ }
+
+ java.nio.file.Path filePath = java.nio.file.Path.of(exportDir, "qa_" + buildFileName(helpTypeId) + ".txt");
+ Files.write(filePath, sb.toString().getBytes(StandardCharsets.UTF_8),
+ StandardOpenOption.CREATE, StandardOpenOption.APPEND);
+ }
+ } catch (Exception e) {
+ log.warn("导出问答文件失败", e);
+ }
+ }
+
+ /**
+ * 将 helpTypeId(可能含逗号分隔值)转为排序后的文件名片段。
+ * 例: "0,6,3" → "036"
+ */
+ private String buildFileName(String helpTypeId) {
+ return Arrays.stream(helpTypeId.split(","))
+ .map(String::trim)
+ .filter(s -> !s.isEmpty())
+ .sorted((a, b) -> {
+ try {
+ return Integer.compare(Integer.parseInt(a), Integer.parseInt(b));
+ } catch (NumberFormatException e) {
+ return a.compareTo(b);
+ }
+ })
+ .collect(Collectors.joining());
+ }
}
diff --git a/src/main/java/com/ichangzuo/system/service/impl/QuestionPollingService.java b/src/main/java/com/ichangzuo/system/service/impl/QuestionPollingService.java
new file mode 100644
index 0000000..06e27c3
--- /dev/null
+++ b/src/main/java/com/ichangzuo/system/service/impl/QuestionPollingService.java
@@ -0,0 +1,294 @@
+package com.ichangzuo.system.service.impl;
+
+import com.ichangzuo.system.mapper.QnAMapper;
+import com.ichangzuo.system.model.bo.QnAUpdateBO;
+import com.ichangzuo.system.model.dto.*;
+import com.ichangzuo.system.model.entity.QnA;
+import com.ichangzuo.system.service.RagClientService;
+import jakarta.annotation.PreDestroy;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Service;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.Collectors;
+
+/**
+ * 问题轮询服务 - 定时拉取未读问题并逐条处理
+ *
+ * 每 {@code polling.fixedDelay}ms 执行一次轮询,每次最多拉取
+ * {@code polling.batch-size} 条 state=0 的未读问题,
+ * 先批量置为 state=1(原子性领取),再逐条串行处理。
+ *
+ * 线程模型:轮询调度器使用单线程(Spring {@code fixedDelay} 保证),
+ * 所有问题在该线程上串行执行。{@code @PreDestroy} 在独立的 JVM 关闭线程上运行。
+ */
+@Slf4j
+@Service
+@RequiredArgsConstructor
+public class QuestionPollingService {
+
+ private final QnAMapper qnAMapper;
+ private final QnAServiceImpl qnaService;
+ private final RagClientService ragClientService;
+
+ @Value("${polling.batch-size:10}")
+ private int batchSize;
+
+ /** 在途问题计数器 — 调度线程递增/递减,shutdown 线程读取 */
+ private final AtomicLong inFlightCount = new AtomicLong(0);
+
+ /**
+ * 优雅关闭用 CountDownLatch(初始计数 1,表示"尚未完成")。
+ * 当 {@link #shutdownRequested} 为 true 且 {@link #inFlightCount} 降为 0 时
+ * (或在 shutdown 时已为 0),调用 {@code countDown()} 将计数归零,
+ * 使 {@link #shutdown()} 中的 {@code await()} 返回。
+ */
+ private final CountDownLatch processingLatch = new CountDownLatch(1);
+
+ /** 优雅关闭标志位 */
+ private volatile boolean shutdownRequested = false;
+
+ // ──────────────────────────── 轮询入口 ────────────────────────────
+
+ /**
+ * 定时轮询方法,按 {@code polling.fixedDelay} 间隔执行。
+ */
+ @Scheduled(fixedDelayString = "${polling.fixedDelay:10000}")
+ public void pollAndProcess() {
+ // 1. 检查关闭请求
+ if (shutdownRequested) {
+ log.debug("轮询已请求关闭,跳过本次轮询");
+ return;
+ }
+
+ // log.debug("开始轮询未读问题,batchSize={}", batchSize);
+
+ // 2. 拉取未处理问题
+ List unreadQuestions = qnAMapper.selectUnreadForProcessing(batchSize);
+ if (unreadQuestions == null || unreadQuestions.isEmpty()) {
+ // log.debug("本次轮询无新问题");
+ return;
+ }
+
+ // 3. 收集 helpId 并原子性置为 state=1
+ List helpIds = unreadQuestions.stream()
+ .map(QnA::getHelpId)
+ .toList();
+ String idsStr = helpIds.stream()
+ .map(String::valueOf)
+ .collect(Collectors.joining(","));
+
+ boolean updated = qnaService.setByIds(idsStr, 1);
+ if (!updated) {
+ log.warn("批量设置 state=1 失败,跳过本次处理, ids={}", idsStr);
+ return;
+ }
+ // log.info("已领取 {} 条问题(state→1), ids={}", helpIds.size(), idsStr);
+
+ // 4. 逐条串行处理
+ for (QnA question : unreadQuestions) {
+ if (shutdownRequested) {
+ log.info("收到关闭请求,停止处理剩余问题");
+ break;
+ }
+
+ // 增加在途计数
+ inFlightCount.incrementAndGet();
+ try {
+ processQuestion(question);
+ } catch (Exception e) {
+ log.error("处理问题异常, helpId={}", question.getHelpId(), e);
+ // 保持 state=1(处理中),不重置为 0,避免无限重试同一条失败记录
+ question.setState(1);
+ qnaService.updateById(question);
+ } finally {
+ // 减少在途计数;若所有在途任务完成且已请求关闭,则释放 processingLatch
+ if (inFlightCount.decrementAndGet() == 0 && shutdownRequested) {
+ processingLatch.countDown();
+ }
+ }
+ }
+ }
+
+ /** 需要从 MySQL 获取答案的已匹配状态集合 */
+ private static final Set STATES_NEED_FETCH_ANSWER = Set.of(4, 6);
+
+ // ──────────────────────────── 单条处理 ────────────────────────────
+
+ /**
+ * 处理单个已领取问题(state=1):调用 RAG 生成答案 → 持久化。
+ *
+ *
+ * - 若 RAG 返回已有匹配(helpId 非空)→ 复制匹配状态/答案
+ * - 否则按置信度路由:≥ 0.9 → state=4(已回答),< 0.9 → state=2(待人工编辑)
+ *
+ *
+ * @param question 已领取的待处理问题
+ */
+ private void processQuestion(QnA question) {
+ final int helpId = question.getHelpId();
+ final String questionText = question.getQuestion();
+ final String helpTypeId = question.getHelpTypeId();
+
+ log.info("开始处理问题 helpId={}, question={}", helpId,
+ questionText != null
+ ? questionText.substring(0, Math.min(80, questionText.length()))
+ : "(null)");
+
+ RagQueryResponse queryResponse;
+ try {
+ RagQueryRequest request = new RagQueryRequest();
+ request.setQuestion(questionText);
+ request.setHelpTypeId(helpTypeId);
+ // 重复问题拦截:检查 state=3(粗口)、4(已回答)、5(无效)的历史记录
+ List duplicateRecords = qnAMapper.getDuplicateCheckRecords(question.getUserId(), helpTypeId);
+ if (questionText != null && duplicateRecords != null) {
+ for (QnA history : duplicateRecords) {
+ if (history.getQuestion() != null
+ && history.getQuestion().trim().equals(questionText.trim())) {
+ log.info("检测到重复问题, helpId={}, 重复来源 help_id={}, state={}, 置 state=5 跳过处理",
+ helpId, history.getHelpId(), history.getState());
+ question.setState(5);
+ qnaService.updateById(question);
+ return;
+ }
+ }
+ }
+
+ // 查询用户5条已回答的历史问答作为 RAG 上下文(仅 state=4)
+ List historyRecords = qnAMapper.getLatestQA(question.getUserId(), helpTypeId);
+ if (historyRecords != null && !historyRecords.isEmpty()) {
+ List historyQAList = historyRecords.stream()
+ .map(q -> "User: " + q.getQuestion() + "\nAssistant: " + q.getAnswer())
+ .toList();
+ request.setHistoryQa(historyQAList);
+ }
+ queryResponse = ragClientService.query(request);
+ } catch (IOException e) {
+ log.error("RAG 生成调用失败, helpId={}", helpId, e);
+ return;
+ }
+
+ if (queryResponse == null || !queryResponse.isSuccess()) {
+ log.warn("RAG 生成失败, helpId={}, error={}", helpId,
+ queryResponse != null ? queryResponse.getErrorMessage() : "null response");
+ return;
+ }
+
+ if (queryResponse.getHelpId() != null) {
+ handleQVMatched(question, queryResponse);
+ return;
+ }
+
+ double confidence = queryResponse.getConfidence() != null ? queryResponse.getConfidence() : 0.0;
+ String answer = queryResponse.getAnswer();
+
+ int newState;
+ if (confidence >= 0.9) {
+ newState = 4; // 已回答
+ log.info("RAG 高置信度回答, helpId={}, confidence={}", helpId, String.format("%.4f", confidence));
+ } else {
+ newState = 2; // 待人工编辑
+ log.info("RAG 低置信度回答, helpId={}, confidence={}, 转人工", helpId, String.format("%.4f", confidence));
+ }
+
+ int confidenceInt = (int) Math.round(confidence * 10000);
+ saveResult(question, answer, newState, confidenceInt);
+ }
+
+ // ──────────────────── 内部辅助方法 ────────────────────
+
+ /**
+ * QV匹配处理
+ */
+ private void handleQVMatched(QnA question, RagQueryResponse response){
+ Integer helpId = question.getHelpId();
+ Integer matchedId = response.getHelpId();
+ int matchedState = response.getHelpState();
+
+ log.info("相似度匹配成功, helpId={}, matchedHelpId={}, matchedState={}, score={}",
+ helpId, matchedId, matchedState, String.format("%.4f", response.getConfidence()));
+
+ if(STATES_NEED_FETCH_ANSWER.contains(matchedState)) { // 匹配状态 4/6:从 MySQL 获取答案
+ QnA record = qnaService.getById(matchedId);
+
+ if (record == null) {
+ log.warn("无法从 MySQL 获取匹配问题的答案, matchedId={}", matchedId);
+ return;
+ }
+
+ question.setAnswer(record.getAnswer());
+ question.setState(4);
+ }
+ else{
+ question.setState(matchedState);
+ }
+ question.setConfidence((int) Math.round(response.getConfidence() * 10000));
+ qnaService.updateById(question);
+ }
+ /**
+ * 持久化处理结果(答案 + 状态),answer_time 由 {@link QnAServiceImpl#updateOrSave} 自动设置。
+ */
+ private void saveResult(QnA question, String answer, int state, int confidence) {
+ QnAUpdateBO bo = new QnAUpdateBO();
+ bo.setHelpId(question.getHelpId());
+ bo.setQuestion(question.getQuestion());
+ bo.setHelpTypeId(question.getHelpTypeId());
+ // 将连续换行合并为单换行,避免存入数据库的格式问题
+ String cleanAnswer = answer.replace("\r\n", "\n").replaceAll("\n{2,}", "\n");
+ bo.setAnswer(cleanAnswer);
+ bo.setState(state);
+ bo.setConfidence(confidence);
+
+ boolean saved = qnaService.updateOrSave(bo);
+ if (!saved) {
+ log.error("持久化处理结果失败, helpId={}, state={}", question.getHelpId(), state);
+ return;
+ }
+
+ log.info("已保存处理结果, helpId={}, state={}", question.getHelpId(), state);
+ }
+
+ // ──────────────────────────── 优雅关闭 ────────────────────────────
+
+ /**
+ * Spring 容器关闭时触发,设置关闭标志并等待所有在途问题处理完毕。
+ *
+ * 执行流程:
+ *
+ * - 设置 {@code shutdownRequested = true},阻止后续轮询和剩余问题处理
+ * - 若当前无在途任务({@code inFlightCount == 0}),立即释放 latch
+ * - 否则等待最后一个在途任务完成后释放 latch
+ *
+ */
+ @PreDestroy
+ public void shutdown() {
+ log.info("QuestionPollingService 收到关闭信号,等待在途任务完成...");
+ shutdownRequested = true;
+
+ // 若当前无在途任务,直接释放 latch 避免永久阻塞
+ if (inFlightCount.get() == 0) {
+ processingLatch.countDown();
+ }
+
+ try {
+ boolean completed = processingLatch.await(60, TimeUnit.SECONDS);
+ if (completed) {
+ log.info("QuestionPollingService 已优雅关闭,所有在途任务已完成");
+ } else {
+ log.warn("QuestionPollingService 关闭超时(60s),可能存在未完成的在途任务");
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ log.warn("等待关闭被中断", e);
+ }
+ }
+}
diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml
index ca30b5d..c3dd49b 100644
--- a/src/main/resources/application-dev.yml
+++ b/src/main/resources/application-dev.yml
@@ -226,3 +226,17 @@ captcha:
# 验证码有效期(秒)
expire-seconds: 120
+# RAG 配置
+rag:
+ base-url: http://localhost:8990/py
+ connect-timeout: 5000
+ read-timeout: 120000
+ batch-size: 20
+ enabled: true
+ export-path: E:/iChangzuo/iChangzuoRAG/docs/qna-export
+
+# 轮询配置
+polling:
+ fixed-delay: 10000
+ batch-size: 2
+
diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml
index 1da3237..e8f7ac6 100644
--- a/src/main/resources/application-prod.yml
+++ b/src/main/resources/application-prod.yml
@@ -224,3 +224,12 @@ captcha:
# 验证码有效期(秒)
expire-seconds: 120
+# RAG 配置
+rag:
+ base-url: http://localhost:8990/py
+ connect-timeout: 5000
+ read-timeout: 120000
+ batch-size: 20
+ enabled: true
+ export-path: ./qna-export
+
diff --git a/src/main/resources/application-test.yml b/src/main/resources/application-test.yml
index f47412f..0c6885f 100644
--- a/src/main/resources/application-test.yml
+++ b/src/main/resources/application-test.yml
@@ -224,3 +224,12 @@ captcha:
# 验证码有效期(秒)
expire-seconds: 120
+# RAG 配置
+rag:
+ base-url: http://localhost:8990/py
+ connect-timeout: 5000
+ read-timeout: 120000
+ batch-size: 20
+ enabled: true
+ export-path: ./qna-export
+
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index ca8330a..01b0b1a 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -6,7 +6,7 @@ spring:
max-file-size: 500MB
max-request-size: 500MB
profiles:
- active: prod
+ active: dev
# 安全配置
security:
@@ -33,6 +33,7 @@ security:
- /api/v1/style/**
- /api/v1/notice/**
- /api/v1/statistics/**
+ - /api/v1/rag/**
- /client/**
- /ws/**
@@ -94,4 +95,18 @@ codegen:
templatePath: codegen/entity.java.vm
subpackageName: model.entity
+# RAG 配置
+rag:
+ base-url: http://localhost:8990/py
+ connect-timeout: 5000
+ read-timeout: 120000
+ batch-size: 20
+ enabled: true
+ export-path: ./qna-export
+
+# 轮询配置
+polling:
+ fixed-delay: 10000
+ batch-size: 2
+
diff --git a/src/main/resources/mapper/QnAMapper.xml b/src/main/resources/mapper/QnAMapper.xml
index 357a916..34bbed4 100644
--- a/src/main/resources/mapper/QnAMapper.xml
+++ b/src/main/resources/mapper/QnAMapper.xml
@@ -39,4 +39,24 @@
ORDER BY help_id DESC
+
+
+
+
+
+