Ollama RAG 知识库接口页面对接

本节需求

基于我们要实现对话和知识的上传使用,使用AI工具完成UI页面的实现

效果展示

注意到左下角我们有切换知识库的功能,默认知识库就是普通的流式请求,不会使用rag功能。目前小傅哥的项目中并没有携带rag参数的流式请求接口,因此我们可以自己实现一个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@RequestMapping(value = "generate_stream_rag", method = RequestMethod.GET)
@Override
public Flux<ChatResponse> generateStreamRag(@RequestParam String model, @RequestParam String message, @RequestParam String ragTag) {

// 参数验证
if (ragTag == null || ragTag.trim().isEmpty()) {
return chatClient.stream(new Prompt(message, OllamaOptions.create().withModel(model)));
}

String SYSTEM_PROMPT = """
Use the information from the DOCUMENTS section to provide accurate answers but act as if you knew this information innately.
If unsure, simply state that you don't know.
Another thing you need to note is that your reply must be in Chinese!
DOCUMENTS:
{documents}
""";

SearchRequest request = SearchRequest.query(message).withTopK(5).withFilterExpression("knowledge == '" + ragTag.replace("'", "''") + "'");

List<Document> documents = pgVectorStore.similaritySearch(request);
// 添加空值检查
String documentsCollectors = documents.stream()
.map(Document::getContent)
.filter(content -> content != null && !content.trim().isEmpty())
.collect(Collectors.joining());

// 如果没有找到相关文档,可以调整提示词
if (documentsCollectors.isEmpty()) {
SYSTEM_PROMPT = """
Please answer the user's question based on your general knowledge.
If you don't know the answer, simply state that you don't know.
Your reply must be in Chinese!
""";
}

Message ragMessage = new SystemPromptTemplate(SYSTEM_PROMPT).createMessage(Map.of("documents", documentsCollectors));

ArrayList<Message> messages = new ArrayList<>();
messages.add(ragMessage);
messages.add(new UserMessage(message));

return chatClient.stream(new Prompt(messages, OllamaOptions.create().withModel(model)));
}

这样就可以灵活切换不同的知识库了!

下面是一个案例:
使用默认知识库

他对于大连理工大学软件学院的地址没有一个准确的认知,也有一定的信息错乱。

上传文件

文件内容包括:大连理工大学软件学院位于图强路321号

使用大连理工大学知识库

准确回答了大连理工大学软件学院的地址!我们的测试顺利通过!

完整前端代码

点击这里下载完整 HTML 文件

我们将完整的 HTML 文件提供为下载链接,您可以点击上方链接获取。