Contextual retrieval

In one sentence

At indexing time, an LLM writes 50–100 tokens situating each chunk in its document; you prepend them before embedding and BM25. Anthropic cut top-20 retrieval failures 49% (67% with reranking), at no query-time cost.

Analogy: A page torn out of a report that says "revenue grew 3%" is useless. Staple a sticky note reading "ACME, Q2 2023 filing" to it, and anyone can file it and find it again.

One cached document feeds an LLM call per chunk; the context-prefixed chunk goes into both indexes, and queries run unchanged.

How it works

  • Split chunks lose context: "revenue grew by 3%" names neither company nor quarter, so search misses it.
  • Each call sees the whole document plus one chunk; prompt caching makes the repeated document reads cheap.
  • The prepended context gives BM25 the missing exact terms and moves the embedding into the right neighborhood.
  • Store the context next to the original text: you cite the real chunk and can regenerate contexts later.
  • Under ~200K tokens (~500 pages) of knowledge, skip retrieval and send everything with caching.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your filings bot uses hybrid search, a reranker, and already prepends title and section path to chunks. It still misses chunks like "revenue grew 3% over the previous quarter" for "ACME Q2 2023 revenue growth": the quarter and figures live elsewhere in the filing. Best next change?

Go deeper

Full explanation

Contextual retrieval repairs chunks that lost their context when the document was split. A chunk reading "The company's revenue grew by 3% over the previous quarter" names neither the company nor the quarter, so neither its embedding nor Lexical search & BM25 can match "ACME Q2 2023 revenue growth".

The fix, published by Anthropic in 2024, runs once, at indexing time:

  1. For each chunk, send the whole document plus the chunk to a cheap LLM: "give a short succinct context to situate this chunk within the overall document".
  2. It returns ~50–100 tokens, e.g. "From ACME's Q2 2023 SEC filing; previous quarter revenue was $314M."
  3. Prepend that context to the chunk and index the result in both the vector store (contextual embeddings) and the BM25 index (contextual BM25).

Query time does not change, so latency doesn't either. The cost is one LLM call per chunk, each re-reading the full document; Prompt caching makes that cheap, because the document is cached once and every chunk reads it from cache.

Store the generated context next to the original text, not instead of it: you cite and show the real chunk, and you can regenerate contexts when you change the prompt or model.

Code Contextualize chunks against a cached document
pythonContextualize chunks against a cached document
import anthropic

client = anthropic.Anthropic()
MODEL = "claude-haiku-4-5"  # any cheap, fast model: the task is short and easy

# Prompt from Anthropic's contextual retrieval post
INSTRUCTION = (
    "Here is the chunk we want to situate within the whole document\n"
    "<chunk>\n{chunk}\n</chunk>\n"
    "Please give a short succinct context to situate this chunk within the "
    "overall document for the purposes of improving search retrieval of the "
    "chunk. Answer only with the succinct context and nothing else."
)

def situate(doc: str, chunk: str) -> str:
    resp = client.messages.create(
        model=MODEL,
        max_tokens=150,
        messages=[{"role": "user", "content": [
            # Same document for every chunk -> written to cache once, then read cheaply
            {"type": "text", "text": f"<document>\n{doc}\n</document>",
             "cache_control": {"type": "ephemeral"}},
            {"type": "text", "text": INSTRUCTION.format(chunk=chunk)},
        ]}],
    )
    return resp.content[0].text.strip()

def index_document(doc_id: str, doc: str) -> None:
    for i, chunk in enumerate(split_into_chunks(doc, tokens=800)):
        context = situate(doc, chunk)       # first call writes the cache
        text = f"{context}\n\n{chunk}"       # this is what gets indexed
        vector_store.upsert(id=f"{doc_id}:{i}", vector=embed(text),
                            payload={"chunk": chunk, "context": context})
        bm25_index.add(id=f"{doc_id}:{i}", text=text)  # contextual BM25 too
Real example

A financial-research bot indexes 1,000 SEC filings of ~8K tokens each: 8M document tokens, ~10,000 chunks of 800 tokens. Contextualizing them costs ~$8 one-time at Anthropic's 2024 estimate (~$1.02 per million document tokens with caching). Before, "ACME revenue growth Q2 2023" missed the chunk "revenue grew by 3%" because "ACME" and "Q2 2023" appeared only on the filing's cover page. After, both terms sit in the prepended context, so BM25 matches them exactly and the embedding lands in the right neighborhood.

Trade-offs +3 · −4

+ You gain

  • Large recall gains with no change to the query path and no added query latency.
  • Helps both embeddings and BM25, and stacks with reranking (−35% → −49% → −67% failures).
  • One-time cost that prompt caching makes small.

− You pay

  • One LLM call per chunk: slower ingestion, and a full re-run whenever you re-chunk or change the prompt.
  • Indexed text grows ~12% (100 tokens on an 800-token chunk).
  • A wrong generated context silently mis-indexes its chunk.
  • Documents longer than the model's window must be split into sections first.

Use it when

Long documents whose chunks depend on surrounding context (filings, contracts, manuals, policies), where "the company", "this section" or "the previous quarter" lose their referent once split.

Avoid it when

Knowledge bases under ~200K tokens (put everything in a cached prompt instead), short self-contained items like FAQs or tickets, or when prepending title and section headers already closes the gap.

Numbers to know 5
  • Top-20 retrieval failure rate in Anthropic's tests: 5.7% baseline → 3.7% with contextual embeddings (−35%).
  • Adding contextual BM25: 2.9% (−49%); adding reranking on top: 1.9% (−67%).
  • Generated context: ~50–100 tokens per chunk.
  • ~$1.02 per million document tokens, one-time, with prompt caching (Claude 3 Haiku pricing, 2024); scale by your model's price.
  • Under ~200K tokens (~500 pages) of knowledge, skip retrieval and send it all with caching.
Common pitfalls 4
  • Firing every chunk of a document in parallel before the first response starts: the cache entry doesn't exist yet, so each call writes it at 1.25× the input price instead of reading it at 0.1×. Send one call, then fan out.
  • Silent cache misses: if a document is under the model's minimum cacheable length (4,096 tokens on Claude Haiku 4.5) or the 5-minute TTL lapses, nothing is cached and no error is raised.
  • Citing or displaying the generated context as if it were source text; a model wrote it and it can be wrong.
  • Skipping the free baseline: prepend title and section path first, and measure recall@20 before paying for LLM calls.
Interview questions 2

Answer out loud first, then reveal.

How is contextual retrieval different from just prepending the document title?Show answer

Title prepending is the free baseline and I'd ship it first, together with the section path. It answers "which document" but not chunk-specific references. Contextual retrieval writes a context per chunk: not just "ACME 10-Q" but "Q2 2023 revenue section; prior quarter $314M". It costs one LLM call per chunk at index time and nothing at query time. I'd measure recall@20 with headers only, read the misses, and pay for contextual retrieval when they are chunks whose referent lives elsewhere in the document.

Your corpus is 50M tokens. What does contextual retrieval cost, and what's the trap?Show answer

At Anthropic's 2024 estimate of ~$1 per million document tokens with caching, about $50 one-time; a few times more with pricier newer models, still small next to engineering time. The trap is that the estimate assumes cache hits. If I fire all chunks of a document before the first call writes the cache, or let the 5-minute TTL lapse, every call writes the whole document to cache at 1.25× the input price instead of reading it at 0.1×, several times the budget. So I warm the cache with one call per document, then fan out its chunks, and parallelize across documents.