Özer Cem KELAHMETKELAHMET
Articles · Chunking

Contextual retrieval explained: give every chunk its missing context before you index it

A chunk that says revenue rose 3% is useless if it never names the company. Contextual retrieval adds a short description of where each chunk sits before indexing. This guide explains the methods, measures the effect with BM25 and works out the cost.

Download Markdown
At a glance
Reading time
19 min
Sections
9
Code examples
3
Tables
4
Sources
7
Published
25 Nov 2026
In 30 seconds
What changed
Anthropic publishes contextual retrieval
Why it matters
Context is a property of your documents, not a setting to switch on everywhere.
What to do
Find your orphaned chunks

Chunking solves one problem and creates another. Splitting a 40-page report into 800-token pieces lets a retriever find the exact paragraph that answers a question. But the paragraph often loses the facts that made it findable. "Revenue rose 3% compared with the same period last year" does not say which company, which year or which report. A question about "Acme's Q2 revenue" has nothing to match against.

Contextual retrieval is the simple fix: before you index a chunk, add a sentence or two that says where it comes from. Anthropic named and measured the technique in 2024 (see the contextual retrieval tool page). Since then, embedding vendors have built the same idea into models, and new research has tested which part of the added context actually helps. This article walks through the methods, measures the effect on a small corpus with code you can run, and works out what it costs at current prices.

If you are new to chunking itself, read chunking for RAG first, or try the chunking strategies simulation.

What happened

Anthropic publishes contextual retrieval (19 September 2024)

Anthropic's post described using a language model to write a short context, "usually 50-100 tokens", for each chunk, and prepending it before both embedding and building a BM25 index. Measured as the failure rate of top-20 retrieval (1 minus recall@20), the baseline was 5.7%. Contextual embeddings cut it to 3.7%, a 35% reduction. Adding contextual BM25 cut it to 2.9%, a 49% reduction. Adding a reranker on top cut it to 1.9%, a 67% reduction. The post estimated a one-time cost of $1.02 per million document tokens with prompt caching.

A study compares late chunking and contextual retrieval (28 April 2025)

Carlo Merola and Jaspinder Singh compared the two main ways to put document context into chunks. Their abstract reports that contextual retrieval "preserves semantic coherence more effectively" but needs more compute, while late chunking is more efficient but tends to lose some relevance and completeness.

Voyage AI releases voyage-context-4 (29 June 2026)

Voyage AI, part of MongoDB, released voyage-context-4, a contextualized chunk embedding model: each chunk's vector reflects the whole document without any added text. MongoDB reports it beats voyage-context-3 by 1.40% on document-level and 2.08% on chunk-level retrieval (NDCG@10 over 39 datasets). When voyage-context-3 launched in July 2025, MongoDB reported it beating Anthropic-style contextual retrieval by 20.54% on chunk-level and 2.40% on document-level retrieval. Price is $0.12 per million tokens, against $0.18 for voyage-context-3.

A placebo-controlled test asks why context helps (7 October 2026)

Andrey Kuehlkamp, Priscila Correa Saboia Moreira and Samuel Rund tested four ways of adding document structure, including LLM-generated chunk contexts and heading-path metadata, on 200 Wikipedia Featured Articles and 1,585 QASPER papers. Their key control was a placebo: real heading paths shuffled across documents. Structure-aligned chunks with real heading paths beat contextualized fixed windows by +0.022 and +0.012 cov-nDCG@10, and beat the placebo by +0.010 and +0.016. Their summary: "the cause is content, not tokens." Naive two-stage hierarchical retrieval hurt, by -0.033 and -0.015.

Why chunks lose their meaning

Think of a chunk as a page torn from a book. The page still has words on it, but it lost the cover, the chapter title and the previous page. A reader can often work out what it is about. A retriever cannot, because it scores only the text it is given.

Three kinds of information disappear most often:

Table 1. Why chunks lose their meaning
Lost information Example chunk text Question that fails What context restores
The entity "The company ended the period with 1,200 employees." "How many staff does Acme have?" "From Acme Robotics' Q2 2026 report"
The time "Revenue rose 3% year on year." "Acme revenue growth Q2 2026" the period covered
The section role "This does not apply to contractors." "Does the leave policy cover contractors?" "Section: Parental leave, eligibility"

Both retrieval families suffer. BM25 matches words, so a missing company name is a missing match. Dense embeddings encode meaning, but a chunk that never mentions the company produces a vector close to every other company's revenue paragraph. The question then lands among dozens of look-alike chunks, and which one ranks first is close to a coin toss.

