High severity intermediate · Fix: 2-5 min

ValueError

langchain.vectorstores.mmr_retriever.ValueError

What this error means
The MMR retriever's fetch_k parameter is set lower than k, causing a ValueError during document retrieval.

Stack trace

traceback
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
QUICK FIX
Ensure fetch_k is set to a value equal or greater than k in the MMRRetriever constructor.

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

1

fetch_k parameter is set lower than k in MMRRetriever initialization

✓ Fix

Set fetch_k to a value greater than or equal to k when creating the MMRRetriever instance.

2

Using default fetch_k which is less than the custom k value passed

✓ Fix

Explicitly specify fetch_k >= k when overriding the default k parameter.

3

Misunderstanding of fetch_k and k roles in MMR retrieval

✓ Fix

Review MMRRetriever docs to understand fetch_k fetches candidates and k selects final results; adjust parameters accordingly.

Code: broken vs fixed

Broken - triggers the error
python
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
Fixed - works correctly
python
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
Updated fetch_k to be greater than or equal to k to satisfy MMRRetriever requirements and avoid ValueError.

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.

Python 3.9+ · langchain-core >=0.1.0 · tested on 0.2.x
Verified 2026-04
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.