!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

![🦜️🔗 Langchain](/v0.1/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.1/img/brand/wordmark-dark.png)

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

*   [People](/v0.1/docs/people/)
*   [Community](/v0.1/docs/community/)
*   [Tutorials](/v0.1/docs/additional_resources/tutorials/)
*   [Contributing](/v0.1/docs/contributing/)

[v0.1](#)

*   [v0.2](https://js.langchain.com/v0.2/docs/introduction)
*   [v0.1](/v0.1/docs/get_started/introduction/)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Get started](/v0.1/docs/get_started/)
    
    *   [Introduction](/v0.1/docs/get_started/introduction/)
    *   [Installation](/v0.1/docs/get_started/installation/)
    *   [Quickstart](/v0.1/docs/get_started/quickstart/)
*   [LangChain Expression Language](/v0.1/docs/expression_language/)
    
    *   [Get started](/v0.1/docs/expression_language/get_started/)
    *   [Why use LCEL?](/v0.1/docs/expression_language/why/)
    *   [Interface](/v0.1/docs/expression_language/interface/)
    *   [Streaming](/v0.1/docs/expression_language/streaming/)
    *   [How to](/v0.1/docs/expression_language/how_to/routing/)
        
    *   [Cookbook](/v0.1/docs/expression_language/cookbook/)
        
    *   [LangChain Expression Language (LCEL)](/v0.1/docs/expression_language/)
*   [Modules](/v0.1/docs/modules/)
    
    *   [Model I/O](/v0.1/docs/modules/model_io/)
        
    *   [Retrieval](/v0.1/docs/modules/data_connection/)
        
        *   [Document loaders](/v0.1/docs/modules/data_connection/document_loaders/)
            
        *   [Text Splitters](/v0.1/docs/modules/data_connection/document_transformers/)
            
        *   [Retrievers](/v0.1/docs/modules/data_connection/retrievers/)
            
            *   [Custom retrievers](/v0.1/docs/modules/data_connection/retrievers/custom/)
            *   [Contextual compression](/v0.1/docs/modules/data_connection/retrievers/contextual_compression/)
            *   [Matryoshka Retriever](/v0.1/docs/modules/data_connection/retrievers/matryoshka_retriever/)
            *   [MultiQuery Retriever](/v0.1/docs/modules/data_connection/retrievers/multi-query-retriever/)
            *   [MultiVector Retriever](/v0.1/docs/modules/data_connection/retrievers/multi-vector-retriever/)
            *   [Parent Document Retriever](/v0.1/docs/modules/data_connection/retrievers/parent-document-retriever/)
            *   [Self-querying](/v0.1/docs/modules/data_connection/retrievers/self_query/)
                
            *   [Similarity Score Threshold](/v0.1/docs/modules/data_connection/retrievers/similarity-score-threshold-retriever/)
            *   [Time-weighted vector store retriever](/v0.1/docs/modules/data_connection/retrievers/time_weighted_vectorstore/)
            *   [Vector store-backed retriever](/v0.1/docs/modules/data_connection/retrievers/vectorstore/)
        *   [Retrieval](/v0.1/docs/modules/data_connection/)
        *   [Text embedding models](/v0.1/docs/modules/data_connection/text_embedding/)
            
        *   [Vector stores](/v0.1/docs/modules/data_connection/vectorstores/)
            
        *   [Indexing](/v0.1/docs/modules/data_connection/indexing/)
        *   [Experimental](/v0.1/docs/modules/data_connection/experimental/multimodal_embeddings/google_vertex_ai/)
            
    *   [Chains](/v0.1/docs/modules/chains/)
    *   [Agents](/v0.1/docs/modules/agents/)
        
    *   [More](/v0.1/docs/modules/memory/)
        
*   [Security](/v0.1/docs/security/)
*   [Guides](/v0.1/docs/guides/)
    
*   [Ecosystem](/v0.1/docs/ecosystem/)
    
*   [LangGraph](/v0.1/docs/langgraph/)
*   * * *
    

*   [](/v0.1/)
*   [Modules](/v0.1/docs/modules/)
*   [Retrieval](/v0.1/docs/modules/data_connection/)
*   [Retrievers](/v0.1/docs/modules/data_connection/retrievers/)
*   MultiQuery Retriever

MultiQuery Retriever
====================

Distance-based vector database retrieval embeds (represents) queries in high-dimensional space and finds similar embedded documents based on "distance". But retrieval may produce different results with subtle changes in query wording or if the embeddings do not capture the semantics of the data well. Prompt engineering / tuning is sometimes done to manually address these problems, but can be tedious.

The MultiQueryRetriever automates the process of prompt tuning by using an LLM to generate multiple queries from different perspectives for a given user input query. For each query, it retrieves a set of relevant documents and takes the unique union across all queries to get a larger set of potentially relevant documents. By generating multiple perspectives on the same question, the MultiQueryRetriever might be able to overcome some of the limitations of the distance-based retrieval and get a richer set of results.

Usage[​](#usage "Direct link to Usage")
---------------------------------------

tip

See [this section for general instructions on installing integration packages](/v0.1/docs/get_started/installation/#installing-integration-packages).

*   npm
*   Yarn
*   pnpm

    npm install @langchain/anthropic @langchain/community

    yarn add @langchain/anthropic @langchain/community

    pnpm add @langchain/anthropic @langchain/community

    import { MemoryVectorStore } from "langchain/vectorstores/memory";import { CohereEmbeddings } from "@langchain/cohere";import { MultiQueryRetriever } from "langchain/retrievers/multi_query";import { ChatAnthropic } from "@langchain/anthropic";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 CohereEmbeddings());const model = new ChatAnthropic({});const retriever = MultiQueryRetriever.fromLLM({  llm: model,  retriever: vectorstore.asRetriever(),  verbose: true,});const query = "What are mitochondria made of?";const retrievedDocs = await retriever.invoke(query);/*  Generated queries: What are the components of mitochondria?,What substances comprise the mitochondria organelle?  ,What is the molecular composition of mitochondria?*/console.log(retrievedDocs);/*  [    Document {      pageContent: 'mitochondria is the powerhouse of the cell',      metadata: {}    },    Document {      pageContent: 'mitochondria is made of lipids',      metadata: {}    },    Document {      pageContent: 'Buildings are made out of brick',      metadata: { id: 1 }    },    Document {      pageContent: 'Buildings are made out of wood',      metadata: { id: 2 }    }  ]*/

#### API Reference:

*   [MemoryVectorStore](https://api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory`
*   [CohereEmbeddings](https://api.js.langchain.com/classes/langchain_cohere.CohereEmbeddings.html) from `@langchain/cohere`
*   [MultiQueryRetriever](https://api.js.langchain.com/classes/langchain_retrievers_multi_query.MultiQueryRetriever.html) from `langchain/retrievers/multi_query`
*   [ChatAnthropic](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic`

Customization[​](#customization "Direct link to Customization")
---------------------------------------------------------------

You can also supply a custom prompt to tune what types of questions are generated. You can also pass a custom output parser to parse and split the results of the LLM call into a list of queries.

    import { MemoryVectorStore } from "langchain/vectorstores/memory";import { CohereEmbeddings } from "@langchain/community/embeddings/cohere";import { MultiQueryRetriever } from "langchain/retrievers/multi_query";import { LLMChain } from "langchain/chains";import { pull } from "langchain/hub";import { BaseOutputParser } from "@langchain/core/output_parsers";import { PromptTemplate } from "@langchain/core/prompts";import { ChatAnthropic } from "@langchain/anthropic";type LineList = {  lines: string[];};class LineListOutputParser extends BaseOutputParser<LineList> {  static lc_name() {    return "LineListOutputParser";  }  lc_namespace = ["langchain", "retrievers", "multiquery"];  async parse(text: string): Promise<LineList> {    const startKeyIndex = text.indexOf("<questions>");    const endKeyIndex = text.indexOf("</questions>");    const questionsStartIndex =      startKeyIndex === -1 ? 0 : startKeyIndex + "<questions>".length;    const questionsEndIndex = endKeyIndex === -1 ? text.length : endKeyIndex;    const lines = text      .slice(questionsStartIndex, questionsEndIndex)      .trim()      .split("\n")      .filter((line) => line.trim() !== "");    return { lines };  }  getFormatInstructions(): string {    throw new Error("Not implemented.");  }}// Default prompt is available at: https://smith.langchain.com/hub/jacob/multi-vector-retrieverconst prompt: PromptTemplate = await pull(  "jacob/multi-vector-retriever-german");const vectorstore = await MemoryVectorStore.fromTexts(  [    "Gebäude werden aus Ziegelsteinen hergestellt",    "Gebäude werden aus Holz hergestellt",    "Gebäude werden aus Stein hergestellt",    "Autos werden aus Metall hergestellt",    "Autos werden aus Kunststoff hergestellt",    "Mitochondrien sind die Energiekraftwerke der Zelle",    "Mitochondrien bestehen aus Lipiden",  ],  [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],  new CohereEmbeddings());const model = new ChatAnthropic({});const llmChain = new LLMChain({  llm: model,  prompt,  outputParser: new LineListOutputParser(),});const retriever = new MultiQueryRetriever({  retriever: vectorstore.asRetriever(),  llmChain,  verbose: true,});const query = "What are mitochondria made of?";const retrievedDocs = await retriever.invoke(query);/*  Generated queries: Was besteht ein Mitochondrium?,Aus welchen Komponenten setzt sich ein Mitochondrium zusammen?  ,Welche Moleküle finden sich in einem Mitochondrium?*/console.log(retrievedDocs);/*  [    Document {      pageContent: 'Mitochondrien bestehen aus Lipiden',      metadata: {}    },    Document {      pageContent: 'Mitochondrien sind die Energiekraftwerke der Zelle',      metadata: {}    },    Document {      pageContent: 'Autos werden aus Metall hergestellt',      metadata: { id: 4 }    },    Document {      pageContent: 'Gebäude werden aus Holz hergestellt',      metadata: { id: 2 }    },    Document {      pageContent: 'Gebäude werden aus Ziegelsteinen hergestellt',      metadata: { id: 1 }    }  ]*/

#### API Reference:

*   [MemoryVectorStore](https://api.js.langchain.com/classes/langchain_vectorstores_memory.MemoryVectorStore.html) from `langchain/vectorstores/memory`
*   [CohereEmbeddings](https://api.js.langchain.com/classes/langchain_community_embeddings_cohere.CohereEmbeddings.html) from `@langchain/community/embeddings/cohere`
*   [MultiQueryRetriever](https://api.js.langchain.com/classes/langchain_retrievers_multi_query.MultiQueryRetriever.html) from `langchain/retrievers/multi_query`
*   [LLMChain](https://api.js.langchain.com/classes/langchain_chains.LLMChain.html) from `langchain/chains`
*   [pull](https://api.js.langchain.com/functions/langchain_hub.pull.html) from `langchain/hub`
*   [BaseOutputParser](https://api.js.langchain.com/classes/langchain_core_output_parsers.BaseOutputParser.html) from `@langchain/core/output_parsers`
*   [PromptTemplate](https://api.js.langchain.com/classes/langchain_core_prompts.PromptTemplate.html) from `@langchain/core/prompts`
*   [ChatAnthropic](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html) from `@langchain/anthropic`

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

Matryoshka Retriever

](/v0.1/docs/modules/data_connection/retrievers/matryoshka_retriever/)[

Next

MultiVector Retriever

](/v0.1/docs/modules/data_connection/retrievers/multi-vector-retriever/)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.