Keyword and hybrid retrieval crash when document tokenization yields an empty vocabulary
Description
Keyword search constructs BM25Okapi even when tokenization removes every word from every document chunk. rank_bm25 then divides by zero while computing average IDF.
This can occur with nonempty documents containing only stop words or punctuation. It also breaks the default hybrid retriever, which includes keyword search.
Reproduction
Environment: Windows, Python 3.12.13, Qwen-Agent 0.0.34 at 31a4d36d123688581a9e9744427272b33ce940e0, rank-bm25 0.2.2, with the RAG dependencies installed.
from qwen_agent.tools import KeywordSearch
from qwen_agent.tools.doc_parser import Chunk, Record
from qwen_agent.utils.tokenization_qwen import count_tokens
text = "to be or not to be"
doc = Record(
url="quote.txt",
title="Quote",
raw=[Chunk(
content=text,
metadata={"source": "quote.txt", "chunk_id": 0},
token=count_tokens(text),
)],
)
KeywordSearch().call({"query": "quote"}, docs=[doc], max_ref_token=3)Actual result:
File "rank_bm25.py", line 101, in _calc_idf
self.average_idf = idf_sum / len(self.idf)
ZeroDivisionError: division by zeroThis is also reproducible through Retrieval.call() using two local text files containing the same sentence and max_ref_token=6: each file is parsed as a whole-document chunk, but their combined token count triggers ranking. Both keyword-only and default hybrid retrieval fail.
Expected Behavior
When no chunk contains searchable keywords, skip BM25 scoring and use the existing fallback behavior rather than crashing. Preserve current scores and chunk identifiers when some chunks still have searchable terms.
Proposed Fix and Verification
Tokenize the chunks once and return an empty ranking if none of the token lists contain words. Otherwise construct BM25 from the unchanged token lists, including any empty lists so that chunk alignment is retained.
The local regression suite covers empty documents/chunks, whitespace, punctuation, stop words, mixed empty/nonempty token lists, and real local-file retrieval in keyword-only and hybrid modes. Before the fix: 9 failed, 2 passed. After the fix, these and the existing keyword/hybrid tests all pass: 13 passed.
This report and the accompanying fix/tests were prepared with AI assistance. Tests use real tokenization and BM25, without external model calls.
Source: QwenLM/Qwen-Agent