Search Tutorials
--Ads--Context Compression and Filtering
Remove irrelevant sentences and chunks to save tokens and reduce noise.
A retrieved chunk of 300 words may contain one relevant sentence. Sending all 300 words to the LLM costs tokens, adds latency and gives the model more irrelevant text to be distracted by. Context compression removes the irrelevant parts of retrieved chunks, or whole chunks, before generation.
Three levels of compression
| Level | Method | Cost |
|---|---|---|
| Drop whole chunks | Rerank score or similarity threshold | Very low (reuses reranker scores) |
| Drop sentences | Embedding similarity of each sentence to the query | Low (local embeddings) |
| Extract relevant parts | An LLM copies out only the relevant passages | One LLM call per query |
Dropping whole chunks
If you use a reranker (previous lesson), you already have a good relevance score for every chunk. Dropping chunks below a threshold is the cheapest and safest form of compression:
relevant = [(chunk, score) for chunk, score in reranked if score >= 0.2]
Sentence-level filtering with embeddings
Split each chunk into sentences, score each sentence against the query, and keep the best sentences plus their neighbours, so that the kept text still reads naturally.
import numpy as np
from semantic_chunker import split_sentences # from the semantic chunking lesson
from rag_helpers import embed
def compress_chunk(query: str, chunk: str, keep_ratio: float = 0.4,
min_sentences: int = 2, neighbours: int = 1) -> str:
sentences = split_sentences(chunk)
if len(sentences) <= min_sentences:
return chunk
scores = embed(sentences) @ embed(query, query=True)[0]
n_keep = max(min_sentences, int(len(sentences) * keep_ratio))
keep = set()
for i in np.argsort(-scores)[:n_keep]:
keep.update(range(max(0, i - neighbours), min(len(sentences), i + neighbours + 1)))
parts, previous = [], -2
for i in sorted(keep):
if i != previous + 1:
parts.append("...") # mark removed text
parts.append(sentences[i])
previous = i
return " ".join(parts)
LLM-based extraction
An LLM can judge relevance far better than sentence embeddings: it understands that "the limit was raised to 6,000" answers a question about hotel budgets even if the word "hotel" appears only in the previous sentence. Ask it to copy out the relevant passages verbatim for all chunks in one call:
from pydantic import BaseModel
import anthropic
client = anthropic.Anthropic()
class Extract(BaseModel):
chunk_id: str
relevant_text: str # verbatim excerpts, or "" if nothing is relevant
class Extraction(BaseModel):
extracts: list[Extract]
def llm_compress(query: str, chunks: dict[str, str]) -> dict[str, str]:
sources = "\n\n".join(f'<chunk id="{cid}">\n{text}\n</chunk>' for cid, text in chunks.items())
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=4000,
output_config={"effort": "low"},
messages=[{"role": "user", "content":
f"{sources}\n\nFor each chunk, copy out word for word only the sentences needed to "
f"answer the question, including any sentence that defines what they refer to. "
f"Use an empty string if a chunk is irrelevant.\n\nQuestion: {query}"}],
output_format=Extraction,
)
result = {e.chunk_id: e.relevant_text.strip() for e in response.parsed_output.extracts}
return {cid: text for cid, text in result.items() if text and cid in chunks}
Asking for verbatim copies keeps the compressed text faithful to the source and lets you verify it: every extract should be found inside its original chunk.
Is compression worth it?
- Pros: fewer tokens in the final prompt, less distraction, more room for additional sources.
- Cons: extra latency (especially the LLM method), and the risk of removing context the answer needs, such as a definition two sentences earlier or a condition like "unless approved by HR".
With modern long-context models, the final LLM is usually good at ignoring irrelevant text in a handful of chunks. Compression pays off most when you send many chunks, when chunks are very long (whole pages or parent sections), or when token cost dominates. Measure answer quality with and without it.
LangChain's ContextualCompressionRetriever with LLMChainExtractor or EmbeddingsFilter, and LlamaIndex's node postprocessors, implement the same ideas. Specialised models such as LLMLingua compress prompts at the token level.
Key takeaways
- Compression removes irrelevant chunks or sentences before generation.
- Dropping low-scoring chunks after reranking is cheap and safe.
- Sentence filtering and LLM extraction cut more tokens but can remove needed context.
- Use it when context is large or expensive, and confirm with an evaluation that answers do not get worse.