Four ways to restore context

There are now four practical methods. They differ in what they add, when they run and what they cost.

1. LLM-written chunk context (contextual retrieval). For each chunk, send the whole document plus the chunk to a small language model and ask for a short situating description. Prepend the answer to the chunk text, then embed and index the combined text. The contextual RAG simulation shows the flow. A prompt in this style looks like this:

<document>
{full document text}
</document>
Here is a chunk from the document above:
<chunk>
{chunk text}
</chunk>
Write a short context (one or two sentences) that situates this chunk within
the document, to improve search retrieval of the chunk.
Answer only with the succinct context and nothing else.

The last line is quoted from Anthropic's published prompt; the rest is a close paraphrase. Because the same document is sent once per chunk, prompt caching matters: the document is written to the cache on the first call and read cheaply on the others.

2. Heading paths and metadata. Prepend deterministic text you already have: document title, date, author and the section path, such as "Employee handbook > Leave > Parental leave > Eligibility". No model call is needed. The October 2026 study found that real heading paths on structure-aligned chunks beat LLM-contextualized fixed windows on both of its corpora.

3. Late chunking. Run a long-context embedding model over the whole document first, then pool the token vectors inside each chunk's span. Each chunk vector carries information from the rest of the document. No text is added and no extra model calls are made, but the embedding model must accept the whole document.

4. Contextualized chunk embedding models. Models such as voyage-context-4 take all chunks of a document in one call and return one vector per chunk that reflects the full document. MongoDB says voyage-context-4 splits documents longer than 32K tokens and embeds the parts independently, supports overlapping chunks and offers 2048, 1024, 512 and 256 dimensions. The call looks like vo.contextualized_embed(...) with model="voyage-context-4". The API takes inputs as a list of lists, one inner list of chunks per document in order; the reference page caps a request at 1,000 inputs, 120K total tokens and 16K chunks.

Table 2. Four ways to restore context
Method What it adds Extra cost Helps BM25 too? Main limit
LLM-written context 50 to 100 tokens of text per chunk One LLM call per chunk (cached document) Yes Ingestion cost and latency; model can be wrong
Heading path and metadata Title, date, section path Almost none Yes Needs documents with real structure
Late chunking Nothing visible; changes the vector One long embedding pass per document No Embedding model context limit
Contextualized embedding model Nothing visible; changes the vector Embedding price per token No Vendor lock-in; dense side only

The last column matters. Only the text-based methods improve keyword search. In Anthropic's results, contextual BM25 added a further step from 3.7% to 2.9% failure on top of contextual embeddings, which is why the two methods are usually combined in hybrid search.

Measuring the effect

To see the mechanism without a paid model, the script below builds a corpus that has exactly the problem described above: 20 companies, 3 quarters and 6 report sections, for 360 short chunks. No chunk names its company or quarter. Each query asks for one company's figure in one quarter, so exactly one chunk is correct. We index four versions of the corpus with BM25 and TF-IDF:

  • plain: the chunk text alone;
  • context header: a header such as "Acme Robotics quarterly report Q2 2026, section revenue." in front of each chunk, standing in for an LLM-written context;
  • company only: a weaker header that names the company but not the quarter or section;
  • placebo: real headers, but shuffled so each chunk gets another chunk's header, the same control the October 2026 paper used.
# pip install rank_bm25 scikit-learn numpy
import random, re
from rank_bm25 import BM25Okapi

random.seed(7)
companies = ["Acme Robotics", "Borealis Foods", "Cobalt Freight", "Dunmore Bank", "Eldridge Pharma",
             "Fernhill Energy", "Granite Telecom", "Harbor Retail", "Ironwood Mining", "Juniper Health",
             "Kestrel Airlines", "Lumen Software", "Meridian Insurance", "Northgate Steel", "Orchid Textiles",
             "Pioneer Water", "Quarry Cement", "Redwood Media", "Summit Hotels", "Tidewater Shipping"]
quarters = ["Q1 2026", "Q2 2026", "Q3 2026"]
topics = {"revenue": "Revenue for the quarter rose {v}% compared with the same period last year.",
          "margin": "Operating margin came in at {v}%, as cost savings offset higher input prices.",
          "headcount": "The company ended the period with {v}00 employees after a hiring freeze.",
          "debt": "Net debt fell to {v} times EBITDA following a bond repayment.",
          "outlook": "Management expects growth of about {v}% for the full year.",
          "dividend": "The board approved a dividend of {v} cents per share."}
