ValueError
builtins.ValueError
Stack trace
ValueError: No results found for the given query with top_k=5
File "llama_index/retrievers/base.py", line 123, in retrieve
raise ValueError("No results found for the given query with top_k={}".format(top_k)) Why it happens
The retriever queries the underlying index with a top_k parameter specifying how many results to return. If the index contains no documents matching the query or the similarity threshold is too strict, the retriever returns an empty list and raises this error. This often happens when the index is empty, the query is too specific, or the top_k value is set but no results meet the criteria.
Detection
Check the retriever's output list length before accessing results or wrap calls in try/except to catch ValueError and log the query and index state to detect empty results early.
Causes & fixes
The index is empty or has no documents matching the query.
Ensure the index is properly built and populated with relevant documents before querying.
The top_k parameter is set higher than the number of available matching documents.
Set top_k to a value less than or equal to the number of documents in the index or handle empty results gracefully.
The similarity or filtering threshold is too strict, filtering out all potential results.
Adjust similarity thresholds or filtering parameters to be less restrictive to allow more results.
Code: broken vs fixed
from llama_index import GPTSimpleVectorIndex
index = GPTSimpleVectorIndex([]) # empty index
results = index.as_retriever(top_k=5).retrieve("What is AI?") # raises ValueError here
print(results) import os
from llama_index import GPTSimpleVectorIndex
# Ensure index is populated
documents = ["AI is artificial intelligence."]
index = GPTSimpleVectorIndex(documents)
retriever = index.as_retriever(top_k=5)
try:
results = retriever.retrieve("What is AI?")
print(results)
except ValueError as e:
print(f"No results found: {e}") # Handle empty results gracefully Workaround
Wrap the retriever call in try/except ValueError, catch the exception, and fallback to a default response or retry with a lower top_k value.
Prevention
Always verify the index is populated with relevant documents before querying and implement graceful handling for empty retrieval results to avoid runtime errors.