feat(retriever): add token-aware context truncation to cap documents passed to LLM - #139
Conversation
|
Thank you — the token-aware framing is right, and better than the document count that landed.
Not adopting it yet, for one reason: 9,531 tokens is 7% of the 128k window, so a second limit would tighten a bound that is not currently binding. Recorded with the measurements in #172 so it is picked up when it matters. The more valuable half of your PR is putting the limits in Noting also that Closing as recorded rather than rejected — the analysis is in #172 with your name on it. |
D1 is Helia's call: SelfQueryRetriever is replaced by plain semantic search, BM25 stays. Recorded with its consequences rather than as a simplification, because it is not one -- retrieval results change materially (#171 measured SelfQuery as stable run to run, agreeing with plain vector on 0.48 of documents and 0.19 of positions), metadata filtering is lost as a capability rather than just as code, and 339 lines across the metadata_info files fall out of the retrieval path while remaining in use by the evaluator and the baseline harness. What it buys: LLM calls in retrieval drop from 21 per message to 1, and the component most likely to break on LangChain 1.x goes away. D2, D3 and D4 are mine, each with the reasoning that decided it: D2 budget stays per collection. The decisive argument is technical: each collection is fused independently, so RRF scores from different collections are not comparable quantities and a global top-N would sort by a meaningless comparison. Coverage is the secondary reason. D3 budget counted in documents. Tokens are the better unit in principle and #139 was right, but 40 documents span 5,796-9,531 tokens at roughly 7% of the window -- a ceiling there would tighten a bound that is not binding. Kept as one named parameter so a token bound can be added later. D4 multi-query expansion stays for now, and is measured separately afterwards. Not because it is known to be valuable -- that has never been measured -- but because D1 already changes retrieval materially, and removing both at once would make any quality difference impossible to attribute. FR-003, FR-005, FR-009 and SC-005 updated so the requirements match the decisions rather than drifting from them. The #171 figures predate the #169 and #170 fixes, so they describe a retriever that no longer exists. Recapturing them is recorded as the first verification step before implementing D1. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Summary
Adds token-aware context truncation to
HybridRetrieverto cap the number of documents and tokens passed to the LLM. Fixes the unbounded document passing problem described in #138.Motivation
create_stuff_documents_chaininrag_chain.pystuffs ALL retrieved documents into the LLM context with zero token awareness. With two databases installed (Reactome + UniProt), this results in 60-100 documents per query reaching the LLM, causing:Changes
New -
src/util/context_truncator.pytruncate_to_token_limit()- truncates a ranked document list to fit within a token budget and document count limitlangchain-openai, zero new dependenciesModified -
src/retrievers/csv_chroma.pyretrieve_documents()- returnstruncate_to_token_limit(subdirectory_docs)instead of rawsubdirectory_docsaretrieve_documents()- same change applied to async retrieval pathtruncate_to_token_limitfromutil.context_truncatorModified -
config_default.ymlretriever.context_truncationblock withmax_docs: 15andmax_tokens: 12000HybridRetrievercan be added later - current defaults are hardcodedWhy These Default Values
Expected Impact
Limits context passed to the LLM to a maximum of 15 documents and 12,000 tokens per query, down from an unbounded 60-100 documents. This reduces token usage significantly and avoids the "lost in the middle" quality degradation that occurs with excessively long contexts.
Note: Exact token counts per document depend on installed database versions and chunk sizes. A follow-up evaluation with real embeddings will quantify the precise reduction.
Note: GPT-4o supports a 128k context window but the 12,000 token limit is intentional - it reserves space for system prompt, chat history, and model output, while avoiding the "lost in the middle" quality degradation that occurs with excessively long contexts.
Interaction With Other PRs
Truncation runs at the end of
retrieve_documents()andaretrieve_documents()- after WRR ranking and after FlashRank reranking (PR #116). This means truncation always removes the least relevant documents from last, preserving quality ordering established by both ranking stages.Related