Sub topic 4
Choosing what to include and what to leave out
This chapter assumes you have called a language model through an API, know what a system prompt is, and can read short Python. It also assumes you know the token budget from the earlier chapter. The question here is which items deserve the tokens you have.
Why selection is the core decision
The context window holds a fixed number of tokens, and every call fills it again. Most of the content competes for the same space. A system prompt, a set of retrieved documents, tool results, and old messages can each be useful, and together they can exceed the budget.
Selection is the process of deciding, for this specific call, which candidate items go in. Two things make it hard:
- Relevance depends on the current step, not on the task as a whole. A document that mattered while planning may be dead weight while writing the final answer.
- Leaving something out is invisible. If you omit a needed fact, the model does not report a gap. It guesses.
A good working rule is that every item in the context should be able to answer the question "what would the model do worse without this?" If you cannot name a concrete answer, the item is a candidate for removal.
What relevance means
An item is relevant when it changes the model's next output in a useful way. That is a stricter test than "related to the topic." A page of general product history is related to a question about resetting a password. It does not help answer it.
Relevance has several dimensions, and they can disagree:
| Dimension | Question to ask | Example |
|---|---|---|
| Topical match | Does the item talk about what the user asked? | A reset-password help page for a reset-password question |
| Authority | Is this the source the answer should come from? | The current policy document, not a forum post |
| Freshness | Is it still true? | The 2026 pricing table, not the 2023 one |
| Specificity | Does it contain the detail needed, or only background? | The exact error code, not a general troubleshooting overview |
| Uniqueness | Does it add something the context lacks? | A second source with new facts, not a copy of the first |
A candidate can score well on topic and still fail on freshness or uniqueness. Treat these as separate checks rather than one blended impression.
A selection pipeline
Selection works best as a sequence of cheap filters followed by a budget cut. Each stage removes candidates for a stated reason.
The order matters. Scoring first lets you stop early once scores fall under the threshold. Deduplication runs before the budget check so that copies do not consume tokens. The budget check comes last because it depends on what was already chosen.
A runnable example
This example uses keyword overlap as the relevance score. Real systems usually score with embeddings or a reranking model, but the pipeline around the score is the same, so you can swap the scorer without changing the rest.
import re
def tokens(text):
return set(re.findall(r"[a-z0-9_]+", text.lower()))
def estimate_tokens(text):
# Rough heuristic: about 4 characters per token for English text.
return max(1, len(text) // 4)
def score(query, passage):
# Fraction of query words that appear in the passage.
q, p = tokens(query), tokens(passage)
if not q:
return 0.0
return len(q & p) / len(q)
def jaccard(a, b):
ta, tb = tokens(a), tokens(b)
union = ta | tb
return len(ta & tb) / len(union) if union else 0.0
def select(query, candidates, min_score=0.3, max_items=5, budget=500, dup_limit=0.8):
ranked = sorted(
((score(query, c), c) for c in candidates),
key=lambda pair: pair[0],
reverse=True,
)
chosen, used = [], 0
for s, text in ranked:
if s < min_score or len(chosen) >= max_items:
break
if any(jaccard(text, c) > dup_limit for c in chosen):
continue
cost = estimate_tokens(text)
if used + cost > budget:
continue
chosen.append(text)
used += cost
return chosen, used
query = "How do I reset my password?"
candidates = [
"To reset your password, open Settings and choose Reset password.",
"Password reset links expire after 30 minutes.",
"Refunds are issued within 5 business days.",
"To reset your password, open Settings and choose Reset password.",
]
chosen, used = select(query, candidates)
for text in chosen:
print(text)Running it prints:
To reset your password, open Settings and choose Reset password.
Password reset links expire after 30 minutes.The refund passage scores 0 and stops the loop. The duplicate of the first passage scores the same as the original but is skipped because its Jaccard similarity to an already chosen item is 1.0.
Note two details in the budget step. A candidate that is too large is skipped with continue, not break, so a smaller, lower-ranked item can still fit. The score threshold uses break because the list is sorted, so nothing after the first low score can pass.
Choosing the threshold and the cutoff
There are two ways to limit selection, and they fail differently.
- A score threshold keeps everything good enough. It adapts to the query: a broad question may pass ten items, a narrow one may pass one. The risk is that a poorly calibrated scorer lets in many mediocre items or none at all.
- A top-k cutoff keeps a fixed number. It is predictable in size. The risk is that it pads the context with weak items when few are relevant, or drops useful ones when many are.
Use both, as the example does: a floor on quality and a ceiling on count and tokens. When the filters return nothing, handle that case on purpose. An empty retrieval result is information. Often the right behavior is to tell the model that no source was found, so it does not invent one.
Precision, recall, and the cost of each error
Selection can fail in two directions.
- Low recall means a needed fact was left out. The model answers from memory or guesses. The error looks like a confident wrong answer.
- Low precision means irrelevant items were included. The model may attend to the wrong passage, or the useful passage gets diluted. The next chapter covers how this turns into distraction and clash.
The costs are not symmetric. Extra items spend tokens and money on every call, and they can lower answer quality. Missing items cause errors that no later step can repair. For high-stakes facts, such as a legal limit or a dosage, favor recall for those specific items and use a stricter filter elsewhere. For background material, favor precision.
Practical heuristics
These rules work in most systems:
- Select per step, not per task. Re-run selection when the question or the agent's goal changes.
- Prefer one authoritative source to three overlapping ones.
- Cut whole items before trimming parts of them. Half a document is often harder to use than none.
- When you must shorten an item, keep the part that answers the question: the matching section, not the first N characters.
- Keep metadata with each item, such as source name and date. It helps the model weigh conflicts and helps you debug.
- Record what you included and excluded for each call. You cannot diagnose a bad answer without knowing what the model saw.
Common mistakes
- Including everything because the window is large. A larger window raises the limit. It does not make extra content free, since cost and latency scale with input size and the model still has to find the relevant part.
- Scoring against the original question only. In a multi-step task, the current sub-goal is a better query than the first user message.
- Ignoring duplicates. Retrieval often returns the same passage from several documents or chunks. Without deduplication, one fact can use a quarter of the budget.
- Keeping items "just in case." If you cannot say what the item is for, remove it. You can load it later if the model asks for it, as described in the retrieval chapter.
- Treating the threshold as fixed. Scores from different scorers or corpora are not comparable. Recalibrate when you change either.
Exercise
In the example's select function, why does the loop use break for a score below min_score but continue for an item that exceeds the budget?
Show answer
The candidates are sorted by score from highest to lowest, so once one item falls below the threshold, every later item also does, and the loop can stop. Token cost is not sorted. An item that is too large for the remaining budget says nothing about the items after it, and a smaller, lower-ranked item may still fit, so the loop skips it and keeps going.
Exercise
A support assistant answers billing questions. Retrieval returns five passages: the current refund policy, a 2022 version of the refund policy, a blog post on company history, a duplicate of the current policy from another page, and an FAQ entry with the refund time limit. Which would you include, and which relevance dimension rules out each one you drop?
Show answer
Include the current refund policy and the FAQ entry with the time limit. Drop the 2022 policy on freshness, since it may contradict the current one. Drop the blog post on topical match, because it does not help answer the question. Drop the duplicate on uniqueness, since it adds no new facts and only spends tokens.