ValueError
builtins.ValueError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
docs = retriever.get_relevant_documents(query, k=5) # This line triggers the error
File "/usr/local/lib/python3.9/site-packages/langchain/retrievers/base.py", line 78, in get_relevant_documents
raise ValueError(f"Retriever returned empty result for k={k} documents")
ValueError: Retriever returned empty result for k=5 documents Why it happens
The retriever component in LangChain queries the underlying vector store or search index for k documents but returns an empty list. This can happen if the vector store is empty, the query embedding is missing or malformed, or the retriever is misconfigured to fetch more documents than exist.
Detection
Check the length of the documents list returned by the retriever before passing it downstream. Log the query and retriever output to detect empty results early.
Causes & fixes
The vector store is empty or uninitialized, so no documents exist to retrieve.
Ensure the vector store is properly populated with embeddings before querying the retriever.
The query embedding is None or invalid, causing the retriever to fail silently and return no results.
Verify the query embedding is correctly generated and passed to the retriever.
The retriever's parameter k is larger than the number of documents in the vector store.
Set k to a value less than or equal to the number of documents in the vector store or handle empty results gracefully.
Misconfiguration of the retriever or vector store connection causing failed queries.
Check retriever initialization parameters and vector store connection settings for correctness.
Code: broken vs fixed
from langchain.vectorstores import FAISS
from langchain.schema import Document
retriever = FAISS.load_local("./faiss_index", embeddings=None)
query = "What is AI?"
docs = retriever.get_relevant_documents(query, k=5) # Raises ValueError: Retriever returned empty result for k=5 documents
print(docs) import os
from langchain.vectorstores import FAISS
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(openai_api_key=os.environ["OPENAI_API_KEY"])
retriever = FAISS.load_local("./faiss_index", embeddings=embeddings) # Added embeddings param
query = "What is AI?"
docs = retriever.get_relevant_documents(query, k=3) # Reduced k to 3 to avoid empty result
if not docs:
print("No documents found for the query.")
else:
print(docs) # Now works without error Workaround
Wrap the retriever call in try/except ValueError, catch empty results, and fallback to a default document or a simpler search method.
Prevention
Always populate and verify your vector store before querying. Use monitoring to alert on empty retriever results and implement fallback logic in your RAG pipeline.