一、文档检索 (Document Retriever)简介
1、核心概念
文档检索(DocumentRetriever)是一种信息检索技术,旨在从大量未结构化或半结构化文档中快速找到与特定查询相关的文档或信息。文档检索通常以在线(online)方式运行。
DocumentRetriever通常基于向量搜索。 它将用户的查询问题(query)转化为Embeddings后,在存储文档中进行相似性搜索,返回相关的片段。片段的用途之一是作为提示词(prompt)的一部分,发送给大模型(LLM)汇总处理后,作为答案呈现给用户。
public interface DocumentRetriever extends Function<Query, List<Document>> {/*** Retrieves relevant documents from an underlying data source based on the given* query.* @param query The query to use for retrieving documents* @return The list of relevant documents*/List<Document> retrieve(Query query);default List<Document> apply(Query query) {return retrieve(query);}}
DocumentRetriever API提供了简单、灵活的方式,供开发者使用自定义的检索系统。
- DocumentRetriever API简单地将用户的查询作为输入,返回文档片段(Document)的列表。
- Document表示一个文档片段,它包含一个文本内容,以及一个或多个元数据。
- 用户可以通过retrieve方法执行自定义的检索步骤。
- DashScopeDocumentRetrieverOptions提供了DashScopeDocumentRetriever的配置信息,它通过构建器创建选项。
- 在构造DashScopeDocumentRetriever时,通过将一个DashScopeDocumentRetrieverOptions实例传入,已完成配置。
DashScopeDocumentCloudReader类:百炼云端文档解析,主要是走当前数据中心逻辑。
作用:将用户添加的文档上传到百炼平台云端。
通过查看 DashScopeDocumentCloudReader的get方法可以看到上传逻辑。
二、文档检索 (Document Retriever)使用
Spring AI Alibaba 文档检索 (Document Retriever):https://java2ai.com/docs/1.0.0-M6.1/tutorials/retriever
Spring AI Alibaba 支持以上 Model 抽象与通义系列模型的适配,并通过 spring-ai-alibaba-starter AutoConfiguration 自动初始化了默认实例,因此我们可以在应用程序中直接注入 ChatModel、ImageModel 等 bean,当然在需要的时候也可以自定义 Model 实例。
在普通 Controller Bean 中注入 DocumentRetriever 实例,实现下面几个功能:
- 简单调用
- 流式调用
- 上传用户文档-向量存储
编写 Controller接口
@Slf4j
@RestController
@RequestMapping("/dashscope/document-retriever")
public class DashScopeDocumentRetrieverController {private final ChatClient chatClient;private final DashScopeApi dashscopeApi;@Value("${spring.ai.dashscope.api-key}")private String apiKey;//private String apiKey = "sk-xxx";private static final String indexName = "高并发-知识库";private static final String retrievalSystemTemplate = """Context information is below.---------------------{question_answer_context}---------------------Given the context and provided history information and not prior knowledge,reply to the user comment. If the answer is not in the context, informthe user that you can't answer the question.""";public DashScopeDocumentRetrieverController(ChatClient.Builder builder) {// 暂时无法从Spring IOC容器中获取,所以这里手动创建 DashScopeApi 对象。this.dashscopeApi = new DashScopeApi(apiKey);DocumentRetriever retriever = new DashScopeDocumentRetriever(this.dashscopeApi,DashScopeDocumentRetrieverOptions.builder().withIndexName(indexName).build());this.chatClient = builder//.defaultAdvisors(new DocumentRetrievalAdvisor(retriever)).defaultAdvisors(new DocumentRetrievalAdvisor(retriever, retrievalSystemTemplate)).build();}/*** 导入用户文档*/@GetMapping("/importDocuments")private String importDocuments() {File file = new File("D:\\TempFiles\\高并发秒杀系统的设计与实现.pdf");// 获取文件或目录的绝对路径。String filePath = file.getAbsolutePath();// 1. import and split documentsDocumentReader reader = new DashScopeDocumentCloudReader(filePath, dashscopeApi, null);List<Document> documentList = reader.get();log.info("{} documents loaded and split", documentList.size());// 2. add documents to DashScope cloud storageVectorStore vectorStore = new DashScopeCloudStore(dashscopeApi, new DashScopeStoreOptions(indexName));vectorStore.add(documentList);log.info("{} documents added to dashscope cloud vector store", documentList.size());return "success";}/*** 简单调用方式*/@GetMapping("/simple/chat")public String simpleChat(@RequestParam(defaultValue = "你好,请问你的知识库文档主要是关于什么内容的?") String userInputPrompt) {String aiOutput = chatClient.prompt(userInputPrompt).call().content();log.info("simpleChat --> userInputPrompt = {}, aiOutput = {}", userInputPrompt, aiOutput);return aiOutput;}/*** Stream 流式调用。* 可以使大模型的输出信息实现打字机效果。*/@GetMapping("/stream/chat")public Flux<String> streamChat(HttpServletResponse response,@RequestParam(defaultValue = "你好,请问你的知识库文档主要是关于什么内容的?") String userInputPrompt) {// 避免接口返回乱码response.setCharacterEncoding("UTF-8");log.info("streamChat --> userInputPrompt = {},", userInputPrompt);Flux<String> aiOutput = chatClient.prompt(userInputPrompt).stream().content();return aiOutput;}}
启动项目,用户上传文件之后,我们在阿里云百炼平台就可以查看到文档信息。
访问接口与 AI 大模型智能对话。
– 求知若饥,虚心若愚。