โ† Back to Blog
RAGAI EngineeringLLMs

Contextual Retrieval: Fix the Chunk That Lost Its Context

Naive chunking strips the context a passage needs to be found. Here's how to add contextual embeddings, hybrid search, and reranking to a RAG pipeline โ€” with runnable code and a cost/latency breakdown.

By Joinloopยท9 September 2026ยท8 min read
ShareLinkedInXReddit
๐Ÿ”ง

Your RAG system returns the wrong chunk. Not because the embedding model is bad, but because the chunk it should have returned reads like this:

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

Which company? Which quarter? The surrounding document knows. The chunk doesn't. When a user asks "how did ACME's Q3 2025 revenue compare to Q2," the embedding of that isolated sentence doesn't carry "ACME," "Q3," or "2025," so it ranks below a dozen less relevant passages that happen to mention those tokens.

This is the single most common failure mode in production RAG, and it has a well-tested fix: contextual retrieval โ€” prepend a short, LLM-generated context blurb to each chunk before you embed and index it. Anthropic's published numbers put the retrieval-failure reduction at ~35% with contextual embeddings plus contextual BM25, and up to ~49% when you add a reranker. This post shows how to build all three layers.

The problem in precise terms

A retrieval pipeline has one job: given a query, return the passages that actually answer it, ranked high enough to survive the top-k cut. It fails when:

  1. Chunks lose document context. Splitting on token count or headings severs pronouns, entities, dates, and defined terms from their referents.
  2. Dense embeddings miss exact matches. Semantic vectors are lossy. Error codes, function names, SKUs, legal clause numbers โ€” the things users paste verbatim โ€” get smeared into "nearby" concepts.
  3. Top-k is a blunt instrument. Cosine similarity ranking is good enough to get the right chunk into the top 100, rarely good enough to get it into the top 5.

Contextual retrieval addresses (1). Hybrid search addresses (2). Reranking addresses (3). You want all three; they compound.

Layer 1: Contextual chunk augmentation

Before indexing, run each chunk through a cheap LLM with the whole document (or a large window of it) in context, and ask for a 1โ€“2 sentence situating blurb. Prepend that blurb to the chunk text, then embed and index the combined string.

import anthropic

client = anthropic.Anthropic()

CONTEXT_PROMPT = """<document>
{doc}
</document>

Here is a chunk we want to situate within the whole document:
<chunk>
{chunk}
</chunk>

Give a short, standalone context (2-3 sentences, no preamble) that situates
this chunk within the document for search retrieval. Name the entities, time
periods, and topics the chunk refers to but does not spell out. Answer with
the context only."""

def contextualize(doc: str, chunk: str) -> str:
    msg = client.messages.create(
        model="claude-haiku-4-5-20251001",
        max_tokens=200,
        messages=[{
            "role": "user",
            "content": [{
                "type": "text",
                "text": CONTEXT_PROMPT.format(doc=doc, chunk=chunk),
                "cache_control": {"type": "ephemeral"},  # cache the document
            }],
        }],
    )
    return msg.content[0].text.strip()

def build_contextual_chunks(doc: str, chunks: list[str]) -> list[str]:
    out = []
    for chunk in chunks:
        ctx = contextualize(doc, chunk)
        out.append(f"{ctx}\n\n{chunk}")
    return out

Two things make this affordable at scale:

  • Prompt caching. The document is identical across every chunk in it. Mark it with cache_control and you pay the full input rate once per document, then a ~10% rate for each subsequent chunk. For a 50-chunk document that is a ~5x cost reduction on the context-generation step. (Check current cache write/read multipliers in the Anthropic docs โ€” they vary by model.)
  • A small model. Haiku-class models are fine for this. You are not asking for reasoning, just entity resolution against text that's right there.

Store the original chunk for what you feed the LLM at answer time, and the contextualized chunk for what you embed and index. The blurb is a retrieval aid, not part of the source of truth.

Layer 2: Hybrid search (dense + BM25)

Dense retrieval and lexical retrieval fail on different queries. Combine them. The standard approach is Reciprocal Rank Fusion (RRF): run both retrievers, then score each document by the sum of 1 / (k + rank) across the result lists it appears in. k is a smoothing constant, usually 60.

from rank_bm25 import BM25Okapi

# --- Index time ---
contextual_chunks = build_contextual_chunks(doc, raw_chunks)
dense_index = embed_and_upsert(contextual_chunks)          # your vector DB
bm25 = BM25Okapi([c.lower().split() for c in contextual_chunks])

# --- Query time ---
def rrf_fuse(rankings: list[list[int]], k: int = 60, top_n: int = 100) -> list[int]:
    scores: dict[int, float] = {}
    for ranking in rankings:
        for rank, doc_id in enumerate(ranking):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)[:top_n]

