Search Tutorials
--Ads--Deduplication and Context Window Budgeting
Fit the best context into a token budget without duplicates.
The final prompt has a budget: the model's context window, your cost target and your latency target. Retrieval results often waste that budget on overlapping chunks, repeated documents and low-value text. This lesson builds a context builder that deduplicates retrieved chunks, merges neighbours and fills a token budget with the most valuable content first.
Sources of waste
- Overlap. Chunks created with overlap repeat 10–20% of their text when neighbours are both retrieved.
- Duplicates. The same paragraph in several documents, or several query variations retrieving the same chunk.
- One document dominating. Eight chunks from one long manual crowd out a short but relevant policy.
- Low-value chunks that made the top k but have low rerank scores.
Step 1: Exact and near-duplicate removal
import re
def normalise(text: str) -> str:
return re.sub(r"\s+", " ", text.lower()).strip()
def dedupe(hits: list[dict]) -> list[dict]:
"""hits are sorted best first; keep the first copy of identical text."""
seen, unique = set(), []
for h in hits:
key = normalise(h["text"])
if key not in seen:
seen.add(key)
unique.append(h)
return unique
Step 2: Merge adjacent chunks from the same document
If chunks 4 and 5 of the same document are both retrieved, send them as one continuous passage without the overlapping text. This needs the doc_id and chunk_index metadata recommended in Extracting Metadata.
def strip_overlap(previous: str, current: str, max_overlap: int = 400) -> str:
"""Remove the start of `current` that repeats the end of `previous`."""
for size in range(min(max_overlap, len(previous), len(current)), 20, -1):
if previous.endswith(current[:size]):
return current[size:]
return current
def merge_adjacent(hits: list[dict]) -> list[dict]:
by_doc: dict[str, list[dict]] = {}
for h in hits:
by_doc.setdefault(h["doc_id"], []).append(h)
merged = []
for items in by_doc.values():
items.sort(key=lambda h: h["chunk_index"])
group = dict(items[0], last_index=items[0]["chunk_index"])
for h in items[1:]:
if h["chunk_index"] == group["last_index"] + 1: # directly follows the group
group["text"] += " " + strip_overlap(group["text"], h["text"])
group["score"] = max(group["score"], h["score"])
group["last_index"] = h["chunk_index"]
else:
merged.append(group)
group = dict(h, last_index=h["chunk_index"])
merged.append(group)
return sorted(merged, key=lambda h: h["score"], reverse=True)
Step 3: Fill the budget greedily
Count tokens and add passages in order of score until the budget is reached. Cap the number of passages per document to keep sources diverse. For exact counts, the API's token counting endpoint gives the real number for the model you use; for a fast estimate inside a loop, about four characters per token is a reasonable rule for English.
import anthropic
client = anthropic.Anthropic()
def estimate_tokens(text: str) -> int:
return len(text) // 4 + 1 # fast approximation for English
def build_context(hits: list[dict], budget_tokens: int = 6000, max_per_doc: int = 3) -> str:
hits = merge_adjacent(dedupe(hits))
used, per_doc, parts = 0, {}, []
for h in hits:
if per_doc.get(h["doc_id"], 0) >= max_per_doc:
continue
block = f'<source id="{len(parts) + 1}" doc="{h["doc_id"]}">\n{h["text"]}\n</source>'
cost = estimate_tokens(block)
if used + cost > budget_tokens:
continue # try smaller passages further down the list
parts.append(block)
used += cost
per_doc[h["doc_id"]] = per_doc.get(h["doc_id"], 0) + 1
return "\n\n".join(parts)
def exact_prompt_tokens(prompt: str) -> int:
return client.messages.count_tokens(
model="claude-opus-5-5",
messages=[{"role": "user", "content": prompt}],
).input_tokens
Choosing the budget
Current models accept very long inputs, so the budget is usually driven by cost and latency rather than the context limit. Things to consider:
- Cost per query grows linearly with input tokens. A 6,000-token context at a million queries per month is a very different bill from a 60,000-token one.
- Latency: more input takes longer to process before the first output token.
- Quality: beyond a point, more chunks add noise rather than evidence. Find the knee of the curve with your evaluation set by trying budgets of, say, 2k, 4k, 8k and 16k tokens.
- Output room: leave enough
max_tokensfor the answer itself.
Key takeaways
- Deduplicate retrieved chunks and merge adjacent chunks from the same document.
- Fill a token budget greedily by score, with a per-document cap for diversity.
- Estimate tokens quickly in loops; use the token counting API for exact numbers.
- Pick the budget from measured quality, cost and latency, not from the context window size.