Retrievers
Relevant source files
The following files were used as context for generating this wiki page:
- libs/core/langchain_core/retrievers.py
- libs/langchain/langchain/retrievers/multi_query.py
- libs/langchain/langchain/retrievers/parent_document_retriever.py
- libs/langchain/langchain/retrievers/contextual_compression.py
- libs/langchain/langchain/retrievers/self_query/base.py
- libs/langchain/langchain/retrievers/init.py
- libs/core/langchain_core/tools/retriever.py
Retrievers are a core component of LangChain, designed to fetch relevant documents in response to a string query. They are fundamental to building applications that leverage external data, such as in Retrieval Augmented Generation (RAG) systems. A retriever is a more general concept than a vector store; while a vector store can act as the backbone for a retriever, a retriever's only requirement is to return documents, not necessarily to store them.
The primary interface for retrievers is the BaseRetriever class, which is a Runnable. This integration with the LangChain Expression Language (LCEL) allows retrievers to be seamlessly chained with other components like LLMs and parsers. The standard input to a retriever is a string (RetrieverInput), and the output is a list of Document objects (RetrieverOutput).
Sources: libs/core/langchain_core/retrievers.py:1-25, libs/langchain/README.md
Core Abstraction: BaseRetriever
The BaseRetriever class is the abstract base class that all retriever implementations inherit from. It defines the common interface and functionality for all document retrieval systems within the framework.
Sources: libs/core/langchain_core/retrievers.py:59-62
Key Properties and Methods
| Property/Method | Type | Description - |
|---|---|---|
tags | Optional[list[str]] | Optional tags to associate with each retriever call, useful for tracing and callbacks. - |
metadata | Optional[dict[str, Any]] | Optional metadata to associate with each retriever call. - |
invoke(input, config) | list[Document] | The main entry point for synchronous retriever invocations. - |
ainvoke(input, config) | list[Document] | The main entry point for asynchronous retriever invocations. - |
_get_relevant_documents(...) | list[Document] | Abstract method. Implementations must override this to define the synchronous document retrieval logic. It receives the query and a run_manager. - |
_aget_relevant_documents(...) | list[Document] | Abstract method. Implementations can override this to provide a native asynchronous retrieval logic. If not overridden, it calls _get_relevant_documents in an executor. - |
Sources: libs/core/langchain_core/retrievers.py:113-125, 240-256, 282-298, 328-335, 340-348
This class diagram shows the inheritance from RunnableSerializable, which provides the standard invocation methods.
Invocation Flow
When a retriever's invoke method is called, it sets up a CallbackManager to handle logging, tracing, and other callbacks for the duration of the run. It creates a RunManager which is then passed to the internal _get_relevant_documents method. This ensures that the retrieval operation is properly instrumented.
The following diagram illustrates the synchronous invocation sequence:
The asynchronous ainvoke method follows a similar pattern using an AsyncCallbackManager.
Sources: libs/core/langchain_core/retrievers.py:282-323
Advanced Retriever Types
LangChain provides several specialized retriever implementations that enhance the basic retrieval process.
MultiQueryRetriever
This retriever improves retrieval performance by generating multiple queries from different perspectives based on a single user input. It uses an LLM to create variants of the original query, retrieves documents for each, and then combines and deduplicates the results. This is particularly useful for tackling complex questions where different sub-queries might be needed to find a complete answer.
The process flow is as follows:
ParentDocumentRetriever
The ParentDocumentRetriever is designed to address the challenge of balancing context and precision. It works by indexing smaller, more precise "child" documents in a vector store, but retrieving the larger "parent" documents they originated from. This allows for efficient, focused similarity searches on small chunks while returning the full context from the original document to the LLM.
It requires a vectorstore for the child documents and a docstore for the parent documents.
This diagram shows the indexing and retrieval flow:
ContextualCompressionRetriever
This retriever acts as a wrapper around a base retriever, adding a compression step to the process. After the base retriever fetches documents, a BaseDocumentCompressor is used to filter out and/or transform the documents to keep only the most relevant information. This reduces the amount of data passed to the LLM, potentially improving performance and reducing costs.
The flow is straightforward:
SelfQueryRetriever
The SelfQueryRetriever uses an LLM to convert a natural language query into a structured query. This structured query includes a semantic query string and a metadata filter, which is then used to perform a more precise search on a vector store. It requires metadata_field_info which describes the metadata fields available for filtering on the documents in the vector store.
This approach allows users to ask questions that involve filtering on specific attributes (e.g., "Find documents about LangChain from 2023").
The retrieval process is as follows:
Using a Retriever as a Tool
Retrievers can be easily converted into Tool objects for use within LangChain Agents. The create_retriever_tool function facilitates this conversion.
The function takes a BaseRetriever instance, a name, and a description for the tool. The resulting tool will accept a string query and return a formatted string containing the page content of the retrieved documents, separated by a configurable separator.
The input to the tool is defined by the RetrieverInput Pydantic model, which simply contains a query field.
# Example of creating a retriever tool
from langchain_core.tools.retriever import create_retriever_tool
# Assume 'my_retriever' is an initialized BaseRetriever instance
retriever_tool = create_retriever_tool(
retriever=my_retriever,
name="search_docs",
description="Searches and returns relevant documents.",
)
Sources: libs/core/langchain_core/tools/retriever.py:56-82
Available Retrievers
LangChain offers a wide variety of retriever implementations, both in the core langchain package and in langchain-community. The following table lists some of the available retrievers.
| Retriever Class | Package | Description |
|---|---|---|
MultiQueryRetriever | langchain | Generates multiple queries from different perspectives to enhance retrieval. |
ParentDocumentRetriever | langchain | Retrieves parent documents based on searches over smaller child documents. |
SelfQueryRetriever | langchain | Uses an LLM to generate structured queries from natural language. |
ContextualCompressionRetriever | langchain | Compresses retrieved documents based on query context. |
TimeWeightedVectorStoreRetriever | langchain | A retriever that considers the recency of documents. |
EnsembleRetriever | langchain | Combines the results of multiple retrievers. |
BM25Retriever | community | Uses the BM25 ranking algorithm for retrieval. |
TFIDFRetriever | community | Uses TF-IDF (Term Frequency-Inverse Document Frequency) for retrieval. |
AzureAISearchRetriever | community | Retriever for Azure AI Search. |
PineconeHybridSearchRetriever | community | Retriever for Pinecone supporting hybrid search. |
WeaviateHybridSearchRetriever | community | Retriever for Weaviate supporting hybrid search. |
WikipediaRetriever | community | Fetches documents from Wikipedia. |
ArxivRetriever | community | Fetches documents from Arxiv. |
PubMedRetriever | community | Fetches documents from PubMed. |
Sources: libs/langchain/langchain/retrievers/init.py:1-177, cookbook/README.md