检索增强生成(RAG)

By ref-nobody 创建时间 2025年4月30日 | 本文最后更新于 2025年4月30日 #ai, #enbedding model, #rag, #翻译

检索增强生成(Retrieval Augmented Generation,RAG)是一种有助于克服大型语言模型在处理长篇内容、事实准确性以及上下文感知方面所面临限制的技术。

Spring AI 通过提供一种模块化架构来支持 RAG,这种架构允许你自行构建定制的 RAG 流程,或者使用通过Advisor API 提供的现成 RAG 流程。

Advisors

Spring AI 通过Advisor API 提供了现成的支持,用于常见的检索增强生成(RAG)流程。

要使用 QuestionAnswerAdvisorRetrievalAugmentationAdvisor,你需要将 spring-ai-advisors-vector-store 依赖项添加到你的项目中。

<dependency>
   <groupId>org.springframework.ai</groupId>
   <artifactId>spring-ai-advisors-vector-store</artifactId>
</dependency>

QuestionAnswerAdvisor

向量数据库存储着人工智能模型所不知道的数据。当用户的问题被发送给人工智能模型时,QuestionAnswerAdvisor 会查询向量数据库,寻找与用户问题相关的文档。

向量数据库的响应会被附加到用户文本上,为人工智能模型生成回答提供上下文。

假设你已经将数据加载到了一个向量存储库中,你可以通过向 ChatClient 提供一个 QuestionAnswerAdvisor 的实例来执行检索增强生成(RAG)。

ChatResponse response = ChatClient.builder(chatModel)
        .build().prompt()
        .advisors(new QuestionAnswerAdvisor(vectorStore))
        .user(userText)
        .call()
        .chatResponse();

在本示例中,QuestionAnswerAdvisor将对向量数据库中的所有文档执行相似性搜索。为限定被检索的文档类型,SearchRequest(搜索请求)采用了类SQL的过滤表达式,该表达式可跨所有VectorStore(向量存储)兼容使用。

此过滤表达式既可在创建QuestionAnswerAdvisor时配置(此时将应用于所有ChatClient请求),也可在每次请求时动态提供。

以下代码演示如何创建QuestionAnswerAdvisor实例,其中设置相似度阈值为0.8,并返回匹配度最高的6条结果:

var qaAdvisor = new QuestionAnswerAdvisor(this.vectorStore,
        SearchRequest.builder().similarityThreshold(0.8d).topK(6).build());

Leave a Reply

Your email address will not be published. Required fields are marked *

目录