package com.ruoyi.ai.controller;
|
|
import com.ruoyi.ai.assistant.KnowledgeChatAgent;
|
import com.ruoyi.ai.dto.KnowledgeChatRequest;
|
import com.ruoyi.ai.service.KnowledgeRagService;
|
import com.ruoyi.approve.pojo.KnowledgeBase;
|
import com.ruoyi.approve.service.KnowledgeBaseService;
|
import com.ruoyi.common.utils.StringUtils;
|
import com.ruoyi.framework.web.domain.AjaxResult;
|
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
import lombok.RequiredArgsConstructor;
|
import lombok.extern.slf4j.Slf4j;
|
import org.springframework.web.bind.annotation.*;
|
import reactor.core.publisher.Flux;
|
|
import java.util.List;
|
|
/**
|
* 知识库问答Controller
|
*/
|
@Slf4j
|
@RestController
|
@RequestMapping("/ai/knowledge")
|
@RequiredArgsConstructor
|
@Tag(name = "知识库问答")
|
public class KnowledgeChatController {
|
|
private final KnowledgeChatAgent knowledgeChatAgent;
|
private final KnowledgeRagService knowledgeRagService;
|
private final KnowledgeBaseService knowledgeBaseService;
|
|
/**
|
* 知识库问答(流式返回)
|
*/
|
@PostMapping(value = "/chat", produces = "text/stream;charset=utf-8")
|
@Operation(summary = "知识库问答")
|
public Flux<String> chat(@RequestBody KnowledgeChatRequest request) {
|
if (request.getKnowledgeBaseId() == null) {
|
return Flux.just("知识库ID不能为空");
|
}
|
if (!StringUtils.hasText(request.getMemoryId())) {
|
return Flux.just("会话ID不能为空");
|
}
|
if (!StringUtils.hasText(request.getQuestion())) {
|
return Flux.just("问题不能为空");
|
}
|
|
KnowledgeBase knowledgeBase = knowledgeBaseService.getById(request.getKnowledgeBaseId());
|
if (knowledgeBase == null) {
|
return Flux.just("知识库不存在");
|
}
|
|
String namespace = "kb-" + request.getKnowledgeBaseId();
|
|
List<String> relevantContents = knowledgeRagService.searchRelevantContent(
|
namespace, request.getQuestion(), 5);
|
|
if (relevantContents.isEmpty()) {
|
return Flux.just("知识库中未找到相关内容,请先上传相关文档。");
|
}
|
|
StringBuilder contextBuilder = new StringBuilder();
|
contextBuilder.append("以下是从知识库中检索到的相关内容:\n\n");
|
for (int i = 0; i < relevantContents.size(); i++) {
|
contextBuilder.append("【内容").append(i + 1).append("】\n");
|
contextBuilder.append(relevantContents.get(i)).append("\n\n");
|
}
|
contextBuilder.append("---\n");
|
contextBuilder.append("请基于以上知识库内容回答用户问题:\n");
|
contextBuilder.append(request.getQuestion());
|
|
return knowledgeChatAgent.chat(request.getMemoryId(), contextBuilder.toString());
|
}
|
|
/**
|
* 知识库列表(用于选择知识库)
|
*/
|
@GetMapping("/list")
|
@Operation(summary = "知识库列表")
|
public AjaxResult listKnowledgeBases() {
|
List<KnowledgeBase> list = knowledgeBaseService.list();
|
return AjaxResult.success(list);
|
}
|
}
|