RAG 进阶:MultiQuery Retriever 是如何工作的?


基于距离的向量数据库检索将用户查询嵌入到高维空间中,并根据 "距离 "找到相似的文档。但是,如果查询措辞发生微妙变化,或者嵌入(embeddings)不能很好地捕捉数据的语义,检索可能会产生不同的结果。为了手动解决这些问题,有时需要利用 Propmpt 工程或微调,但这可能会很繁琐。
MultiQuery Retriever[1] 通过使用 LLM 从不同角度为给定的用户输入查询生成多个不同的查询,从而执行自动调整过程。对于每个查询,它都会检索一组相关文档,并采用所有查询之间的唯一并集来获取更大的一组潜在相关文档。通过对同一问题生成多个视角的查询,MultiQuery Retriever 或许能够克服相似性搜索的一些限制,并获得更丰富的结果集。

本文我将介绍如何利用 Ollama 和 Llama3 来分析 MultiQuery Retriever 内部的工作流程。
创建 MemoryVectorStore
在以下代码中,我们使用 Langchain 内置的 MemoryVectorStore 创建了基于内存的向量数据库。同时,我们利用 Ollama 在本地运行 nomic-embed-text[2] Embeddings 服务,实现对文本的 Embeddings 处理。你可以通过 ollama pull nomic-embed-text 命令来拉取 nomic-embed-text Embeddings 模型。
import { MemoryVectorStore } from "langchain/vectorstores/memory";import { OllamaEmbeddings } from "@langchain/community/embeddings/ollama";const vectorstore = await MemoryVectorStore.fromTexts(    [      "Buildings are made out of brick",      "Buildings are made out of wood",      "Buildings are made out of stone",      "Cars are made out of metal",      "Cars are made out of plastic",      "mitochondria is the powerhouse of the cell",      "mitochondria is made of lipids",    ],    [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],    new OllamaEmbeddings({      model: "nomic-embed-text",      baseUrl: "http://127.0.0.1:11434",    })  );
创建 MultiQueryRetriever
近期 Meta 发布了 Llama 3 8B 和 70B 模型,有了强大的 Ollama,我们可以轻松地在本地运行最新的 Llama 3 模型。

只需在终端中输入 ollama run llama3 命令,Ollama 就会自动帮我们下载和运行 llama3:8b 模型。当成功执行上述命令后,我们可以通过 curl 来验证本地的 llama3 服务是否正常工作。
curl -X POST http://localhost:11434/api/generate -d '{  "model": "llama3",  "prompt":"Why is the sky blue?" }'
接下来,我们直接使用 LangChain 社区提供的 ChatOllama[3] 来调用本地的 Llama 3 服务。
import { ChatOllama } from "@langchain/community/chat_models/ollama";import { MultiQueryRetriever } from "langchain/retrievers/multi_query";  const model = new ChatOllama({  model: "llama3:latest",  baseUrl: "http://127.0.0.1:11434",});const retriever = MultiQueryRetriever.fromLLM({  llm: model,  retriever: vectorstore.asRetriever(),  verbose: true,});
在以上代码中,我们使用 MultiQueryRetriever.fromLLM 方法创建了 retriever 对象,其中 verbose 参数用于在终端输出 MultiQueryRetriever 的执行过程。创建了 MultiQueryRetriever 对象之后,我们就可以调用该对象上的 getRelevantDocuments 方法来获取与用户输入问题相关的文档集:
  const query = "What are mitochondria made of?";  const retrievedDocs = await retriever.getRelevantDocuments(query);
MultiQueryRetriever 执行流程
1.生成相关问题

在上图中,我们可以清楚看到 MultiQueryRetriever 的执行流程:
 1:retriever:MultiQueryRetriever > 2:chain:LLMChain > 3:llm:ChatOllama
在调用 Llama 3 服务时,会所使用 MultiQueryRetriever 默认的提示词模板生成 3 个不同维度的相关问题:
// langchain/src/retrievers/multi_query.tsconst DEFAULT_QUERY_PROMPT = new PromptTemplate({  inputVariables: ["question", "queryCount"],  template: `You are an AI language model assistant. Your task isto generate {queryCount} different versions of the given userquestion 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 limitationsof distance-based similarity search.Provide these alternative questions separated by newlines between XML tags. For example:<questions>Question 1Question 2Question 3</questions>Original question: {question}`,});
当成功调用 LLM 服务之后,就会解析返回结果,具体如下图所示:

下面我们用一张图来描述上述的执行流程:

2.获取与每个问题有关的文档
2.1 What components comprise the structure of mitochondria?

2.2 What are the fundamental building blocks that form the mitochondria?

2.3 What is the molecular composition of mitochondria?

观察以上的图片,你会发现虽然使用的是不同问题,但会返回相同的文档。所以,在返回最终的文档集前,我们需要对文档进行去重处理。
3.返回去重后的文档
总结
MultiQueryRetriever 的核心处理流程,包含生成多个不同维度的查询、获取每个查询的相关文档和文档去重三个步骤。对应的处理流程被封装在 MultiQueryRetriever 类中的 _getRelevantDocuments 方法内部:
  export class MultiQueryRetriever extends BaseRetriever {      async _getRelevantDocuments(        question: string,        runManager?: CallbackManagerForRetrieverRun      ): Promise<Document[]> {        const queries = await this._generateQueries(question, runManager);        const documents = await this._retrieveDocuments(queries, runManager);        const uniqueDocuments = this._uniqueUnion(documents);        return uniqueDocuments;      } }
感兴趣的话,你可以阅读 MultiQueryRetriever[4] 类的相关代码。若有遇到问题,可以在评论区给我留言。如果你对 RAG 的相关技术感兴趣的话,可以关注我,后续会持续分享更多 RAG 和 LangChain 相关的文章。
参考资料
[1] 
MultiQuery Retriever: https://js.langchain.com/docs/modules/data_connection/retrievers/multi-query-retriever[2] 
nomic-embed-text: https://ollama.com/library/nomic-embed-text[3] 
ChatOllama: https://js.langchain.com/docs/integrations/chat/ollama[4] 
MultiQueryRetriever: https://github.com/langchain-ai/langchainjs/blob/76193ec0db1cebd55ea49456b373bae7c83838eb/langchain/src/retrievers/multi_query.ts#L90
到顶部