Search Tutorials
--Ads--Contextual Retrieval
Prepend LLM-written context to every chunk before embedding and BM25 indexing.
Contextual retrieval is a technique published by Anthropic in 2024 that fixes the lost-context problem of chunking (see Late Chunking and Contextual Chunk Headers). Before indexing, an LLM reads each chunk together with its whole document and writes a short piece of context that situates the chunk. That context is prepended to the chunk, and the combined text is used for both the embedding index and the BM25 index.
Why it works
A chunk such as "Revenue grew by 3% over the previous quarter" does not mention the company or the period. After contextualisation it starts with "From Acme Corp's Q2 2026 quarterly report, financial results section." Now a question about "Acme's Q2 revenue" matches it in both the embedding space and BM25. In Anthropic's experiments, contextual embeddings reduced the top-20 retrieval failure rate by about 35%; adding contextual BM25 raised that to about 49%, and adding a reranker on top to about 67%.
Implementation
The whole document is the same for every chunk in it, so it is a perfect candidate for prompt caching: the document is processed once, and each following chunk only pays for the chunk text and a cheap cache read of the document.
import anthropic
client = anthropic.Anthropic()
INSTRUCTIONS = """Write a short context (one or two sentences) that places the chunk below
within the overall document, to improve search retrieval of the chunk. Mention the document's
subject and the section or topic the chunk belongs to. Reply with the context only."""
def contextualize(document: str, chunk: str) -> str:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=300,
output_config={"effort": "low"},
messages=[{
"role": "user",
"content": [
# Identical for every chunk of this document -> cached after the first call
{"type": "text", "text": f"<document>\n{document}\n</document>",
"cache_control": {"type": "ephemeral"}},
{"type": "text", "text": f"<chunk>\n{chunk}\n</chunk>\n\n{INSTRUCTIONS}"},
],
}],
)
print("cache read tokens:", response.usage.cache_read_input_tokens)
return response.content[0].text.strip()
def contextualize_document(document: str, chunks: list[str]) -> list[str]:
return [f"{contextualize(document, c)}\n\n{c}" for c in chunks]
The first call for a document writes it to the cache; later calls for the same document should show a non-zero cache_read_input_tokens. Very short documents (below the model's minimum cacheable length) are not cached, which is fine because they are cheap anyway. Process the chunks of one document one after another so the cache stays warm.
Index the contextualised chunks
Use the contextualised text for indexing (embedding and BM25), and decide what to show the LLM at answer time. Including the context there too is usually helpful, since it tells the model where each chunk comes from.
from hybrid import HybridRetriever # from the hybrid search lesson
from chunkers import recursive_split
records = []
for doc_id, document in documents.items():
chunks = recursive_split(document, 1200)
for i, text in enumerate(contextualize_document(document, chunks)):
records.append({"id": f"{doc_id}:{i}", "text": text})
retriever = HybridRetriever([r["text"] for r in records]) # contextual embeddings + contextual BM25
Cost and practical notes
- Indexing cost is one LLM call per chunk. With caching, most input tokens are cheap cache reads. Re-run only for new or changed documents, and cache the generated context by chunk hash.
- Very long documents that exceed what you want to send per call can be split into large sections, using the section as the "document".
- Batch processing. For large one-off indexing jobs, the Message Batches API halves the price in exchange for asynchronous results.
- Custom instructions help: for financial filings, ask the model to always mention the company, the period and the statement type.
Contextual embeddings + contextual BM25 + reciprocal rank fusion + a reranker is one of the strongest general-purpose retrieval setups available, and every part is covered in this tutorial.
Key takeaways
- Contextual retrieval prepends LLM-written, document-aware context to each chunk before indexing.
- Use the contextualised text for both embeddings and BM25 for the biggest gain.
- Prompt caching makes it affordable: the document is cached and reused for all of its chunks.
- Combine it with hybrid search and reranking for the best results.