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. |
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