words = {"revenue": "revenue growth", "margin": "operating margin", "headcount": "number of employees",
         "debt": "net debt", "outlook": "full year outlook", "dividend": "dividend per share"}
chunks, meta = [], []
for c in companies:
    for q in quarters:
        for t, tmpl in topics.items():
            chunks.append(tmpl.format(v=random.randint(2, 19))); meta.append((c, q, t))

tok = lambda s: re.findall(r"[a-z0-9]+", s.lower())
header = lambda m: f"{m[0]} quarterly report {m[1]}, section {m[2]}."
perm = list(range(len(meta))); random.shuffle(perm)
corpora = {"plain": chunks,
           "context header": [header(m) + " " + ch for m, ch in zip(meta, chunks)],
           "company only": [f"{m[0]} quarterly report. " + ch for m, ch in zip(meta, chunks)],
           "placebo": [header(meta[perm[i]]) + " " + ch for i, ch in enumerate(chunks)]}
queries = [(f"What was {c}'s {words[t]} in {q}?", i) for i, (c, q, t) in enumerate(meta)]

for name, texts in corpora.items():
    bm = BM25Okapi([tok(x) for x in texts]); hit5 = 0.0
    for qtext, gold in queries:
        s = bm.get_scores(tok(qtext))
        better, ties = (s > s[gold]).sum(), (s == s[gold]).sum() - 1
        hit5 += min(1.0, max(0.0, (5 - better) / (ties + 1)))   # expected hit under random tie-breaking
    print(f"{name:15s} recall@5 = {hit5 / len(queries):.3f}")

Ties are scored as their expected value under random tie-breaking, so a chunk tied with 59 others counts as a 5-in-60 chance of being in the top 5. Extending the same script to recall@1, recall@20, MRR and a scikit-learn TF-IDF retriever gives:

Table 3. Measuring the effect
Corpus version BM25 R@1 BM25 R@5 BM25 R@20 BM25 MRR TF-IDF R@5
Plain chunks 0.014 0.069 0.278 0.029 0.069
Placebo header 0.008 0.029 0.070 0.036 0.033
Company-only header 0.278 0.889 1.000 0.442 0.842
Full context header 1.000 1.000 1.000 1.000 1.000
BM25 recall@5 by chunk context (360 chunks, 360 queries)
00.20.40.60.81plainplacebo headercompany onlyfull headerrecall@5 · plain: 0.0690.069recall@5 · placebo header: 0.0290.029recall@5 · company only: 0.8890.889recall@5 · full header: 11what is prepended to each chunkrecall@5
Figure 1. Computed with the rank_bm25 script in this article; synthetic corpus built to have orphaned chunks

Read the rows as a story.

Plain chunks fail as predicted. For any query there are 60 chunks with the same section template (20 companies × 3 quarters). If the retriever could only guess among them, recall@20 would be about 20 / 60 = 0.33. BM25 reached 0.278, close to that guess. Recall@1 of 0.014 is close to 1 / 60 = 0.017.

The placebo is worse than nothing. Shuffled headers add a wrong company name to each chunk, so the query's company now matches the wrong chunks. Recall@20 fell from 0.278 to 0.070. Adding tokens does not help; adding correct content does. This is the same conclusion the October 2026 paper reached on real corpora.

Partial context gives partial gains. Naming only the company narrows 60 candidates to 3 (one per quarter). Recall@1 should then be about 1 / 3 = 0.33, and BM25 reached 0.278. Recall@5 jumped to 0.889 because the right chunk is almost always among those three.

Full context solves this toy completely for BM25. That 1.000 is not a realistic number. Real documents are messier, real questions use synonyms, and a real LLM sometimes writes a vague or wrong context. Anthropic's real-world gain was a 35% to 49% cut in failures, not a perfect score. The toy is useful because it isolates the mechanism: context helps exactly when chunks are ambiguous without it.

What it costs

Contextual retrieval adds one LLM call per chunk at ingestion. Anthropic's cost estimate assumed 8,000-token documents, 800-token chunks, a 50-token instruction and 100 tokens of generated context per chunk. With caching, each document is written to the cache once and read for the other nine chunks. The cost per document is:

cost = doc × write + (n − 1) × doc × hit + n × (chunk + instruction) × input + n × context × output

