DEV Community

Cover image for Your RAG chunks forgot where they came from: add context before you embed them (Contextual Retrieval)
M.T.Ramkrushna
M.T.Ramkrushna

Posted on

Your RAG chunks forgot where they came from: add context before you embed them (Contextual Retrieval)

Monday AI Insight. One practical RAG lesson: a chunk that makes sense inside its document can be useless on its own. Before you embed it, tell it where it came from.

The problem: chunking strips context

Most RAG pipelines split documents into chunks of a few hundred tokens, embed each chunk, and (if you are doing hybrid search) index the same chunks with BM25. Each chunk is now searched alone.

Anthropic's example from their Contextual Retrieval post: a user asks "What was the revenue growth for ACME Corp in Q2 2023?" The right chunk in an SEC filing says:

"The company's revenue grew by 3% over the previous quarter."

Which company? Which quarter? The chunk doesn't say. The document header did, but chunking cut it off. The embedding has no "ACME" in it and BM25 has no "ACME" or "Q2 2023" to match. So the right chunk can lose to a chunk that merely mentions ACME.

The fix: prepend a short, chunk-specific context

Contextual Retrieval (Anthropic, Sep 19, 2024) is a preprocessing step. For every chunk, ask an LLM to write a short description that situates the chunk in its full document, then prepend that text to the chunk before you embed it (Contextual Embeddings) and before you build the BM25 index (Contextual BM25).

The prompt Anthropic published is roughly:

<document>
{{WHOLE_DOCUMENT}}
</document>
Here is the chunk we want to situate within the whole document
<chunk>
{{CHUNK_CONTENT}}
</chunk>
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.
Enter fullscreen mode Exit fullscreen mode

The generated context is usually 50-100 tokens. The ACME chunk becomes something like "This chunk is from an SEC filing on ACME corp's performance in Q2 2023; the previous quarter's revenue was $314 million. The company's revenue grew by 3% over the previous quarter."

A minimal version of the pipeline:

def contextualize(doc_text: str, chunk: str) -> str:
    context = llm(CONTEXT_PROMPT.format(doc=doc_text, chunk=chunk))  # short, 50-100 tokens
    return f"{context.strip()}\n\n{chunk}"

for doc in docs:
    for chunk in split(doc.text):
        text = contextualize(doc.text, chunk)
        vector_index.add(embed(text), payload={"chunk": chunk, "doc_id": doc.id})
        bm25_index.add(text, doc_id=doc.id)
Enter fullscreen mode Exit fullscreen mode

Two details worth copying: store the original chunk as the payload you show the model (or keep both), and use the same contextualized text for both the embedding and BM25 so the two retrievers agree on what a chunk is about.

What it bought them

Anthropic measured 1 minus recall@20 (the share of relevant chunks that did not make the top 20), averaged across codebases, fiction, ArXiv papers and science papers, with their best embedding setup (Gemini Text 004):

  • Contextual Embeddings: retrieval failure rate down 35% (5.7% → 3.7%)
  • Contextual Embeddings + Contextual BM25: down 49% (5.7% → 2.9%)
  • + reranking: down 67% (5.7% → 1.9%)

Their summary: embeddings + BM25 beats embeddings alone, adding context helps a lot, reranking helps more, and the benefits stack.

What it costs

You call an LLM once per chunk at indexing time, and every call includes the whole document. That sounds expensive, and it would be without caching. With prompt caching you load the document once and reuse it for every chunk of that document. Anthropic's estimate, assuming 800-token chunks, 8k-token documents, 50 tokens of instructions and 100 tokens of context per chunk: about $1.02 per million document tokens, one time.

It is a one-time indexing cost, not a per-query cost. Query latency doesn't change (unless you also add a reranker).

