Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 23. Advanced RAG
  4. 23.5

Lesson 23.5 · 5 of 7 · 4 min read · Reviewed 24 Nov 2026

Contextual retrieval

By the end, you can

  • Explain contextual retrieval.
  • Add context to chunks before indexing.

Anthropic described this technique in its Contextual RetrievalContextual retrieval: Adding a short, document-aware context sentence to each chunk before embedding and indexing it. write-up.

The problem

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

Which company? Which quarter? Embedded alone, this chunkChunking: Splitting documents into smaller passages before embedding and indexing them. won’t match “ACME Q2 2025 revenue growth”.

The fix

Before indexing, ask a model to write a short context for each chunk, given the whole document:

<document> ...full filing... </document>
Here is a chunk from it: <chunk> ... </chunk>
Write 1 to 2 sentences situating this chunk within the document, to improve search retrieval.

-> "This chunk is from ACME Corp's Q2 2025 filing, discussing quarterly revenue
    compared with Q1 2025."

Prepend that context to the chunk, then build both the embeddingEmbedding: A list of numbers (a vector) that represents the meaning of a piece of text, so similar meanings land close together. index and the BM25BM25: A classic keyword ranking function that scores documents by term frequency and rarity. index from the result.

Keeping cost down

Every chunk in a document needs the same full document in its prompt. With prompt cachingPrompt caching: Reusing the processed form of a repeated prompt prefix across requests, which cuts cost and latency., the document is cached after the first chunk, so later chunks reuse it at a much lower input price (70.1).

Results

The write-up reports that contextual embeddings plus contextual BM25 reduced retrieval failures substantially, and adding rerankingReranking: Re-scoring an initial set of retrieved results with a more accurate model to put the best ones first. reduced them further. Your gains depend on your documents; measure with your own test set (chapter 26).

Key points

  • A chunk on its own often lacks context: 'Revenue grew 3%' — which company, which quarter?
  • Contextual retrieval adds a short, generated description of where the chunk sits in its document before embedding and keyword indexing.
  • Prompt caching keeps the cost of generating that context low, since the whole document is reused for every chunk.
Hands-on labRuns in the Playground

Add context to chunks before indexing

Prepend a short document-level context to each chunk and measure how far it moves the right chunk up the ranking.

You will have: A contextualise() function, the chunk's rank before and after, and a cost estimate with and without prompt caching.

Steps

  1. Read the two filings: each has chunks that never name the company or quarter.
  2. Write contextualise(): prepend 'From <company>'s <quarter> filing, <section>:' to each chunk (standing in for a model-written context).
  3. Rank all chunks for 'ACME Q2 2025 revenue growth' before and after.
  4. Estimate input tokens for generating context for 20 chunks of one 8,000-token report, with and without caching (cached reads at a tenth).

Done when

  • The ACME revenue chunk moves to rank 1 after contextualising.
  • Caching cuts the context-generation input by more than 5x in the estimate.

Open in the Playground No API key needed.

Starter code (Python)
import math, re
from collections import Counter

STOP = {"a", "an", "the", "to", "of", "and", "or", "is", "are", "be", "in", "on", "for", "if", "it", "by", "you", "your", "may", "can", "do", "i", "what", "has", "have", "not", "into", "up", "this", "that", "with", "from", "over"}

def words(text):
    out = []
    for w in re.findall(r"[a-z0-9]+", text.lower()):
        if w in STOP:
            continue
        out.append(w[:-1] if w.endswith("s") and len(w) > 3 else w)
    return out

def embed(text):
    """A toy embedding: content-word counts. Real systems use an embedding model."""
    return Counter(words(text))

def cosine(a, b):
    dot = sum(a[k] * b[k] for k in a)
    na = math.sqrt(sum(v * v for v in a.values())); nb = math.sqrt(sum(v * v for v in b.values()))
    return dot / (na * nb) if na and nb else 0.0

