Retrievers play a crucial role in the LangChain framework by providing a flexible interface that returns documents based on unstructured queries. Unlike vector stores, retrievers are not required to store documents; their primary function is to retrieve relevant information. While vector stores can serve as the backbone of a retriever, various types of retrievers exist, each tailored to specific use cases.
Retrievers accept a string query as input and output a list of Document objects. This mechanism allows applications to fetch pertinent information efficiently, enabling advanced interactions with large datasets or knowledge bases.
A vector store retriever efficiently retrieves documents by leveraging vector representations. It serves as a lightweight wrapper around the vector store class, conforming to the retriever interface and utilizing methods like similarity search and Maximum Marginal Relevance (MMR).
To create a retriever from a vector store, use the .as_retriever method. For example, with a Pinecone vector store based on customer reviews, we can set it up as follows:
from langchain_community.document_loaders import CSVLoader
from langchain_community.vectorstores import Pinecone
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
loader = CSVLoader("customer_reviews.csv")
documents = loader.load()
text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=50)
texts = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
vectorstore = Pinecone.from_documents(texts, embeddings)
retriever = vectorstore.as_retriever()
We can now use this retriever to query relevant reviews:
docs = retriever.invoke("What do customers think about the battery life?")
By default, the retriever uses similarity search, but we can specify MMR as the search type:
retriever = vectorstore.as_retriever(search_type="mmr")
Additionally, we can pass parameters like a similarity score threshold or limit the number of results with top-k:
retriever = vectorstore.as_retriever(search_kwargs={"k": 2, "score_threshold": 0.6})
Output:
Using a vector store as a retriever enhances document retrieval by ensuring efficient access to relevant information.
The MultiQueryRetriever enhances distance-based vector database retrieval by addressing common limitations, such as variations in query wording and suboptimal embeddings. Automating prompt tuning with a large language model (LLM) generates multiple queries from different perspectives for a given user input. This process allows for retrieving relevant documents for each query and combining the results to yield a richer set of potential documents.
To demonstrate the MultiQueryRetriever, let’s create a vector store using product descriptions from a CSV file:
from langchain_community.document_loaders import CSVLoader
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
# Load product descriptions
loader = CSVLoader("product_descriptions.csv")
data = loader.load()
# Split the text into chunks
text_splitter = CharacterTextSplitter(chunk_size=300, chunk_overlap=50)
documents = text_splitter.split_documents(data)
# Create the vector store
embeddings = OpenAIEmbeddings()
vectordb = FAISS.from_documents(documents, embeddings)
To utilize the MultiQueryRetriever, specify the LLM for query generation:
from langchain.retrievers.multi_query import MultiQueryRetriever
from langchain_openai import ChatOpenAI
question = "What features do customers value in smartphones?"
llm = ChatOpenAI(temperature=0)
retriever_from_llm = MultiQueryRetriever.from_llm(
retriever=vectordb.as_retriever(), llm=llm
)
unique_docs = retriever_from_llm.invoke(question)
len(unique_docs) # Number of unique documents retrieved
Output:
The MultiQueryRetriever generates multiple queries, enhancing the diversity and relevance of the retrieved documents.
To tailor the generated queries, you can create a custom PromptTemplate and an output parser:
from langchain_core.output_parsers import BaseOutputParser
from langchain_core.prompts import PromptTemplate
from typing import List
# Custom output parser
class LineListOutputParser(BaseOutputParser[List[str]]):
def parse(self, text: str) -> List[str]:
return list(filter(None, text.strip().split("\n")))
output_parser = LineListOutputParser()
# Custom prompt for query generation
QUERY_PROMPT = PromptTemplate(
input_variables=["question"],
template="""Generate five different versions of the question: {question}"""
)
llm_chain = QUERY_PROMPT | llm | output_parser
# Initialize the retriever
retriever = MultiQueryRetriever(
retriever=vectordb.as_retriever(), llm_chain=llm_chain, parser_key="lines"
)
unique_docs = retriever.invoke("What features do customers value in smartphones?")
len(unique_docs) # Number of unique documents retrieved
Output
Using the MultiQueryRetriever allows for more effective retrieval processes, ensuring diverse and comprehensive results based on user queries
Retrieving relevant information from large document collections can be challenging, especially when the specific queries users will pose are unknown at the time of data ingestion. Often, valuable insights are buried in lengthy documents, leading to inefficient and costly calls to language models (LLMs) while providing less-than-ideal responses. Contextual compression addresses this issue by refining the retrieval process, ensuring that only pertinent information is returned based on the user’s query.
The Contextual Compression Retriever operates by integrating a base retriever with a Document Compressor. Instead of returning documents in their entirety, this approach compresses them according to the context provided by the query. This compression involves both reducing the content of individual documents and filtering out irrelevant ones.
1. Initialize the Base Retriever: Begin by setting up a vanilla vector store retriever. For example, consider a news article on climate change policy:
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
# Load and split the article
documents = TextLoader("climate_change_policy.txt").load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
# Initialize the vector store retriever
retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever()
2. Perform an Initial Query: Execute a query to see the results returned by the base retriever, which may include relevant as well as irrelevant information.
docs = retriever.invoke("What actions are being proposed to combat climate change?")
3. Enhance Retrieval with Contextual Compression: Wrap the base retriever with a ContextualCompressionRetriever, utilizing an LLMChainExtractor to extract relevant content:
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import LLMChainExtractor
from langchain_openai import OpenAI
llm = OpenAI(temperature=0)
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(
base_compressor=compressor, base_retriever=retriever
)
# Perform the compressed retrieval
compressed_docs = compression_retriever.invoke("What actions are being proposed to combat climate change?")
Review the Compressed Results: The ContextualCompressionRetriever processes the initial documents and extracts only the relevant information related to the query, optimizing the response.
A retriever is essential in many LLM applications. It is tasked with fetching relevant documents based on user queries. These documents are formatted into prompts for the LLM, enabling it to generate appropriate responses.
To create a custom retriever, extend the BaseRetriever class and implement the following methods:
Method | Description | Required/Optional |
_get_relevant_documents | Retrieve documents relevant to a query. | Required |
_aget_relevant_documents | Asynchronous implementation for native support. | Optional |
Inheriting from BaseRetriever grants your retriever the standard Runnable functionality.
Here’s an example of a simple retriever:
from typing import List
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever
class ToyRetriever(BaseRetriever):
"""A simple retriever that returns top k documents containing the user query."""
documents: List[Document]
k: int
def _get_relevant_documents(self, query: str) -> List[Document]:
matching_documents = [doc for doc in self.documents if query.lower() in doc.page_content.lower()]
return matching_documents[:self.k]
# Example usage
documents = [
Document("Dogs are great companions.", {"type": "dog"}),
Document("Cats are independent pets.", {"type": "cat"}),
]
retriever = ToyRetriever(documents=documents, k=1)
result = retriever.invoke("dog")
print(result[0].page_content)
Output
This implementation provides a straightforward way to retrieve documents based on user input, illustrating the core functionality of a custom retriever in LangChain.
In the LangChain framework, retrievers are powerful tools that enable efficient access to relevant information across various document types and use cases. By understanding and implementing different retriever types—such as vector store retrievers, the MultiQueryRetriever, and the Contextual Compression Retriever—developers can tailor document retrieval to their application’s specific needs.
Each retriever type offers unique advantages, from handling complex queries with MultiQueryRetriever to optimizing responses with Contextual Compression. Additionally, creating custom retrievers allows for even greater flexibility, accommodating specialized requirements that built-in options may not meet. Mastering these retrieval techniques empowers developers to build more effective and responsive applications, harnessing the full potential of language models and large datasets.
If you’re looking to master LangChain and other Generative AI concepts, don’t miss out on our GenAI Pinnacle Program.
Ans. A retriever’s primary role is to fetch relevant documents in response to a query. This helps applications efficiently access necessary information from large datasets without needing to store the documents themselves.
Ans. A vector store is used for storing documents in a way that allows similarity-based retrieval, while a retriever is an interface designed to retrieve documents based on queries. Although vector stores can be part of a retriever, the retriever’s job is focused on fetching relevant information.
Ans. The MultiQueryRetriever improves search results by creating multiple variations of a query using a language model. This method captures a broader range of documents that might be relevant to differently phrased questions, enhancing the diversity of retrieved information.
Ans. Contextual compression refines retrieval results by reducing document content to only the relevant sections and filtering out unrelated information. This is especially useful in large collections where full documents might contain extraneous details, saving resources and providing more focused responses.
Ans. To set up a MultiQueryRetriever, you need a vector store for document storage, a language model (LLM) to generate multiple query perspectives, and, optionally, a custom prompt template to refine query generation further.