增加rag服务
This commit is contained in:
+2
-1
@@ -12,4 +12,5 @@ target
|
||||
logs
|
||||
.history
|
||||
lib
|
||||
sql
|
||||
sql
|
||||
src/test
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
## 项目概况
|
||||
|
||||
- **开发框架**:Spring Boot 3.3.2 + Spring Security 6 + MyBatis-Plus 3.5.7
|
||||
- **开发框架**:Spring Boot 3.3.2 + Spring Security 6 + MyBatis-Plus 3.5.8
|
||||
- **安全认证**:Spring Security + JWT 无状态认证,部分接口白名单免登录
|
||||
- **权限管理**:基于 RBAC 模型,细粒度控制到接口方法和按钮级别
|
||||
- **功能模块**:用户管理、角色管理、菜单管理、部门管理、字典管理、代码生成、文件管理、邮件、短信、支付(支付宝/微信)等
|
||||
@@ -49,7 +49,7 @@ src/main/java/com/ichangzuo/
|
||||
| JDK | 17 | |
|
||||
| Spring Boot | 3.3.2 | 开发框架 |
|
||||
| Spring Security | 6 | 安全认证 |
|
||||
| MyBatis-Plus | 3.5.7 | ORM 框架 |
|
||||
| MyBatis-Plus | 3.5.8 | ORM 框架 |
|
||||
| Knife4j | 4.5.0 | 接口文档 |
|
||||
| MapStruct | 1.5.5.Final | 对象映射 |
|
||||
| Druid | 1.2.23 | 数据库连接池 |
|
||||
@@ -104,6 +104,92 @@ mvn test
|
||||
mvn clean package -DskipTests
|
||||
```
|
||||
|
||||
## RAG 智能问答集成
|
||||
|
||||
系统集成了 Python FastAPI RAG 服务(端口 8990),提供 AI 自动问答能力。
|
||||
|
||||
### 架构
|
||||
|
||||
```
|
||||
用户提问 (C++ 桌面端)
|
||||
↓
|
||||
Spring Boot (8989) — QuestionPollingService 定时轮询 state=0 的新问题
|
||||
↓
|
||||
RagClientService → FastAPI (8990/py/rag/*)
|
||||
↓
|
||||
LangGraph Pipeline: 嵌入 → 相似度匹配 → 知识库检索 → LLM 生成 → 置信度评分
|
||||
↓
|
||||
结果写回 MySQL mc_help_qa 表
|
||||
```
|
||||
|
||||
### 核心组件
|
||||
|
||||
| 组件 | 路径 | 职责 |
|
||||
|------|------|------|
|
||||
| `RagClientService` | `service/RagClientService.java` | HTTP 客户端,调用 FastAPI `/py/rag/*` 端点(含 FAQ 上传/删除) |
|
||||
| `QuestionPollingService` | `service/impl/QuestionPollingService.java` | 定时轮询(默认 10s),处理新问题,路由置信度 |
|
||||
| `RagController` | `controller/RagController.java` | 管理端 API:知识库统计、文件上传/删除(按 category 路由 FAQ/手册) |
|
||||
| `HelperController` | `controller/HelperController.java` | 问答管理:列表、编辑、入库/移出向量库 |
|
||||
| `RagConfig` | `config/RagConfig.java` | HTTP 连接池配置(最大 20 连接) |
|
||||
| `RagProperties` | `config/property/RagProperties.java` | 配置属性:`rag.baseUrl`、超时、批量大小 |
|
||||
|
||||
### RAG 端点(Spring Boot → FastAPI)
|
||||
|
||||
| Spring Boot 端点 | 转发到 FastAPI | 说明 |
|
||||
|---|---|---|
|
||||
| `POST /api/v1/rag/query` | `POST /py/rag/query` | RAG 智能问答 |
|
||||
| `GET /api/v1/rag/kb/stats` | `GET /py/rag/stats` | 知识库统计 |
|
||||
| `GET /api/v1/rag/kb/files` | MySQL 直读 | 文件列表(Java 侧管理,含 `fileCategory`) |
|
||||
| `POST /api/v1/rag/kb/upload` | `POST /py/rag/addKF` 或 `/py/rag/addQAF` | 上传文档,按 `category` 路由:0=手册→addKF,1=FAQ→addQAF |
|
||||
| `DELETE /api/v1/rag/kb/files/{fileId}` | `DELETE /py/rag/delKF/{fileId}` 或 `/py/rag/delQAF/{fileId}` | 删除文档,按 `fileCategory` 路由 |
|
||||
|
||||
### 问答管理端点
|
||||
|
||||
| 端点 | 说明 |
|
||||
|---|---|
|
||||
| `GET /api/v1/helper/listQnA/{id}` | 按类型获取问答列表 |
|
||||
| `GET /api/v1/helper/pageQnA` | 分页查询问答 |
|
||||
| `PUT /api/v1/helper/updateQnA` | 新增/编辑问答 |
|
||||
| `PUT /api/v1/helper/setQnAByIds/{ids}` | 批量设置状态 |
|
||||
| `POST /api/v1/helper/updateVectors` | 批量入库/移出向量库 |
|
||||
|
||||
### 问题处理流程
|
||||
|
||||
1. C++ 桌面端提交问题 → MySQL `mc_help_qa` (state=0)
|
||||
2. `QuestionPollingService` 每 10s 轮询 → 批量 claim (state=0→1)
|
||||
3. 重复问题拦截:与历史记录(state=3/4/5)比对,重复 → state=5 跳过
|
||||
4. 逐条调用 `RagClientService.query()` → FastAPI RAG 流水线
|
||||
5. 命中问题库(helpId 非空)→ 复制匹配状态与答案(匹配 state=4/6 时从 MySQL 取答案)
|
||||
6. 未命中:置信度 ≥ 0.9 → 自动通过 (state=4);< 0.9 → 待人工编辑 (state=2)
|
||||
7. 人工审核 → 编辑/批准/不处理/无效/发布
|
||||
|
||||
### 问题状态机
|
||||
|
||||
| state | 含义 | 说明 |
|
||||
|-------|------|------|
|
||||
| 0 | 未查阅 | C++ 桌面端提交的初始状态 |
|
||||
| 1 | 已领取 | 轮询服务原子性 claim,处理中 |
|
||||
| 2 | 待人工编辑 | RAG 置信度 < 0.9,转人工 |
|
||||
| 3 | 不处理 | 粗口/违规,人工标记 |
|
||||
| 4 | 已回答 | RAG 置信度 ≥ 0.9 自动通过,或 QV 匹配复制 |
|
||||
| 5 | 无效 | 重复问题,自动跳过 |
|
||||
| 6 | 公开 | 已发布,QV 匹配时从 MySQL 取答案 |
|
||||
|
||||
### 配置
|
||||
|
||||
```yaml
|
||||
rag:
|
||||
base-url: http://localhost:8990/py # FastAPI 地址
|
||||
connect-timeout: 5000 # 连接超时 (ms)
|
||||
read-timeout: 120000 # 读取超时 (ms)
|
||||
batch-size: 20 # 批量操作大小
|
||||
enabled: true # 是否启用 RAG
|
||||
|
||||
polling:
|
||||
fixed-delay: 10000 # 轮询间隔 (ms)
|
||||
batch-size: 2 # 每轮最多处理条数
|
||||
```
|
||||
|
||||
## 接口文档
|
||||
- `knife4j` 接口文档:[http://localhost:8989/doc.html](http://localhost:8989/doc.html)
|
||||
- `swagger` 接口文档:[http://localhost:8989/swagger-ui/index.html](http://localhost:8989/swagger-ui/index.html)
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>com.ichangzuo</groupId>
|
||||
<artifactId>server-java</artifactId>
|
||||
<version>1.9</version>
|
||||
<version>2.0</version>
|
||||
<description>基于 Java 17 + SpringBoot 3 + Spring Security 构建的唱作网系统。</description>
|
||||
|
||||
<parent>
|
||||
@@ -24,7 +24,7 @@
|
||||
|
||||
<mysql.version>8.0.28</mysql.version>
|
||||
<druid.version>1.2.23</druid.version>
|
||||
<mybatis-plus.version>3.5.7</mybatis-plus.version>
|
||||
<mybatis-plus.version>3.5.8</mybatis-plus.version>
|
||||
|
||||
<knife4j.version>4.5.0</knife4j.version>
|
||||
|
||||
@@ -250,6 +250,32 @@
|
||||
<artifactId>httpclient5</artifactId>
|
||||
<version>5.1</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Test dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>testcontainers</artifactId>
|
||||
<version>1.19.8</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>mysql</artifactId>
|
||||
<version>1.19.8</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>1.19.8</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.squareup.okhttp3</groupId>
|
||||
<artifactId>mockwebserver</artifactId>
|
||||
<version>4.12.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<profiles>
|
||||
@@ -303,12 +329,12 @@
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<layout>ZIP</layout>
|
||||
<includes>
|
||||
<!-- <includes>
|
||||
<include>
|
||||
<groupId>nothing</groupId>
|
||||
<artifactId>nothing</artifactId>
|
||||
</include>
|
||||
</includes>
|
||||
</includes> -->
|
||||
<excludes>
|
||||
<exclude>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.ichangzuo.config;
|
||||
|
||||
import com.ichangzuo.config.property.RagProperties;
|
||||
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
|
||||
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
|
||||
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
|
||||
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
|
||||
import org.apache.hc.core5.util.Timeout;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
/**
|
||||
* RAG 服务配置类
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Configuration
|
||||
public class RagConfig {
|
||||
|
||||
private final RagProperties ragProperties;
|
||||
|
||||
public RagConfig(RagProperties ragProperties) {
|
||||
this.ragProperties = ragProperties;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CloseableHttpClient ragHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
|
||||
HttpClientConnectionManager connManager = PoolingHttpClientConnectionManagerBuilder.create()
|
||||
.setMaxConnTotal(20)
|
||||
.setMaxConnPerRoute(10)
|
||||
.build();
|
||||
|
||||
return HttpClientBuilder.create()
|
||||
.setConnectionManager(connManager)
|
||||
.setConnectionManagerShared(true)
|
||||
.evictIdleConnections(Timeout.ofSeconds(30))
|
||||
.evictExpiredConnections()
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ichangzuo.config.property;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* RAG 服务配置属性
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "rag")
|
||||
public class RagProperties {
|
||||
|
||||
/**
|
||||
* FastAPI RAG 服务基础地址
|
||||
*/
|
||||
private String baseUrl = "http://localhost:8990/py";
|
||||
|
||||
/**
|
||||
* 连接超时时间(毫秒)
|
||||
*/
|
||||
private int connectTimeout = 5000;
|
||||
|
||||
/**
|
||||
* 读取超时时间(毫秒)
|
||||
*/
|
||||
private int readTimeout = 120000;
|
||||
|
||||
/**
|
||||
* 分批处理大小
|
||||
*/
|
||||
private int batchSize = 20;
|
||||
|
||||
/**
|
||||
* 是否启用 RAG 服务
|
||||
*/
|
||||
private boolean enabled = true;
|
||||
|
||||
/**
|
||||
* 入库问答导出文件目录
|
||||
*/
|
||||
private String exportPath = "./qna-export";
|
||||
}
|
||||
@@ -3,10 +3,7 @@ package com.ichangzuo;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.annotation.EnableTransactionManagement;
|
||||
|
||||
/**
|
||||
* 应用启动类
|
||||
|
||||
@@ -8,12 +8,18 @@ import com.ichangzuo.system.model.bo.QnAFullBO;
|
||||
import com.ichangzuo.system.model.bo.QnAUpdateBO;
|
||||
import com.ichangzuo.system.model.query.QnAPageQuery;
|
||||
import com.ichangzuo.system.service.impl.QnAServiceImpl;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Tag(name = "帮助中心/问题库管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/helper")
|
||||
@RequiredArgsConstructor
|
||||
@@ -46,4 +52,42 @@ public class HelperController {
|
||||
boolean result = qnaService.setByIds(ids,state);
|
||||
return Result.judge(result);
|
||||
}
|
||||
|
||||
@Operation(summary = "更新向量库(同步选中问题到 FastAPI RAG 服务)")
|
||||
@PostMapping("/updateVectors")
|
||||
public Result<List<Integer>> updateVectors(
|
||||
@Parameter(description = "QnAID,多个以英文逗号(,)分割") @RequestParam String ids,
|
||||
@Parameter(description = "操作方向:1=入库, 0=移出") @RequestParam Integer embedded
|
||||
) {
|
||||
try {
|
||||
if (StrUtil.isBlank(ids)) {
|
||||
return Result.failed("ids 不能为空");
|
||||
}
|
||||
|
||||
if (embedded != 0 && embedded != 1) {
|
||||
return Result.failed("embedded 参数必须为 0 或 1");
|
||||
}
|
||||
|
||||
// 解析前端传入的逗号分隔字符串
|
||||
List<Integer> helpIds = Arrays.stream(ids.split(","))
|
||||
.map(String::trim)
|
||||
.filter(StrUtil::isNotBlank)
|
||||
.map(Integer::parseInt)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (helpIds.isEmpty()) {
|
||||
return Result.failed("无有效的 helpId");
|
||||
}
|
||||
|
||||
// 调用 Service 统一处理入库/移出
|
||||
List<Integer> successIds = qnaService.updateVectors(helpIds, embedded);
|
||||
if (embedded == 0 && successIds.isEmpty()) {
|
||||
return Result.failed("向量库删除失败,请检查 ragservice 日志后重试");
|
||||
}
|
||||
return Result.success(successIds);
|
||||
|
||||
} catch (Exception e) {
|
||||
return Result.failed("向量库更新失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package com.ichangzuo.system.controller;
|
||||
|
||||
import com.ichangzuo.common.result.Result;
|
||||
import com.ichangzuo.system.model.dto.*;
|
||||
import com.ichangzuo.system.model.entity.KbFile;
|
||||
import com.ichangzuo.system.service.IKbFileService;
|
||||
import com.ichangzuo.system.service.RagClientService;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* RAG 问答接口
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Tag(name = "RAG 问答接口")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/rag")
|
||||
@RequiredArgsConstructor
|
||||
public class RagController {
|
||||
|
||||
private final RagClientService ragClientService;
|
||||
private final IKbFileService kbFileService;
|
||||
|
||||
@Operation(summary = "RAG 智能问答 --用于curl调试")
|
||||
@PostMapping("/query")
|
||||
public Result<RagQueryResponse> query(@RequestBody RagQueryRequest request) {
|
||||
try {
|
||||
RagQueryResponse response = ragClientService.query(request);
|
||||
return Result.success(response);
|
||||
} catch (Exception e) {
|
||||
return Result.failed("RAG 查询失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "获取知识库统计信息")
|
||||
@GetMapping("/kb/stats")
|
||||
public Result<RagKnowledgeStatsResponse> getKnowledgeStats() {
|
||||
try {
|
||||
RagKnowledgeStatsResponse response = ragClientService.getStats();
|
||||
return Result.success(response);
|
||||
} catch (Exception e) {
|
||||
return Result.failed("获取知识库统计失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "获取知识库文件列表")
|
||||
@GetMapping("/kb/files")
|
||||
public Result<RagKnowledgeFileListResponse> getKnowledgeFiles() {
|
||||
try {
|
||||
// 直接从 MySQL 读取,不再转发到 Python
|
||||
List<KbFile> dbFiles = kbFileService.list(
|
||||
new LambdaQueryWrapper<KbFile>()
|
||||
.orderByDesc(KbFile::getUploadTime)
|
||||
);
|
||||
RagKnowledgeFileListResponse resp = new RagKnowledgeFileListResponse();
|
||||
resp.setSuccess(true);
|
||||
resp.setFiles(dbFiles.stream().map(f -> {
|
||||
RagKnowledgeFileInfo dto = new RagKnowledgeFileInfo();
|
||||
dto.setFileId(f.getFileId());
|
||||
dto.setFileName(f.getFileName());
|
||||
dto.setHelpTypeId(f.getHelpTypeId());
|
||||
dto.setUploadTime(f.getUploadTime());
|
||||
dto.setChunkCount(f.getChunkCount());
|
||||
dto.setFileCategory(f.getFileCategory());
|
||||
return dto;
|
||||
}).collect(Collectors.toList()));
|
||||
return Result.success(resp);
|
||||
} catch (Exception e) {
|
||||
return Result.failed("获取文件列表失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "上传知识库文档(仅支持 TXT/MD)")
|
||||
@PostMapping("/kb/upload")
|
||||
public Result<RagKBUploadResponse> uploadKnowledgeFile(
|
||||
@RequestPart MultipartFile file,
|
||||
@RequestParam String helpTypeId,
|
||||
@RequestParam(required = false, defaultValue = "0") int category) {
|
||||
try {
|
||||
// 1. 先调 Python 完成向量化(category=1 → addQAF,否则 addKF)
|
||||
RagKBUploadResponse response = (category == 1)
|
||||
? ragClientService.addQAF(file, helpTypeId)
|
||||
: ragClientService.addKF(file, helpTypeId);
|
||||
if (!response.isSuccess()) {
|
||||
return Result.failed(response.getErrorMessage());
|
||||
}
|
||||
// 2. Python 成功后写 MySQL,使用 ChromaDB 生成的 file_id
|
||||
KbFile kbFile = new KbFile();
|
||||
kbFile.setFileId(response.getFileId());
|
||||
kbFile.setFileName(file.getOriginalFilename());
|
||||
kbFile.setHelpTypeId(helpTypeId);
|
||||
kbFile.setChunkCount(response.getChunkCount());
|
||||
kbFile.setUploadTime(System.currentTimeMillis() / 1000);
|
||||
kbFile.setFileCategory(category);
|
||||
try {
|
||||
kbFileService.save(kbFile);
|
||||
} catch (Exception dbEx) {
|
||||
// 3. MySQL 写库失败 → 回滚 Python 端向量数据,避免 ChromaDB 有向量而 MySQL 无记录(审查 M2)
|
||||
if (category == 1) {
|
||||
ragClientService.delQAF(response.getFileId());
|
||||
} else {
|
||||
ragClientService.delKF(response.getFileId());
|
||||
}
|
||||
throw dbEx;
|
||||
}
|
||||
return Result.success(response);
|
||||
} catch (Exception e) {
|
||||
return Result.failed("知识库文档上传失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "删除知识库文件")
|
||||
@DeleteMapping("/kb/files/{fileId}")
|
||||
public Result<Void> deleteKnowledgeFile(@PathVariable Long fileId) {
|
||||
try {
|
||||
// 0. 按 file_category 路由到 delQAF / delKF
|
||||
KbFile dbFile = kbFileService.getById(fileId);
|
||||
if (dbFile == null) {
|
||||
// 文件不存在,直接拒绝,避免错误降级到 delKF(审查 B3)
|
||||
return Result.failed("文件不存在或已删除");
|
||||
}
|
||||
boolean pythonOk;
|
||||
if (dbFile.getFileCategory() != null && dbFile.getFileCategory() == 1) {
|
||||
pythonOk = ragClientService.delQAF(fileId);
|
||||
} else {
|
||||
pythonOk = ragClientService.delKF(fileId);
|
||||
}
|
||||
if (!pythonOk) {
|
||||
return Result.failed("Python 删除向量数据失败");
|
||||
}
|
||||
// 2. Python 成功后从 MySQL 删除
|
||||
kbFileService.removeById(fileId);
|
||||
return Result.success();
|
||||
} catch (Exception e) {
|
||||
return Result.failed("删除文件失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.ichangzuo.system.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.ichangzuo.system.model.entity.KbFile;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface KbFileMapper extends BaseMapper<KbFile> {
|
||||
}
|
||||
@@ -7,6 +7,9 @@ import com.ichangzuo.system.model.bo.QnAFullBO;
|
||||
import com.ichangzuo.system.model.entity.QnA;
|
||||
import com.ichangzuo.system.model.query.QnAPageQuery;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -15,4 +18,11 @@ public interface QnAMapper extends BaseMapper<QnA> {
|
||||
List<QnABO> listByType(Integer typeId);
|
||||
|
||||
Page<QnAFullBO> listPage(Page<QnAFullBO> page, QnAPageQuery queryParams);
|
||||
|
||||
List<QnA> selectUnreadForProcessing(@Param("batchSize") int batchSize);
|
||||
|
||||
@Select("SELECT help_id, question, answer FROM mc_help_qa WHERE state = 4 AND user_id = #{userId} AND help_type_id = #{helpTypeId} ORDER BY help_id DESC LIMIT 5")
|
||||
List<QnA> getLatestQA(@Param("userId") Long userId, @Param("helpTypeId") String helpTypeId);
|
||||
|
||||
List<QnA> getDuplicateCheckRecords(@Param("userId") Long userId, @Param("helpTypeId") String helpTypeId);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,8 @@
|
||||
package com.ichangzuo.system.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.Wrapper;
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Constants;
|
||||
import com.ichangzuo.common.annotation.DataPermission;
|
||||
import com.ichangzuo.system.model.entity.Dept;
|
||||
import com.ichangzuo.system.model.entity.Software;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface SoftwareMapper extends BaseMapper<Software> {
|
||||
|
||||
@@ -7,4 +7,5 @@ public class QnABO {
|
||||
private Integer helpId;
|
||||
private String question;
|
||||
private String answer;
|
||||
private Integer confidence;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RAG 更新向量库请求
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Data
|
||||
public class RagAddQVRequest {
|
||||
|
||||
/**
|
||||
* 问答项列表
|
||||
*/
|
||||
private List<QnAItem> items;
|
||||
|
||||
@Data
|
||||
public static class QnAItem {
|
||||
/**
|
||||
* 问题ID
|
||||
*/
|
||||
private Integer helpId;
|
||||
|
||||
/**
|
||||
* 问题内容(仅向量化该字段)
|
||||
*/
|
||||
private String question;
|
||||
|
||||
/**
|
||||
* 客户端类型编号(存入元数据)
|
||||
*/
|
||||
private String helpTypeId;
|
||||
|
||||
/**
|
||||
* 状态(存入元数据)
|
||||
*/
|
||||
private Integer state;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RAG 批量删除向量库响应
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2026/8/26
|
||||
*/
|
||||
@Data
|
||||
public class RagBatchDeleteResponse {
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
private boolean success;
|
||||
|
||||
/**
|
||||
* 成功删除的 ID 列表
|
||||
*/
|
||||
private List<Integer> successIds;
|
||||
|
||||
/**
|
||||
* 失败的 ID 列表
|
||||
*/
|
||||
private List<Integer> failedIds;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
private String errorMessage;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RAG 批量删除向量库请求
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2026/8/26
|
||||
*/
|
||||
@Data
|
||||
public class RagDelQVRequest {
|
||||
|
||||
/**
|
||||
* 问题ID列表
|
||||
*/
|
||||
private List<Integer> helpIds;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* RAG 生成回答请求参数
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Data
|
||||
public class RagGenerateRequest {
|
||||
|
||||
/**
|
||||
* 问题内容
|
||||
*/
|
||||
private String question;
|
||||
|
||||
/**
|
||||
* 帮助类型 ID
|
||||
*/
|
||||
@JsonProperty("helpTypeId")
|
||||
private String helpTypeId;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RAG 生成回答响应
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Data
|
||||
public class RagGenerateResponse {
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
private boolean success;
|
||||
|
||||
/**
|
||||
* 回答内容
|
||||
*/
|
||||
private String answer;
|
||||
|
||||
/**
|
||||
* 置信度分数 (0-1)
|
||||
*/
|
||||
private Double confidence;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
@JsonProperty("errorMessage")
|
||||
private String errorMessage;
|
||||
|
||||
/**
|
||||
* RAG 服务禁用时的默认响应
|
||||
*/
|
||||
public static RagGenerateResponse disabled() {
|
||||
RagGenerateResponse r = new RagGenerateResponse();
|
||||
r.setSuccess(false);
|
||||
r.setErrorMessage("RAG service disabled");
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* RAG 知识库文档上传响应
|
||||
*
|
||||
* <p>与 Python FastAPI 服务 {@code /api/v1/knowledge/upload} 的
|
||||
* {@code KnowledgeUploadResponse} 字段契约保持一致。</p>
|
||||
*
|
||||
* @author haoxr
|
||||
*/
|
||||
@Data
|
||||
public class RagKBUploadResponse {
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
private boolean success;
|
||||
|
||||
/**
|
||||
* 文件 ID
|
||||
*/
|
||||
private Long fileId;
|
||||
|
||||
/**
|
||||
* 分块数
|
||||
*/
|
||||
private Integer chunkCount;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
private String errorMessage;
|
||||
|
||||
/**
|
||||
* RAG 服务禁用时的默认响应
|
||||
*/
|
||||
public static RagKBUploadResponse disabled() {
|
||||
RagKBUploadResponse r = new RagKBUploadResponse();
|
||||
r.setSuccess(false);
|
||||
r.setErrorMessage("RAG service disabled");
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* RAG 知识库文件信息
|
||||
*
|
||||
* <p>与 Python FastAPI 服务 {@code /api/v1/knowledge/files} 返回的
|
||||
* 文件列表项字段契约保持一致。</p>
|
||||
*
|
||||
* @author haoxr
|
||||
*/
|
||||
@Data
|
||||
public class RagKnowledgeFileInfo {
|
||||
|
||||
/**
|
||||
* 文件 ID
|
||||
*/
|
||||
private Long fileId;
|
||||
|
||||
/**
|
||||
* 文件名
|
||||
*/
|
||||
private String fileName;
|
||||
|
||||
/**
|
||||
* 帮助类型 ID
|
||||
*/
|
||||
private String helpTypeId;
|
||||
|
||||
/**
|
||||
* 上传时间(Unix 时间戳)
|
||||
*/
|
||||
private Long uploadTime;
|
||||
|
||||
/**
|
||||
* 分块数
|
||||
*/
|
||||
private Integer chunkCount;
|
||||
|
||||
/**
|
||||
* 文件分类:0=manual, 1=faq
|
||||
*/
|
||||
private Integer fileCategory;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RAG 知识库文件列表响应
|
||||
*
|
||||
* <p>与 Python FastAPI 服务 {@code /api/v1/knowledge/files} 的
|
||||
* 字段契约保持一致。</p>
|
||||
*
|
||||
* @author haoxr
|
||||
*/
|
||||
@Data
|
||||
public class RagKnowledgeFileListResponse {
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
private boolean success;
|
||||
|
||||
/**
|
||||
* 文件列表
|
||||
*/
|
||||
private List<RagKnowledgeFileInfo> files = java.util.Collections.emptyList();
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
private String errorMessage;
|
||||
|
||||
/**
|
||||
* RAG 服务禁用时的默认响应
|
||||
*/
|
||||
public static RagKnowledgeFileListResponse disabled() {
|
||||
RagKnowledgeFileListResponse r = new RagKnowledgeFileListResponse();
|
||||
r.setSuccess(false);
|
||||
r.setErrorMessage("RAG service disabled");
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* RAG 知识库统计响应
|
||||
*
|
||||
* <p>与 Python FastAPI 服务 {@code /api/v1/knowledge/stats} 的
|
||||
* 字段契约保持一致。</p>
|
||||
*
|
||||
* @author haoxr
|
||||
*/
|
||||
@Data
|
||||
public class RagKnowledgeStatsResponse {
|
||||
|
||||
/**
|
||||
* 分块总数
|
||||
*/
|
||||
private Integer chunkCount;
|
||||
|
||||
/**
|
||||
* 文档总数
|
||||
*/
|
||||
private Integer docCount;
|
||||
|
||||
/**
|
||||
* 最后更新时间
|
||||
*/
|
||||
private String lastUpdate;
|
||||
|
||||
/**
|
||||
* RAG 服务禁用时的默认响应
|
||||
*/
|
||||
public static RagKnowledgeStatsResponse disabled() {
|
||||
RagKnowledgeStatsResponse r = new RagKnowledgeStatsResponse();
|
||||
r.setChunkCount(0);
|
||||
r.setDocCount(0);
|
||||
r.setLastUpdate(null);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RAG 查询请求参数
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Data
|
||||
public class RagQueryRequest {
|
||||
|
||||
/**
|
||||
* 问题内容
|
||||
*/
|
||||
private String question;
|
||||
|
||||
/**
|
||||
* 返回文档数量
|
||||
*/
|
||||
private Integer topK = 5;
|
||||
|
||||
/**
|
||||
* 相似度阈值
|
||||
*/
|
||||
private Double scoreThreshold = 0.7;
|
||||
|
||||
/**
|
||||
* 帮助类型 ID
|
||||
*/
|
||||
@JsonProperty("helpTypeId")
|
||||
private String helpTypeId;
|
||||
|
||||
/**
|
||||
* 历史问答列表(格式化字符串)
|
||||
*/
|
||||
private List<String> historyQa = new java.util.ArrayList<>();
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RAG 查询响应
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Data
|
||||
public class RagQueryResponse {
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
private boolean success;
|
||||
|
||||
/**
|
||||
* 回答内容
|
||||
*/
|
||||
private String answer;
|
||||
|
||||
/**
|
||||
* QV中检索到help_id
|
||||
*/
|
||||
@JsonProperty("helpId")
|
||||
private Integer helpId;
|
||||
|
||||
/**
|
||||
* QV中检索到help_state
|
||||
*/
|
||||
@JsonProperty("helpState")
|
||||
private Integer helpState;
|
||||
|
||||
/**
|
||||
* 置信度分数 (0-1)
|
||||
*/
|
||||
private Double confidence;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
@JsonProperty("errorMessage")
|
||||
private String errorMessage;
|
||||
|
||||
/**
|
||||
* RAG 服务禁用时的默认响应
|
||||
*/
|
||||
public static RagQueryResponse disabled() {
|
||||
RagQueryResponse r = new RagQueryResponse();
|
||||
r.setSuccess(false);
|
||||
r.setErrorMessage("RAG service disabled");
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 相似问题搜索请求参数
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Data
|
||||
public class RagSearchRequest {
|
||||
|
||||
/**
|
||||
* 问题内容
|
||||
*/
|
||||
private String question;
|
||||
|
||||
/**
|
||||
* 帮助类型 ID
|
||||
*/
|
||||
@JsonProperty("helpTypeId")
|
||||
private String helpTypeId;
|
||||
|
||||
/**
|
||||
* 返回结果数量
|
||||
*/
|
||||
private Integer topK = 5;
|
||||
|
||||
/**
|
||||
* 相似度阈值
|
||||
*/
|
||||
private Double threshold = 0.9;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 相似问题搜索响应
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Data
|
||||
public class RagSearchResponse {
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
private boolean success;
|
||||
|
||||
/**
|
||||
* 匹配结果列表
|
||||
*/
|
||||
@JsonProperty("matches")
|
||||
private List<MatchedQuestion> results;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
@JsonProperty("errorMessage")
|
||||
private String errorMessage;
|
||||
|
||||
@Data
|
||||
public static class MatchedQuestion {
|
||||
|
||||
/**
|
||||
* 帮助文档 ID
|
||||
*/
|
||||
@JsonProperty("helpId")
|
||||
private Long helpId;
|
||||
|
||||
/**
|
||||
* 状态
|
||||
*/
|
||||
private String state;
|
||||
|
||||
/**
|
||||
* 答案内容
|
||||
*/
|
||||
private String answer;
|
||||
|
||||
/**
|
||||
* 相似度分数
|
||||
*/
|
||||
private Double score;
|
||||
}
|
||||
|
||||
/**
|
||||
* RAG 服务禁用时的默认响应
|
||||
*/
|
||||
public static RagSearchResponse disabled() {
|
||||
RagSearchResponse r = new RagSearchResponse();
|
||||
r.setSuccess(false);
|
||||
r.setErrorMessage("RAG service disabled");
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* 空响应(无匹配结果)
|
||||
*/
|
||||
public static RagSearchResponse empty() {
|
||||
RagSearchResponse r = new RagSearchResponse();
|
||||
r.setSuccess(true);
|
||||
r.setResults(List.of());
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RAG 更新向量库响应
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2024/8/21
|
||||
*/
|
||||
@Data
|
||||
public class RagUpdQVResponse {
|
||||
|
||||
/**
|
||||
* 是否成功
|
||||
*/
|
||||
private boolean success;
|
||||
|
||||
/**
|
||||
* 成功的 help_id 数组(Python 侧直接返回,Java 直接用于更新 SQL 库)
|
||||
*/
|
||||
private List<Integer> successIds;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
private String errorMessage;
|
||||
|
||||
/**
|
||||
* RAG 服务禁用时的默认响应
|
||||
*/
|
||||
public static RagUpdQVResponse disabled() {
|
||||
RagUpdQVResponse r = new RagUpdQVResponse();
|
||||
r.setSuccess(false);
|
||||
r.setErrorMessage("RAG service disabled");
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ichangzuo.system.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* RAG 更新向量库结果(前端视图)
|
||||
*
|
||||
* <p>与内部契约 {@link RagUpdateVectorResponse}(Python↔Java,含 details)不同,
|
||||
* 该 VO 仅向前端暴露成功 help_id 数组,不暴露 details 明细。
|
||||
*
|
||||
* @author haoxr
|
||||
*/
|
||||
@Data
|
||||
public class RagUpdateVectorResultVO {
|
||||
|
||||
/**
|
||||
* 成功的 help_id 数组(条数即数组长度)
|
||||
*/
|
||||
private List<Integer> successIds;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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=已入库
|
||||
}
|
||||
|
||||
@@ -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<KbFile> {
|
||||
}
|
||||
@@ -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<String> 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<Integer> addQV(RagAddQVRequest request) throws IOException {
|
||||
String url = ragProperties.getBaseUrl() + "/rag/addQV";
|
||||
List<RagAddQVRequest.QnAItem> allItems = request.getItems();
|
||||
int batchSize = ragProperties.getBatchSize();
|
||||
List<Integer> totalSuccessIds = new ArrayList<>();
|
||||
|
||||
for (int i = 0; i < allItems.size(); i += batchSize) {
|
||||
List<RagAddQVRequest.QnAItem> 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<Integer> delQV(List<Integer> 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)
|
||||
*
|
||||
* <p>在网关层做扩展名白名单校验(统一小写,拒绝无扩展名),
|
||||
* 合法格式以 multipart/form-data 转发到 Python
|
||||
* {@code /knowledge/upload},字段契约与 Python 一致(file + help_type_id)。</p>
|
||||
*
|
||||
* @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> T executePost(String url, Object request, Class<T> 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> T executeGet(String url, Class<T> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.datao.service.alipay;
|
||||
package com.ichangzuo.system.service.alipay;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.datao.service.alipay;
|
||||
package com.ichangzuo.system.service.alipay;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.*;
|
||||
|
||||
@@ -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<KbFileMapper, KbFile> implements IKbFileService {
|
||||
}
|
||||
@@ -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<QnAMapper, QnA> {
|
||||
|
||||
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<QnABO> listByType(Integer typeId){
|
||||
return baseMapper.listByType(typeId);
|
||||
}
|
||||
@@ -32,8 +53,11 @@ public class QnAServiceImpl extends ServiceImpl<QnAMapper, QnA> {
|
||||
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<QnAMapper, QnA> {
|
||||
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<QnAMapper, QnA> {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新 embedded 字段
|
||||
*/
|
||||
public void updateEmbeddedBatch(List<Integer> ids, Integer embedded) {
|
||||
if (ids == null || ids.isEmpty()) return;
|
||||
update(new LambdaUpdateWrapper<QnA>()
|
||||
.in(QnA::getHelpId, ids)
|
||||
.set(QnA::getEmbedded, embedded));
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一向量库同步接口
|
||||
* embedded=1: 入库 (仅处理 embedded=0 的记录)
|
||||
* embedded=0: 移出 (仅处理 embedded=1 的记录)
|
||||
*/
|
||||
public List<Integer> updateVectors(List<Integer> helpIds, Integer embedded) {
|
||||
// 1. 查询选中的 QnA 实体
|
||||
List<QnA> qnaList = listByIds(helpIds);
|
||||
|
||||
// 2. 幂等过滤:入库取 embedded=0,移出取 embedded=1
|
||||
List<QnA> targetList = qnaList.stream()
|
||||
.filter(q -> !Objects.equals(q.getEmbedded(), embedded))
|
||||
.toList();
|
||||
|
||||
if (targetList.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<Integer> successIds;
|
||||
|
||||
if (embedded == 1) {
|
||||
// 入库:复用现有逻辑,调用 FastAPI batch add
|
||||
List<RagAddQVRequest.QnAItem> 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<Integer> 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<QnA> qnaList, List<Integer> successIds) {
|
||||
try {
|
||||
Set<Integer> successSet = new HashSet<>(successIds);
|
||||
|
||||
// 按 helpTypeId 分组
|
||||
Map<String, List<QnA>> grouped = qnaList.stream()
|
||||
.filter(q -> successSet.contains(q.getHelpId()))
|
||||
.collect(Collectors.groupingBy(QnA::getHelpTypeId));
|
||||
|
||||
String exportDir = ragProperties.getExportPath();
|
||||
|
||||
for (Map.Entry<String, List<QnA>> entry : grouped.entrySet()) {
|
||||
String helpTypeId = entry.getKey();
|
||||
List<QnA> 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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/**
|
||||
* 问题轮询服务 - 定时拉取未读问题并逐条处理
|
||||
*
|
||||
* <p>每 {@code polling.fixedDelay}ms 执行一次轮询,每次最多拉取
|
||||
* {@code polling.batch-size} 条 state=0 的未读问题,
|
||||
* 先批量置为 state=1(原子性领取),再逐条串行处理。</p>
|
||||
*
|
||||
* <p>线程模型:轮询调度器使用单线程(Spring {@code fixedDelay} 保证),
|
||||
* 所有问题在该线程上串行执行。{@code @PreDestroy} 在独立的 JVM 关闭线程上运行。</p>
|
||||
*/
|
||||
@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,表示"尚未完成")。
|
||||
* <p>当 {@link #shutdownRequested} 为 true 且 {@link #inFlightCount} 降为 0 时
|
||||
* (或在 shutdown 时已为 0),调用 {@code countDown()} 将计数归零,
|
||||
* 使 {@link #shutdown()} 中的 {@code await()} 返回。</p>
|
||||
*/
|
||||
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<QnA> unreadQuestions = qnAMapper.selectUnreadForProcessing(batchSize);
|
||||
if (unreadQuestions == null || unreadQuestions.isEmpty()) {
|
||||
// log.debug("本次轮询无新问题");
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. 收集 helpId 并原子性置为 state=1
|
||||
List<Integer> 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<Integer> STATES_NEED_FETCH_ANSWER = Set.of(4, 6);
|
||||
|
||||
// ──────────────────────────── 单条处理 ────────────────────────────
|
||||
|
||||
/**
|
||||
* 处理单个已领取问题(state=1):调用 RAG 生成答案 → 持久化。
|
||||
*
|
||||
* <ul>
|
||||
* <li>若 RAG 返回已有匹配(helpId 非空)→ 复制匹配状态/答案</li>
|
||||
* <li>否则按置信度路由:≥ 0.9 → state=4(已回答),< 0.9 → state=2(待人工编辑)</li>
|
||||
* </ul>
|
||||
*
|
||||
* @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<QnA> 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<QnA> historyRecords = qnAMapper.getLatestQA(question.getUserId(), helpTypeId);
|
||||
if (historyRecords != null && !historyRecords.isEmpty()) {
|
||||
List<String> 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 容器关闭时触发,设置关闭标志并等待所有在途问题处理完毕。
|
||||
*
|
||||
* <p>执行流程:</p>
|
||||
* <ol>
|
||||
* <li>设置 {@code shutdownRequested = true},阻止后续轮询和剩余问题处理</li>
|
||||
* <li>若当前无在途任务({@code inFlightCount == 0}),立即释放 latch</li>
|
||||
* <li>否则等待最后一个在途任务完成后释放 latch</li>
|
||||
* </ol>
|
||||
*/
|
||||
@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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -39,4 +39,24 @@
|
||||
</where>
|
||||
ORDER BY help_id DESC
|
||||
</select>
|
||||
|
||||
<!-- 批量查询未处理的问答记录(用于 RAG 轮询) -->
|
||||
<select id="selectUnreadForProcessing" resultType="com.ichangzuo.system.model.entity.QnA">
|
||||
SELECT *
|
||||
FROM mc_help_qa
|
||||
WHERE state = 0
|
||||
ORDER BY help_id
|
||||
LIMIT #{batchSize}
|
||||
FOR UPDATE SKIP LOCKED
|
||||
</select>
|
||||
|
||||
<!-- 重复问题检测:state=3/4/5 各取最新一条(窗口函数替代 UNION,避免 MyBatis-Plus 拦截器解析 UNION 报错) -->
|
||||
<select id="getDuplicateCheckRecords" resultType="com.ichangzuo.system.model.entity.QnA">
|
||||
SELECT help_id, question, answer FROM (
|
||||
SELECT help_id, question, answer, state,
|
||||
ROW_NUMBER() OVER (PARTITION BY state ORDER BY help_id DESC) AS rn
|
||||
FROM mc_help_qa
|
||||
WHERE user_id = #{userId} AND help_type_id = #{helpTypeId} AND state IN (3, 4, 5)
|
||||
) t WHERE rn = 1
|
||||
</select>
|
||||
</mapper>
|
||||
|
||||
Reference in New Issue
Block a user