高级RAG技术:查询扩展、自查询、过滤向量搜索与重排序的实现
引言:RAG推理流水线架构概览
在构建生产级RAG系统时,检索步骤是决定生成质量的核心。本章将深入讲解四个高级RAG技术:查询扩展(Query Expansion)、自查询(Self-Querying)、过滤向量搜索(Filtered Vector Search)和重排序(Reranking)。这些技术分别作用于预检索、检索和后检索阶段,显著提升召回率和准确率。
整个RAG推理流水线流程如下:用户输入查询 → 查询扩展(生成多个变体) → 自查询(提取作者ID等元数据) → 过滤向量搜索(对每个变体执行相似度搜索,并应用元数据过滤) → 收集所有结果(N×K个) → 重排序(交叉编码器打分,取Top-K) → 构建提示并调用LLM生成答案。
预检索优化:查询扩展
问题
传统RAG使用单个向量表示查询,只能覆盖嵌入空间的局部区域。当查询的语义不够丰富时,容易遗漏相关文档。
解决方案
利用LLM生成原始查询的多个变体,每个变体从不同角度刻画同一信息需求。嵌入这些变体后,搜索范围扩大,召回率提升。
代码实现
首先定义QueryExpansionTemplate,用于构建生成多查询的提示模板:
fromlangchain.promptsimportPromptTemplatefrom.baseimportPromptTemplateFactoryclassQueryExpansionTemplate(PromptTemplateFactory):prompt:str="""You are an AI language model assistant. Your task is to generate {expand_to_n} different versions of the given user question to retrieve relevant documents from a vector database. By generating multiple perspectives on the user question, your goal is to help the user overcome some of the limitations of the distance-based similarity search. Provide these alternative questions separated by '{separator}'. Original question: {question}"""@propertydefseparator(self)->str:return"#next-question#"defcreate_template(self,expand_to_n:int)->PromptTemplate:returnPromptTemplate(template=self.prompt,input_variables=["question"],partial_variables={"separator":self.separator,"expand_to_n":expand_to_n,},)接着实现QueryExpansion类,继承RAGStep基类:
fromlangchain_openaiimportChatOpenAIfromllm_engineering.domain.queriesimportQueryfromllm_engineering.settingsimportsettingsfrom.baseimportRAGStepfrom.prompt_templatesimportQueryExpansionTemplateclassQueryExpansion(RAGStep):