增加rag服务

This commit is contained in:
2026-09-09 14:19:17 +08:00
parent a3deaea4e8
commit 3dada33b3d
41 changed files with 1970 additions and 24 deletions
@@ -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(已回答),&lt; 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);
}
}
}