ValueError
langchain.vectorstores.mmr_retriever.ValueError
Stack trace
ValueError: fetch_k must be greater than or equal to k
File "/usr/local/lib/python3.9/site-packages/langchain/vectorstores/mmr_retriever.py", line 85, in get_relevant_documents
raise ValueError("fetch_k must be greater than or equal to k")
File "app.py", line 42, in <module>
docs = retriever.get_relevant_documents(query) # triggers error Why it happens
The MMR retriever requires fetch_k to be at least as large as k because it first fetches fetch_k documents before reranking and selecting the top k. Setting fetch_k less than k violates this logic and triggers a ValueError.
Detection
Check the retriever initialization parameters and assert fetch_k >= k before calling get_relevant_documents to catch this error early.
Causes & fixes
fetch_k parameter is set lower than k in MMRRetriever initialization
Set fetch_k to a value greater than or equal to k when creating the MMRRetriever instance.
Using default fetch_k which is less than the custom k value passed
Explicitly specify fetch_k >= k when overriding the default k parameter.
Misunderstanding of fetch_k and k roles in MMR retrieval
Review MMRRetriever docs to understand fetch_k fetches candidates and k selects final results; adjust parameters accordingly.
Code: broken vs fixed
from langchain.vectorstores import MMRRetriever
retriever = MMRRetriever(vectorstore=vs, k=5, fetch_k=3) # fetch_k < k triggers error
results = retriever.get_relevant_documents("example query") # ValueError here from langchain.vectorstores import MMRRetriever
retriever = MMRRetriever(vectorstore=vs, k=5, fetch_k=10) # fetch_k >= k fixed
results = retriever.get_relevant_documents("example query")
print(results) # Works without error Workaround
Wrap get_relevant_documents call in try/except ValueError, and if caught, programmatically reset fetch_k to k or higher and retry the call.
Prevention
Always validate that fetch_k >= k before initializing MMRRetriever, ideally with assertions or parameter validation in your code to prevent runtime errors.