Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 33/ 160
02. RAG

Contextual Retrieval

Prepend document context to chunks before embedding so snippets stay meaningful alone.

AdvancedContext Prefix · Chunk Clarity3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Before storing each snippet, the system adds a one-line note saying what document and topic it came from, so it can be found even when the snippet alone is vague.

Think of it like…

Writing the book title, chapter and date at the top of every index card you cut out of a book. Later, a card that says "the limit is 5,000" can still be matched to a question about the Mumbai office expense policy, because the header carries the missing context.

Where you’ve seen it

An investor-relations assistant indexes thousands of filings. The chunk "The company's revenue grew by 3% over the previous quarter" is retrieved for many companies' questions. After contextual retrieval adds "This chunk is from ACME Corp's Q2 2024 filing; it discusses total revenue growth; prior quarter revenue was ₹314 crore", queries naming ACME and Q2 2024 rank it first. In Anthropic's published evaluation, the share of questions whose answer is missing from the top 20 chunks fell from 5.7 percent to about 2.9 percent with contextual embeddings plus contextual BM25, and further with reranking; your own numbers will differ, so measure on your data.

Words you’ll hear

Situating context
A short LLM-written description placing a chunk within its document.
Contextual embeddings
Embedding the context plus the chunk text rather than the chunk alone.
Contextual BM25
Indexing the same context-prefixed text in the keyword index.
Prompt caching for indexing
Reusing the cached full document in the prompt for every chunk, cutting cost.

Visual diagram

Loading interactive diagram

Theory & deep dive

How it works and what it costs

For each chunk, prompt an LLM with the whole document (or a large enough window around the chunk) and the chunk, and ask for a concise context that situates the chunk for retrieval: "Here is the document … Here is the chunk … Give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval. Answer only with the context." The output (50 to 100 tokens) is prepended; the result is embedded and also added to the BM25 index. Because the same document is sent with every chunk's prompt, prompt caching makes the repeated document tokens cheap; Anthropic estimated roughly one dollar per million document tokens to contextualise with a small model and caching, a one-off indexing cost.

Context should add what's missing, not repeat the chunk: document title and type, entity names, time period, section topic, and resolved references ("it" → "the 2025 refund policy"). Store the original chunk text separately for display and citations, and keep the context as a field so you can regenerate it when you change prompts or models.

Before and after

Before: "The limit is 5,000." After: "This chunk is from Pune office travel policy (rev. April 2026), section on daily meal allowances for domestic trips. The limit is 5,000." A query about Pune meal allowance now matches.

Key takeaway: Prepend a short, LLM-written context before embedding and BM25 indexing; cache the document to keep cost low.

Results, alternatives and pitfalls

In Anthropic's published evaluation across several datasets, contextual embeddings cut the top-20 retrieval failure rate by about 35 percent, adding contextual BM25 brought it to about 49 percent, and adding a reranker to about 67 percent. Treat these as encouraging evidence, not guarantees: gains depend on how context-poor your chunks are. Documents that are short and self-contained benefit little; long reports, filings, manuals, transcripts and code with many cross-references benefit most.

Alternatives and complements: prepend simple, free metadata (title and section path) when structure is reliable; parent-child retrieval returns larger surrounding text at answer time; late chunking and long-context embedding models embed the whole document and then pool per-chunk vectors; and fine-tuned embeddings improve matching directly. Pitfalls: the LLM may hallucinate details not in the document (verify with a sample review), very long contexts dilute the chunk's own meaning, re-indexing is needed whenever documents change, and costs scale with corpus size. Evaluate on labelled queries before and after, per document type.

A quick audit

Sample 50 contextualised chunks and check that every fact in the context appears in the document. In one pass, 3 had invented dates; tightening the prompt ("use only information in the document") removed them.

Key takeaway: Biggest gains on context-poor chunks; audit generated context and re-evaluate.

How it works, step by step

Step 1 of 4
Analysis

1. Find context-poor chunks

Review failed retrievals for chunks with pronouns, relative dates or unnamed subjects.

"the company's revenue grew 3%…"
Key numbers at this step
Signal
ambiguous alone

When to use it & trade-offs

What it is

A chunk like "Revenue grew 3% over the previous quarter" is meaningless alone: which company, which quarter? Contextual retrieval fixes this at indexing time. For each chunk, an LLM reads the whole document and writes a short situating blurb (about 50 to 100 tokens), such as "This chunk is from Acme Corp's Q2 2024 10-Q filing, in the discussion of revenue." The blurb is prepended to the chunk before embedding and before BM25 indexing, so both retrievers see the missing context. Anthropic popularised the name and reported large drops in retrieval failures on their benchmarks.

Why it matters: Chunking destroys context: pronouns, relative dates, "the policy", "this section" all lose their referents. Chunk-level retrieval then matches wrongly or misses. Adding context to the indexed text is a one-time cost per chunk that improves every future query, and it composes well with hybrid search and reranking. It's one of the most effective documented recall boosts for RAG over long, structured documents.

When to reach for it

  • Financial filings, legal documents and technical manuals
  • Transcripts and meeting notes with implicit references
  • RAG systems where failed retrievals come from ambiguous chunks

When to avoid or be careful

  • Letting generated context grow longer than the chunk
  • Skipping an audit for invented details
  • Using it on short self-contained documents where it adds cost only

Ways to keep chunks meaningful

LLM-generated chunk context
Best for: Long, cross-referencing documents (filings, manuals, transcripts)

Strengths: Resolves references; improves both dense and BM25 retrieval.

Watch out: Indexing cost; needs auditing; re-run on change.

Title and section-path prefix
Best for: Well-structured documents

Strengths: Free and deterministic.

Watch out: Doesn't resolve pronouns or relative dates.

Parent-child or sentence-window retrieval
Best for: Giving the LLM more surrounding text

Strengths: Restores context at answer time.

Watch out: Doesn't improve how the chunk matches.

Interview signals & numbers to know

When this topic comes up

  • “Retrieved chunks are out of context”
  • “The same chunk matches many companies or versions”
  • “What is contextual retrieval?”
  • Chunk ambiguity
  • Prompt caching at indexing time

Benchmarks & rules of thumb

50 – 100 tokens -
typical context length
35% / 49% / 67% -
reported failure reductions: embeddings, + BM25, + reranker (Anthropic's benchmarks)
≈ $1 / M doc tokens -
reported cost with a small model and caching

Common mistakes & follow-ups

Common interview mistakes

  • Contextualising only the embeddings and not the BM25 index, losing keyword gains.
  • Overwriting the original chunk text with the context, so citations show confusing prefixes.
  • Not re-generating context after the documents change.

Likely interviewer follow-ups

  • What problem does contextual retrieval solve?
  • How do you keep its indexing cost manageable?
  • How does it differ from parent-child retrieval?
Interview tip: Quote the before-and-after chunk ("The limit is 5,000"). A single concrete example explains the whole technique.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Contextual Retrieval with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
HyDE
Next topic
Parent-Child Chunking