where n = 8,000 / 800 = 10 chunks, and prices are per token. With Claude Haiku 5.5 prices for prompts up to 100,000 tokens ($0.10 input, $0.125 five-minute cache write, $0.01 cache hit and $0.50 output per million tokens):

  • cache write: 8,000 × $0.125 = $1,000 per million, or $0.001000;
  • cache reads: 9 × 8,000 × $0.01 = $720 per million, or $0.000720;
  • uncached input: 10 × 850 × $0.10 = $850 per million, or $0.000850;
  • output: 10 × 100 × $0.50 = $500 per million, or $0.000500.

That totals $0.00307 per 8,000-token document. A million document tokens is 125 such documents, so the one-time cost is 125 × $0.00307 = $0.384.

Table 4. What it costs
Setup (Anthropic's assumptions) Cost per million document tokens
Anthropic's 2024 published estimate $1.02
Claude Haiku 5.5, with prompt caching $0.384
Claude Haiku 5.5, batch, no caching $0.584
Claude Haiku 5.5, no caching $1.169
Claude Haiku 4.5, with prompt caching $3.838
voyage-context-4 embedding (no LLM step) $0.12

The voyage-context-4 row is only the embedding price, and it replaces your normal embedding cost rather than adding to it, so the rows are not like for like. Caching saves about two thirds against uncached calls ($0.384 against $1.169) because the document is re-read nine times per document. The prompt cache simulation shows the same effect for agent sessions.

One-time context generation cost per million document tokens
$0$1$2$3$4Haiku 5.5 cachedUSD · Haiku 5.5 cached: $0.384$0.384Haiku 5.5 batchUSD · Haiku 5.5 batch: $0.584$0.584Anthropic 2024 estimateUSD · Anthropic 2024 estimate: $1.02$1.02Haiku 5.5 uncachedUSD · Haiku 5.5 uncached: $1.17$1.17Haiku 4.5 cachedUSD · Haiku 4.5 cached: $3.84$3.84setupdollars per million document tokens
Figure 2. Computed from Claude pricing page rates and Anthropic's assumptions (8k-token documents, 800-token chunks); the 2024 figure is Anthropic's published estimate

There are two smaller costs. Each chunk grows by about 100 tokens, so an 800-token chunk becomes 900 tokens, 12.5% more to embed and store. And because the context is stored with the chunk, it also enters the generator's prompt unless you strip it out after retrieval.

Use cases and examples

Financial filings assistant. An analyst team indexes 4,000 quarterly reports of about 8,000 tokens each, 32 million tokens in total. At $0.384 per million tokens with Claude Haiku 5.5 and caching, generating contexts costs 32 × $0.384 = $12.29 once. Each quarter adds about 400 reports, or 3.2 million tokens, costing about $1.23. The team measures recall@20 on 300 analyst questions before and after.

HR policy bot with good structure. An HR handbook is written in Markdown with clear headings. Here heading paths do most of the work at no model cost: each chunk gets "Handbook > Leave > Parental leave > Eligibility" prepended. Following the October 2026 study, the team splits on section boundaries rather than fixed windows and compares against a placebo of shuffled headings to confirm the gain is real.

Support tickets with short documents. Tickets are a few hundred tokens long, so each ticket fits in one chunk and has no lost context. Contextual retrieval adds cost with nothing to fix. The team prepends only metadata (product, customer tier, date) for filtering and keyword matching.

Scanned contracts with no headings. Contracts arrive as OCR text with no reliable structure. An LLM context such as "Termination clause of the 2025 supply agreement between X and Y" restores what the scan lost. The team uses the batch API overnight, accepting the higher uncached price ($0.584 per million tokens) because latency does not matter.

What it means in practice

Context is a property of your documents, not a setting to switch on everywhere. When chunks are ambiguous without their source (reports, filings, manuals with repeated sections), adding context is one of the cheapest recall gains in RAG, measured in cents per million tokens at current small-model prices. When documents are short or chunks already name their subject, it adds cost and index size for nothing.

Start with what you already have. Titles, dates and heading paths cost nothing and help both BM25 and embeddings. Add LLM-written context where structure is missing. Consider a contextualized embedding model if you want the dense-side gain without changing your text, but remember it does nothing for keyword search. Then put a reranker on top: in Anthropic's results it took failures from 2.9% to 1.9%. For small corpora, check whether you need retrieval at all; Anthropic's post notes that a knowledge base under 200,000 tokens can go straight into the prompt, a trade-off covered in long context vs RAG.

What to do now

  1. Find your orphaned chunks. Sample 100 chunks and count how many fail to name their subject, time or section. If few do, stop here.
  2. Prepend metadata first. Add title, date and heading path to every chunk before embedding and before BM25 indexing.
  3. Split on structure where it exists. Align chunks with sections instead of fixed windows; the October 2026 study found this beats contextualized fixed windows.
  4. Generate LLM context where structure is missing. Use a small model, cache the document, and cap the output at about 100 tokens.
  5. Index the context in both legs. Put the contextualized text into BM25 and the embedding index; Anthropic's best result used both.
  6. Run a placebo check. Shuffle contexts across documents and confirm recall drops; if it does not, your gain came from extra tokens, not content.
  7. Re-run context generation on updates. A chunk's context depends on its whole document, so regenerate it when the document changes.
  8. Measure before and after. Report recall@20 and MRR on a fixed question set, as in the RAG evaluation guide.

Risks and open questions

The model can write wrong context. An LLM that misreads a document attaches a wrong company or date to a chunk, which our placebo test shows is worse than no context at all. Spot-check contexts, especially for long or messy documents.

Gains vary by corpus. The October 2026 study found effect sizes that were consistent but small (dz 0.06 to 0.11), and gold structure beat LLM-induced structure on Wikipedia but not on QASPER.

Ingestion gets slower and more complex. One model call per chunk adds latency, rate limits and failure handling to the pipeline. Batch processing helps cost but not freshness.

Vendor comparisons are vendor-run. The voyage-context-3 and voyage-context-4 margins come from MongoDB's own evaluation. Test on your data before switching.

Watch next: independent benchmarks of contextualized embedding models against LLM-written context, whether more vector stores generate chunk context during ingestion, and follow-up work on why naive hierarchical retrieval loses section recall.

Frequently asked questions

What is contextual retrieval in one sentence?

It is the practice of prepending a short, document-aware description to each chunk before embedding and keyword indexing it. Anthropic introduced the name in September 2024 and reported a 35% to 49% cut in top-20 retrieval failures, or 67% with reranking.

Is contextual retrieval the same as late chunking?

No. Contextual retrieval adds visible text to each chunk, so it helps BM25 as well as embeddings. Late chunking changes only the vectors, by pooling token embeddings computed over the whole document.

How much does it cost to add LLM context to chunks?

With Anthropic's assumptions and Claude Haiku 5.5 prices with prompt caching, our calculation gives about $0.38 per million document tokens, once. Without caching it is about $1.17, and Anthropic's own 2024 estimate was $1.02.

Do I need an LLM, or are headings enough?

Often headings are enough. A 2026 placebo-controlled study found that structure-aligned chunks with real heading paths beat LLM-contextualized fixed windows on two corpora. Use an LLM where documents lack reliable structure.

Should the added context be shown to the generator?

It can be, because it helps the model understand where each passage came from. If prompt length is tight, store the context in a separate field and send only the original chunk text to the generator.

Summary

Chunks often lose the company, date or section that made them findable, and both BM25 and embeddings then rank them among dozens of look-alikes. Contextual retrieval restores that information before indexing, through LLM-written context, heading paths, late chunking or contextualized embedding models such as voyage-context-4. Anthropic measured a 35% to 49% cut in retrieval failures, and a 2026 placebo study confirmed that correct content, not extra tokens, drives the gain; our toy BM25 test showed the same pattern, with shuffled headers cutting recall@20 from 0.278 to 0.070. At Claude Haiku 5.5 prices with caching, generating context costs about $0.38 per million document tokens. Use metadata first, add LLM context where structure is missing, and measure with a placebo check.

Sources

Cite this article

Kelahmet, Ö. C. (2026, November 25). Contextual retrieval explained: give every chunk its missing context before you index it. Özer Cem KELAHMET. https://www.ozercemkelahmet.com/articles/contextual-retrieval-chunk-context-headers

BibTeX
@online{kelahmet2026contextual,
  author = {Kelahmet, {\"O}zer Cem},
  title  = {{Contextual retrieval explained: give every chunk its missing context before you index it}},
  year   = {2026},
  month  = {nov},
  url    = {https://www.ozercemkelahmet.com/articles/contextual-retrieval-chunk-context-headers}
}
Version historyfirst version
  1. Published

Factual corrections are listed here with what changed. Wording and formatting edits are not listed.

Last updated Nov 25, 2026
Type to search.
    ↑↓ navigate↵ open