When to use it (and when not)

  • Use it when chunks lean on context they don't carry: filings, contracts, policies, long reports, code files where a function only makes sense with its module, anything with "the company", "this section" or "the above".
  • Skip RAG entirely if the whole knowledge base fits in the prompt. Anthropic's own note: under about 200,000 tokens (about 500 pages), just put it all in the prompt with prompt caching.
  • Tune the prompt for your domain. Anthropic suggests custom contextualizer prompts, for example adding a glossary of terms that are only defined in other documents.
  • Re-index when the doc changes. The context is derived from the full document, so editing one section can make other chunks' context stale.
  • Measure it. Run recall@k on your own question set before and after. Don't assume the 35-67% transfers to your data.

Checklist

  1. Build a small eval set of real questions with the chunk(s) that answer them.
  2. Measure recall@20 with your current pipeline.
  3. Add a contextualize step at ingestion (with prompt caching per document).
  4. Embed and BM25-index the contextualized text; keep the original chunk as payload.
  5. Re-measure. Then try adding a reranker and measure again.

Takeaway: your retriever only sees the chunk. If the chunk doesn't say what it's about, write that down for it before you embed it.

Have you tried contextual chunks in production? Did the gain hold on your data?

References

Top comments (9)

Collapse
 
iictp profile image
IICTP •

The re-index note is the part I'd want to hear more about — since the context is derived from the full document, editing one section can quietly stale the context of every other chunk, so the re-index unit becomes the document, not the chunk. How are you handling that in practice — full-document re-index on any edit, or a check for which chunks' context actually shifted?

Collapse
 
m_t_ramkrushna profile image
M.T.Ramkrushna •

Right now I'd do a full-document re-index on any edit, since that's the safe default. The cheaper option is to diff the regenerated context per chunk and re-embed only the ones whose context text changed, so you skip most vector writes.

Collapse
 
iictp profile image
IICTP •

Thank you — the diff-the-regenerated-context idea is the part I was hoping to hear more about. Re-embedding only the chunks whose context text changed keeps the safe default's spirit without paying the full re-index on every small edit. The part I'd watch is whether the context diff itself stays cheap when the document is long — does regenerating every chunk's context on each edit end up costing more than the vector writes it saves?

Thread Thread
 
m_t_ramkrushna profile image
M.T.Ramkrushna •

Fair concern. Regenerating context is the expensive part, so I'd only regenerate for the edited section plus neighbours that reference it, and cache the document as a prompt prefix so each extra call is cheap. For long documents, a hash per section lets you skip regeneration for untouched parts, and the heading-path arm is the free fallback if cost still bites.

Collapse
 
recallrundev profile image
RecallRun •

Worth adding a free arm to the before/after: prepend the heading path, no LLM call. On the FastAPI docs with BM25, heading-aware chunks scored 0.712 hit@1; prepending Page title > Section > Subsection to the indexed text took the same chunks to 0.785 (hit@5 0.933 to 0.966). For well-structured docs that recovers part of what contextual retrieval does, at zero indexing cost and with nothing to go stale when one section is edited.

The LLM context should earn its cost where the missing fact isn't in any heading, like your ACME example, where the company and quarter only appear on the filing's cover page. So I'd run three arms on the same eval set: plain chunks, heading path, LLM context. If the last two land close, you skip the per-chunk calls and the re-index problem.

Collapse
 
m_t_ramkrushna profile image
M.T.Ramkrushna •

Good call, a heading-path arm is cheap and stays in sync when one section changes. I'll run the three arms (plain, heading path, LLM context) on one eval set and see if the last two land close enough to skip the per-chunk calls.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

How do you handle re-indexing when one section changes, since the context is derived from the whole document?

Collapse
 
m_t_ramkrushna profile image
M.T.Ramkrushna •

Short answer: the re-index unit becomes the document. I'd hash each section and, on an edit, regenerate context only for chunks in that document, reusing the cached document prompt so cost stays low. Then re-embed only chunks whose generated context text actually changed.

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

Hashing each section and re-embedding only chunks whose generated context changed is a tight loop. Reusing the cached document prompt is what keeps the cost low.