def hybrid_search(query: str, top_n: int = 100) -> list[int]:
    dense_ids = dense_index.query(embed(query), top_k=top_n)      # list of chunk ids
    bm25_scores = bm25.get_scores(query.lower().split())
    bm25_ids = sorted(range(len(bm25_scores)),
                      key=lambda i: bm25_scores[i], reverse=True)[:top_n]
    return rrf_fuse([dense_ids, bm25_ids], top_n=top_n)

Note that BM25 runs over the contextualized chunks too โ€” Anthropic calls this "contextual BM25," and it matters because the blurb injects the entity and date tokens that the raw chunk was missing, which is exactly what lexical search keys on. Many managed vector DBs (Weaviate, Qdrant, Pinecone, pgvector + paradedb/pg_search) now do hybrid + RRF server-side; use that if you have it rather than hand-rolling BM25.

Layer 3: Reranking

Fusion gives you ~100 plausible candidates. A cross-encoder reranker reads the query and each candidate together (not as separate vectors) and scores true relevance. It's slower per pair, which is why you only run it on the shortlist, and it's the single biggest quality jump after contextualization.

import cohere

co = cohere.ClientV2()

def rerank(query: str, candidate_ids: list[int], chunks: list[str],
           top_k: int = 8) -> list[int]:
    docs = [chunks[i] for i in candidate_ids]
    res = co.rerank(model="rerank-v3.5", query=query, documents=docs, top_n=top_k)
    return [candidate_ids[r.index] for r in res.results]

def retrieve(query: str) -> list[str]:
    fused = hybrid_search(query, top_n=100)
    top = rerank(query, fused, contextual_chunks, top_k=8)
    return [raw_chunks[i] for i in top]   # feed ORIGINAL text to the generator

Open-weight alternatives (BAAI/bge-reranker-v2-m3, mixedbread-ai/mxbai-rerank-large-v1) run locally on a GPU if you can't send text to an API. Budget 50โ€“200ms for 100 candidates depending on model and hardware.

Putting the pipeline together

Stage Purpose Model class When it runs Rough cost
Chunking Split into 300โ€“500 token units, 10โ€“15% overlap none index free
Contextualization Add situating blurb per chunk Haiku-class LLM + prompt caching index ~$1โ€“2 per 1M doc tokens with caching
Dense embedding Semantic recall embedding model index + query cheap
BM25 Exact-match recall none index + query free
RRF fusion Merge rankings none query negligible
Reranking Precision on the shortlist cross-encoder query ~$1โ€“2 per 1K queries (100 docs each)

Query-time latency adds up to roughly: embedding (~20ms) + hybrid search (~30โ€“80ms) + rerank (~50โ€“200ms) = under 300ms before generation, which is acceptable for most chat UX.

Common pitfalls

  • Embedding the blurb but retrieving the blurb. Feed the original chunk to the generator. The context blurb is LLM-written and can hallucinate; keep it out of the answer path.
  • Skipping evaluation. Build a set of 50โ€“100 real query/relevant-chunk pairs before you touch the pipeline. Measure recall@20 and recall@5 (or nDCG) at every layer. If a layer doesn't move the number on your data, cut it. In 2026 the norm is systematic eval from day one โ€” don't ship on vibes.
  • Reranking too few candidates. If fusion only hands the reranker 20 candidates, the right chunk may already be gone. Rerank 75โ€“150.
  • Over-chunking. Sub-200-token chunks fragment ideas and inflate your contextualization bill. Sub-500 with light overlap is the sweet spot for most prose.
  • Contextualizing tiny corpora. Under a few hundred chunks, just put more text in the context window directly, or use a long-context model. Contextual retrieval earns its complexity at 10k+ chunks.
  • Stale context after edits. If source documents change, re-run contextualization for the affected chunks. The blurb references document-level facts that may have shifted.

Next steps

  1. Instrument your current pipeline: log query, retrieved chunk ids, and whether the answer was grounded. You can't improve what you don't measure.
  2. Build the eval set. 50 pairs is enough to start.
  3. Add reranking first โ€” it's one API call and usually the biggest single jump.
  4. Add contextualization second, with prompt caching on from the start.
  5. Add BM25 + RRF third if exact-match queries (codes, names, IDs) are common in your traffic.
  6. Re-measure after each. Keep only the layers that pay for themselves.

If you're building retrieval systems and want to go deep on evals, chunking strategy, and agentic RAG with people who've shipped this in production, that's the core of what we cover in the Joinloop AI engineering cohort.

Sources: RAG Techniques Compared (2026), RAG Is Not Dead: Advanced Retrieval Patterns (2026), Understanding Contextual Retrieval in RAG โ€” Towards Data Science, All you need to know about RAG in 2026

ShareLinkedInXReddit

Want to build this yourself?

Join a live cohort and go from reading about AI to shipping it, with practitioners who do it daily.