Sub topic 10
Budget retrieved context
This chapter assumes you have built a retrieval-augmented generation (RAG) pipeline that embeds documents, searches for similar chunks, and pastes them into the prompt. It also assumes you know how input tokens are priced and how prefill delay affects time to first token, both covered in earlier chapters.
Why retrieved context needs a budget
In most RAG applications, retrieved chunks are the largest part of the prompt. A system prompt might be 300 tokens and a question 50 tokens. Ten retrieved chunks of 500 tokens each add 5,000. Those tokens cost money on every request, and they lengthen prefill, which delays the first output token.
A fixed "top-k" setting hides this cost. If you always retrieve 20 chunks, you pay for 20 chunks even when two answer the question. Context budgeting replaces "always send k chunks" with "send the best chunks that fit a token limit."
Here is the cost difference using the placeholder price of $1.00 per million input tokens:
| Strategy | Context tokens per request | Input cost per request | Cost at 100,000 requests per day |
|---|---|---|---|
| 20 chunks of 500 tokens | 10,000 | $0.0100 | $1,000 |
| 5 chunks of 400 tokens | 2,000 | $0.0020 | $200 |
The saving is real only if answer quality holds. Treat every budget change as an experiment that you check against your evaluation set.
Work out the budget
Start from the model's context window and subtract everything else. What remains is the retrieval budget.
- Take the context window, or a smaller working limit you choose for cost reasons.
- Subtract the system prompt tokens.
- Subtract the user question and any conversation history.
- Subtract a reserve for the output (your
max_tokenssetting). - Subtract a safety margin, such as 5 to 10 percent, because token counts from a local tokenizer can differ slightly from the provider's count.
The result is a ceiling, not a target. A 100,000-token window does not mean you should fill it. Many applications get the same answer quality from 2,000 to 4,000 tokens of well-chosen context. Find your own number by measuring.
def retrieval_budget(window, system_tokens, question_tokens, history_tokens,
max_output_tokens, margin=0.05, cost_cap=None):
"""Return how many tokens of retrieved context we may send."""
fixed = system_tokens + question_tokens + history_tokens + max_output_tokens
available = int((window - fixed) * (1 - margin))
if cost_cap is not None:
available = min(available, cost_cap)
return max(available, 0)
print(retrieval_budget(16_000, 300, 50, 400, 600, cost_cap=3_000))The cost_cap argument is the cost lever. The window sets what is possible, and the cap sets what you choose to spend.
Select chunks under a budget
A budgeted selector does four things:
- Rank candidates by retrieval score.
- Drop candidates below a minimum score, so weak matches never enter the prompt.
- Drop near-duplicates, which are common when documents overlap or chunks use a sliding window.
- Add chunks until the next one would exceed the budget, and cap the size of any single chunk.
import tiktoken
ENC = tiktoken.get_encoding("cl100k_base")
def select_chunks(chunks, budget_tokens, min_score=0.0, max_chunk_tokens=400):
"""Pick the best-scoring chunks that fit in budget_tokens.
Each chunk is a dict with 'id', 'text', 'score', and optional 'position'.
Returns the chosen chunks in document order and the tokens used.
"""
chosen, used, seen = [], 0, set()
for chunk in sorted(chunks, key=lambda c: c["score"], reverse=True):
if chunk["score"] < min_score:
break # sorted by score, so everything after is weaker
key = " ".join(chunk["text"].lower().split())
if key in seen:
continue # exact duplicate after whitespace normalization
tokens = ENC.encode(chunk["text"])
if len(tokens) > max_chunk_tokens:
tokens = tokens[:max_chunk_tokens]
if used + len(tokens) > budget_tokens:
continue # this one does not fit, a smaller one still might
seen.add(key)
chosen.append({**chunk, "text": ENC.decode(tokens), "tokens": len(tokens)})
used += len(tokens)
chosen.sort(key=lambda c: c.get("position", 0))
return chosen, used
chunks = [
{"id": "a", "text": "Refunds are issued within 14 days of a return.", "score": 0.91, "position": 2},
{"id": "b", "text": "Refunds are issued within 14 days of a return.", "score": 0.90, "position": 7},
{"id": "c", "text": "Our offices are closed on public holidays.", "score": 0.22, "position": 4},
{"id": "d", "text": "Returns must include the original receipt.", "score": 0.78, "position": 3},
]
picked, used = select_chunks(chunks, budget_tokens=60, min_score=0.5)
print([c["id"] for c in picked], used)Run as shown, this keeps chunks a and d. Chunk b is a duplicate of a, and chunk c falls below the score threshold.
Two details matter in this code. Truncating by tokens can cut a sentence in half, so for production prefer to split documents into well-sized chunks at indexing time and use the cap only as a safety net. The continue on a chunk that does not fit lets later, smaller chunks fill the remaining space. If you would rather stop at the first chunk that does not fit, use break instead.
The selection flow
The diagram shows where each filter sits between retrieval and the model call.
Retrieve wide, then rerank narrow
Vector search is cheap and approximate. A common pattern is to retrieve 30 to 50 candidates, rerank them with a more precise but slower scorer, and apply the budget to the reranked list. The reranker may be a cross-encoder model or a small LLM call. This costs extra latency and money at the reranking step, so it pays off only when it lets you cut the final context substantially. Measure both sides: the reranker's cost and latency against the input tokens and prefill time it saves.
Choose the threshold from data
A score threshold such as 0.5 is only meaningful for your embedding model and your data. Scores from different models are not comparable. To set it:
- Take questions from your evaluation set with known relevant chunks.
- Record the retrieval scores of relevant and irrelevant chunks.
- Pick a threshold that keeps most relevant chunks while dropping most irrelevant ones.
- Re-check whenever you change the embedding model or the chunking.
Also handle the empty case. If no chunk passes the threshold, you have a decision to make: answer without context, say that nothing relevant was found, or fall back to a broader search. Do not silently lower the threshold per request, because that hides retrieval problems.
Order and format matter
Models often use information at the start and end of a long context more reliably than information in the middle. If you send many chunks, put the highest-scoring ones first and last. For small budgets of a few chunks, document order often reads more coherently and is a reasonable default. Test both against your evaluation set.
Formatting costs tokens too. Each chunk's header, separator, and metadata repeats in every request. Keep wrappers short, and include only metadata the model needs, such as a source ID for citations. A 40-token header on each of 8 chunks is 320 tokens you pay for on every call.
Interaction with caching
Retrieved chunks change per query, so they cannot be part of a stable cached prefix. Provider prompt caching works on an exact prefix, so keep the system prompt and fixed instructions first, then place retrieved context after them. If the same chunks are retrieved for many queries, response caching on a normalized question may help more. Keep the budget small even with caching, because uncached tokens are still billed at the full rate.
Common errors
- Counting characters instead of tokens. Characters per token vary by language and content. Count with a tokenizer.
- Budgeting only the context. Forgetting the output reserve causes truncated answers or request errors when the window is nearly full.
- Keeping redundant chunks. Overlapping windows often return the same sentence several times. Deduplicate before spending tokens.
- Ignoring conversation history. In chat applications, history grows each turn and silently shrinks the retrieval budget. Summarize or trim old turns.
- Tuning on cost alone. Track answer quality, retrieved-token counts, and latency together.
What to log
For each request, record the number of candidates retrieved, the number kept, the tokens used against the budget, and the top score. A rising share of requests that hit the budget limit means your chunks are too large or the threshold too loose. A rising share with zero kept chunks points to an indexing or embedding problem. These metrics feed the budgets and monitoring chapter later in this tutorial.
Exercise
Your model has a 16,000-token window. The system prompt is 500 tokens, the question and history total 700 tokens, and you reserve 800 tokens for output. You apply a 5 percent safety margin to the remaining space and also set a cost cap of 4,000 tokens. How many tokens of retrieved context may you send, and why is the cost cap the binding limit?
Show answer
Fixed tokens are 500 + 700 + 800 = 2,000. The remaining space is 16,000 - 2,000 = 14,000. After a 5 percent margin, that is 13,300 tokens. The cost cap of 4,000 is lower, so the budget is 4,000 tokens. The window allows far more than you have chosen to spend, so the cost cap decides how much context you send.
Exercise
A request retrieves 10 chunks. Chunks 3 and 4 are identical text from overlapping documents, and chunks 8 to 10 score below your tuned threshold. What does the selector do with them, and what two numbers should you log to detect a retrieval problem later?
Show answer
It keeps one copy of the duplicated text and drops the other, and it drops chunks 8 to 10 because their scores are under the threshold. Log the number of chunks kept and the tokens used against the budget, and ideally the top retrieval score as well. Persistent zero-kept requests or constant budget exhaustion signal a problem with indexing, chunk size, or the threshold.