def rank_of(target, query_vec, docs):
    order = sorted(docs, key=lambda d: -cosine(query_vec, embed(docs[d])))
    return order.index(target) + 1

FILINGS = [
    {"company": "ACME Corp", "quarter": "Q2 2025", "chunks": {
        "acme-rev": ("Revenue", "The company's revenue grew by 3% over the previous quarter."),
        "acme-cost": ("Costs", "Margins narrowed as costs rose."),
    }},
    {"company": "Beta Ltd", "quarter": "Q2 2025", "chunks": {
        "beta-rev": ("Revenue", "Sales fell 2% over the previous quarter."),
        "beta-q2": ("Outlook", "Growth guidance for next year was cut."),
    }},
]
QUERY = "ACME Q2 2025 revenue growth"

def plain(filings):
    return {cid: text for f in filings for cid, (sec, text) in f["chunks"].items()}

def contextualise(filings):
    # TODO: return {cid: "From <company>'s <quarter> filing, <section>: <text>"}
    return plain(filings)

print("rank before:", rank_of("acme-rev", embed(QUERY), plain(FILINGS)))
print("rank after: ", rank_of("acme-rev", embed(QUERY), contextualise(FILINGS)))
# TODO: cost estimate for 20 chunks of an 8,000-token report, with and without caching
Show a solution
import math, re
from collections import Counter

STOP = {"a", "an", "the", "to", "of", "and", "or", "is", "are", "be", "in", "on", "for", "if", "it", "by", "you", "your", "may", "can", "do", "i", "what", "has", "have", "not", "into", "up", "this", "that", "with", "from", "over"}

def words(text):
    out = []
    for w in re.findall(r"[a-z0-9]+", text.lower()):
        if w in STOP:
            continue
        out.append(w[:-1] if w.endswith("s") and len(w) > 3 else w)
    return out

def embed(text):
    """A toy embedding: content-word counts. Real systems use an embedding model."""
    return Counter(words(text))

def cosine(a, b):
    dot = sum(a[k] * b[k] for k in a)
    na = math.sqrt(sum(v * v for v in a.values())); nb = math.sqrt(sum(v * v for v in b.values()))
    return dot / (na * nb) if na and nb else 0.0

def rank_of(target, query_vec, docs):
    order = sorted(docs, key=lambda d: -cosine(query_vec, embed(docs[d])))
    return order.index(target) + 1

FILINGS = [
    {"company": "ACME Corp", "quarter": "Q2 2025", "chunks": {
        "acme-rev": ("Revenue", "The company's revenue grew by 3% over the previous quarter."),
        "acme-cost": ("Costs", "Margins narrowed as costs rose."),
    }},
    {"company": "Beta Ltd", "quarter": "Q2 2025", "chunks": {
        "beta-rev": ("Revenue", "Sales fell 2% over the previous quarter."),
        "beta-q2": ("Outlook", "Growth guidance for next year was cut."),
    }},
]
QUERY = "ACME Q2 2025 revenue growth"

def plain(filings):
    return {cid: text for f in filings for cid, (sec, text) in f["chunks"].items()}

def contextualise(filings):
    return {cid: f"From {f['company']}'s {f['quarter']} filing, {sec}: {text}"
            for f in filings for cid, (sec, text) in f["chunks"].items()}

before = rank_of("acme-rev", embed(QUERY), plain(FILINGS))
after = rank_of("acme-rev", embed(QUERY), contextualise(FILINGS))
print(f"acme-rev rank before: {before}, after: {after}")

DOC_TOKENS, CHUNKS, CACHED_RATE = 8000, 20, 0.1   # illustrative
no_cache = DOC_TOKENS * CHUNKS
with_cache = DOC_TOKENS + DOC_TOKENS * CACHED_RATE * (CHUNKS - 1)
print(f"context generation input: {no_cache:,} without caching, {with_cache:,.0f} with caching ({no_cache / with_cache:.1f}x less)")
Quick checkWhat does contextual retrieval add to each chunk before indexing?
How sure are you?
Pick an answer and how sure you are