Sub topic 10
Budget retrieved context
This chapter assumes you have built a retrieval-augmented generation (RAG) pipeline. It also assumes you know how tokens drive cost, and you have a baseline measurement and a small evaluation set from earlier chapters.
Why retrieval needs a budget
In a RAG pipeline, retrieved chunks are often the largest part of the prompt. Retrieving 10 chunks of 500 tokens adds 5,000 input tokens to every request. You pay for those tokens on every call. They also lengthen prefill, so time to first token rises.
More context does not always improve answers. Irrelevant chunks add noise, and models can overlook facts buried in the middle of a long prompt. A fixed token budget for context forces a deliberate choice about what earns its place.
Set a budget in tokens, not chunks
"Top 5 chunks" is a weak limit because chunk sizes vary. Set a limit in tokens instead, and fill it with the most relevant chunks.
- Pick a context budget, such as 2,000 tokens.
- Rank candidate chunks by retrieval score.
- Add chunks in rank order while they fit.
- Skip a chunk that would overflow the budget, and try smaller ones.
A budget-aware packer
This function counts tokens with tiktoken and keeps the best-scoring chunks that fit.
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
def pack_context(chunks, budget_tokens):
"""chunks: list of (score, text). Returns (selected texts, tokens used)."""
selected, used = [], 0
for score, text in sorted(chunks, key=lambda c: c[0], reverse=True):
n = len(enc.encode(text))
if used + n > budget_tokens:
continue
selected.append(text)
used += n
return selected, used
chunks = [
(0.91, "Refunds are issued within 14 days of a return request."),
(0.84, "Shipping to the EU takes 3 to 5 business days. " * 20),
(0.77, "Gift cards cannot be refunded."),
]
texts, used = pack_context(chunks, budget_tokens=60)
print(len(texts), "chunks,", used, "tokens")With a 60-token budget, the long shipping chunk is skipped and the two short chunks fit. A greedy packer like this is simple and predictable. Remember that the prompt also holds the system message, the question, and room for the answer, so set the context budget below the total input you can afford.
Ways to shrink what you retrieve
- Retrieve fewer, then rerank. Fetch 20 candidates cheaply, rerank them, and keep the top few. A reranker costs less than sending 20 chunks to a large model.
- Use a score threshold. Drop chunks below a minimum relevance, even if the budget has room. Easy questions then use fewer tokens.
- Use smaller chunks. Chunks of 200 to 300 tokens carry less unrelated text than 1,000-token chunks.
- Remove duplicates. Overlapping chunks from the same document often repeat text. Merge or drop them.
- Put important chunks first or last. If you must include long context, avoid burying the best evidence in the middle.
Tune the budget with evidence
Treat the budget as a setting you measure. Run your evaluation set at several budgets, such as 500, 1,000, 2,000 and 4,000 tokens. Record quality score, input tokens, cost, and time to first token for each. Choose the smallest budget where quality stays within your bar.
Exercise
Your pipeline always sends the top 8 chunks. Average chunk length grows from 300 to 700 tokens after a document re-ingestion, and costs rise. What change fixes the cause, and how do you pick its value?
Show answer
Replace the fixed chunk count with a token budget for context, and fill it in rank order. Choose the value by running the evaluation set at several budgets and picking the smallest one that keeps quality within your bar.