---
agent:
  instructions: "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://mixpeek.com/.well-known/search?q={query}"
  method: GET
  documentation: "https://mixpeek.com/llms.txt"
---

Retrieval

18 min read

Updated 2026-06-17

# Chunk Contextualization: How Late Chunking and Contextual Retrieval Fix Broken RAG

A technical guide to the chunking problem that silently breaks document retrieval for AI agents. Learn why naive chunking strips context, how late chunking pools token embeddings after a long-context forward pass, how Anthropic's contextual retrieval prepends LLM-generated context, the math and tradeoffs of each, and how to apply the pattern in Mixpeek.

![Ethan Steininger](/people/ethan.webp)

By [Ethan Steininger](/blog/authors/ethan), Founder & CEO, Mixpeek

Late Chunking

Contextual Retrieval

RAG

Chunking

Document Understanding

Retrieval

[Run this on your own data. Try it as you read.Search your own archive →](https://studio.mixpeek.com/namespaces/create?mode=managed&utm_source=homepage&utm_medium=guide_cta&utm_campaign=mvs_onramp)

[One-click templatesStart from a templateEach template deploys a working search app on your own files.Browse templates](/templates)

## The Problem: A Chunk Without Context Is Unsearchable

  
  
Almost every document RAG system splits long text into chunks, embeds each chunk independently, and stores the vectors. This is the default, and it has a quiet failure mode that an AI agent feels every day: a chunk torn out of its document loses the context that made it findable.  
  
Consider a chunk that reads:  
  
\> "He refused the offer, and the board accepted his resignation the following week."  
  
Who is "he"? What offer? The answer lives three paragraphs earlier: "the CEO, Maria Chen, was presented with a buyout proposal." Embedded on its own, this chunk has no signal connecting it to "Maria Chen" or "buyout." An agent asking "what happened with the CEO's buyout?" will rank this chunk low, even though it is the exact passage that answers the question.  
  
This is not an edge case. Pronouns, acronyms defined once, section headings that scope everything below them, tables whose meaning lives in a caption, transcript turns that only make sense given the previous speaker: all of these break under naive chunking. The retrieval failure is invisible: the system returns \*something\*, just not the right thing, and the agent confidently reasons over the wrong evidence.  
  
Two techniques fix this without making chunks huge (which over-compresses semantics and hurts precision): **late chunking** and **contextual retrieval**. They attack the same root cause from opposite directions.  
  

## Why Not Just Use Bigger Chunks?

  
  
The naive instinct is to make chunks larger so each one carries more context. This trades one problem for another. Dense embedding models compress an entire chunk into a single fixed-size vector. The more text you stuff into one chunk, the more distinct ideas get averaged into one point in vector space, and the embedding drifts toward a bland centroid that matches everything weakly and nothing strongly.  
  
So you are caught between two failures:  
  
*   **Small chunks**: sharp, specific embeddings, but each one is missing surrounding context.
*   **Large chunks**: full of context, but semantically over-compressed and imprecise.
  
  
Both late chunking and contextual retrieval let you keep chunks small \*and\* contextual.  
  

## Technique 1: Late Chunking

  
  
Late chunking, introduced by Jina AI in 2024, comes from a simple observation about \*when\* you split. Naive chunking splits the text first, then embeds each piece. Late chunking embeds first, then splits.  
  

### The Algorithm

  
  
A long-context embedding model (8K+ tokens) is a transformer whose attention lets every token see every other token. Late chunking exploits this:  
  
1\. **Concatenate** the chunks (or take the whole document) as one sequence. 2. **Run a single forward pass** through the long-context model. Now every token embedding has attended to the full document: the token for "he" has already absorbed information from "Maria Chen" three paragraphs back. 3. **Mark chunk boundaries** over the token sequence (by sentence, fixed size, or semantic split). 4. **Mean-pool within each chunk's token span** to produce one vector per chunk.  
  
The difference is entirely in the pooling boundary. Naive chunking pools \*before\* the chunks have seen each other; late chunking pools \*after\*.

Naive chunking:
  split --&gt; \[chunk A\]\[chunk B\]\[chunk C\]
  embed each independently (no cross-chunk attention)
  pool --&gt; vec(A), vec(B), vec(C)

Late chunking:
  concatenate --&gt; \[chunk A | chunk B | chunk C\]
  ONE forward pass with full attention across A,B,C
  token embeddings: t1 t2 t3 ... tN   (each conditioned on all others)
  pool within boundaries --&gt; vec(A) from t1..ti
                             vec(B) from ti+1..tj
                             vec(C) from tj+1..tN

### Pseudocode

def late\_chunk(document, model, chunk\_spans):
    # 1. ONE forward pass over the whole document
    token\_embeddings = model.encode\_tokens(document)  # shape: \[num\_tokens, dim\]

    # 2. Mean-pool within each chunk's token range
    chunk\_vectors = \[\]
    for (start, end) in chunk\_spans:          # spans are token indices
        span = token\_embeddings\[start:end\]    # tokens already saw full doc
        chunk\_vectors.append(span.mean(axis=0))
    return chunk\_vectors

### Why It Works

  
  
The contextual signal is injected by attention, for free, at encode time. No extra model calls, no extra storage: you still store one vector per chunk. The chunk for "He refused the offer..." now carries a trace of "Maria Chen" and "buyout" because those tokens were in the attention window during the single forward pass.  
  
The cost is that you need a genuine long-context embedding model and enough context budget to fit the relevant span. For documents longer than the model's window, you process overlapping macro-windows and pool within each.  
  

### What the Numbers Say

  
  
In Jina's evaluation across three models and four retrieval datasets, late chunking delivered a consistent **~2-4% relative nDCG improvement** over naive chunking (sentence, fixed-size, and semantic boundaries alike) with zero additional training. The gains concentrate exactly where you expect: chunks that are ambiguous on their own.  
  

## Technique 2: Contextual Retrieval

  
  
Anthropic's contextual retrieval (2024) attacks the same problem with an LLM instead of attention. Instead of relying on the embedding model to propagate context, it \*writes the context into the chunk text\* before embedding.  
  

### The Algorithm

  
  
For each chunk, call an LLM with the whole document and that chunk, and ask it to produce a short situating description. Prepend that description to the chunk, then embed and index the augmented chunk.

For each chunk:
  context = LLM("Given this document: {doc}
                 Write 1-2 sentences situating this chunk: {chunk}")
  augmented\_chunk = context + "\\n\\n" + chunk
  index(embed(augmented\_chunk))          # dense vector
  index(bm25(augmented\_chunk))           # sparse / keyword

A generated context might read: \*"This chunk is from the Q3 board minutes describing CEO Maria Chen's response to the buyout proposal."\* Now both the dense embedding and the keyword index contain "Maria Chen" and "buyout": the chunk is findable by either path.  
  

### The Full Pipeline

  
  
Anthropic's published pipeline stacks three reinforcing steps, each adding measurable lift to retrieval recall:  
  
*   **Contextual embeddings** (the prefix above) reduced the retrieval-failure rate by **35%**.
*   Adding a **contextual BM25** index over the same augmented chunks pushed the reduction to **49%**: sparse keyword matching catches exact terms, names, and codes that dense vectors blur.
*   Adding a **reranker** on top reached **67%**.
  
  
The lesson generalizes beyond this one technique: contextualization, hybrid dense+sparse retrieval, and reranking are complementary, not redundant.  
  

### The Tradeoff

  
  
Contextual retrieval is more expensive than late chunking: you make one LLM call per chunk at index time. Prompt caching makes this affordable (you cache the document once and vary only the chunk), but it is still real cost and latency at ingestion. In exchange you get a human-readable, hybrid-searchable chunk that does not depend on a long-context embedding model, and the context is explicit rather than implicit in the vector.  
  

## Choosing Between Them

  
  

Dimension

Naive chunking

Late chunking

Contextual retrieval

Where context comes from

nowhere

attention (single forward pass)

LLM-generated text prefix

Index-time cost

lowest

one long-context encode

one LLM call per chunk

Needs long-context encoder

no

yes

no

Works with BM25 / keyword

poorly

poorly

yes (text is augmented)

Storage

1 vector/chunk

1 vector/chunk

1 vector/chunk (+ longer text)

Best when

short, self-contained docs

long docs, latency-sensitive ingest

names/codes/entities matter, hybrid search

  
  
In practice they are not mutually exclusive. A strong document pipeline often does late chunking for cheap baseline context, then layers hybrid dense+sparse retrieval and a reranker, borrowing the structural lesson from contextual retrieval even when you skip the per-chunk LLM call.  
  

## This Applies to More Than Text

  
  
The same failure mode appears in every modality an agent perceives:  
  
*   **ASR transcripts.** A transcript turn ("yeah, do that one") is meaningless without the previous turns. Contextualizing each segment with the dialogue around it makes spoken-content search work.
*   **OCR'd documents.** A scanned table cell needs its column header and caption to be retrievable.
*   **Long video.** A scene description needs the preceding scenes to disambiguate "the same building" or "he leaves."
  
  
Whenever you decompose continuous content into searchable pieces, ask: does each piece still carry the context that makes it findable? If not, you need one of these techniques.  
  

## Doing This in Mixpeek

  
  
Mixpeek ingests documents into collections through feature extractors, and the chunking + embedding strategy is part of the collection's extraction config: so you decide the contextualization policy once, at the collection level, and every document inherits it. Retrievers then search those chunk vectors, and Mixpeek's hybrid retriever fuses dense and BM25 stages, which is exactly the dense+sparse pattern contextual retrieval relies on.

from mixpeek import Mixpeek

client = Mixpeek(api\_key="YOUR\_API\_KEY", namespace="board-docs")

# A document collection whose chunks carry enough surrounding text to stand
# alone, embedded with E5 and searchable by keyword as well.
collection = client.collections.create(
    collection\_name="board-minutes",
    source={"type": "bucket", "bucket\_ids": \["bkt\_board\_minutes"\]},
    feature\_extractor={
        "feature\_extractor\_name": "text\_extractor",
        "version": "v1",
        "parameters": {
            "split\_by": "words",
            "chunk\_size": 380,     # counted in words: about 500 E5 tokens, under its 512 limit
            "chunk\_overlap": 60,
        },
    },
)

# Hybrid retriever: dense chunk vectors plus BM25 over the same chunk text,
# fused with RRF. BM25 reads the namespace's text payload indexes.
retriever = client.retrievers.create(
    retriever\_name="board-minutes-hybrid",
    collection\_identifiers=\["board-minutes"\],
    input\_schema={"query": {"type": "text", "required": True}},
    stages=\[
        {
            "stage\_name": "dense\_and\_bm25",
            "stage\_id": "feature\_search",
            "parameters": {
                "searches": \[
                    {
                        "feature\_uri": "mixpeek://text\_extractor@v1/multilingual\_e5\_large\_instruct\_v1",
                        "query": {"input\_mode": "text", "value": "{{INPUT.query}}"},
                        "top\_k": 50,
                        "min\_score": 0.4,
                    },
                    {
                        "feature\_uri": "mixpeek://text\_extractor@v1/multilingual\_e5\_large\_instruct\_v1",
                        "query": {"input\_mode": "text", "value": "{{INPUT.query}}"},
                        "top\_k": 50,
                        "lexical": True,
                    },
                \],
                "fusion": "rrf",
                "final\_top\_k": 10,
            },
        }
    \],
)

# The agent's query now lands on the chunk that carries its context.
results = client.retrievers.execute(
    retriever\["retriever\_id"\],
    inputs={"query": "what happened with the CEO's buyout?"},
)

If you need explicit, LLM-generated context per chunk (the Anthropic-style prefix), do that contextualization in your ingestion code before upload, and store the augmented text on the document: the dense and keyword stages above will then both benefit. Keep the chunking and embedding choices versioned with the collection: changing the chunk strategy or embedding model changes what is findable, so treat it like a migration, not a tweak.  
  

## Further Reading

  
  
*   [Multimodal Chunking Strategies](/guides/multimodal-chunking-strategies) -- how to decompose video, audio, images, and documents before embedding
*   [Late Interaction Retrieval](/guides/late-interaction-retrieval) -- keeping per-token detail instead of pooling at all
*   [Multi-Stage Retrieval](/guides/multi-stage-retrieval-how-agents-search-unstructured-data) -- combining dense, sparse, and rerank stages
*   [How to Build a Multimodal RAG Pipeline](/guides/multimodal-rag-pipeline-architecture) -- where chunking fits in the full pipeline
*   [Structured Extraction from Unstructured Documents](/guides/structured-extraction-from-unstructured-documents) -- the complementary extraction path
*   [Calibrating Similarity Scores](/guides/calibrating-similarity-scores) -- making the retriever's scores mean something
*   [Models](/models) -- browse long-context text and [multimodal embedding models](/curated-lists/best-multimodal-embedding-models)

## Run this on your own data

Point Mixpeek at the storage you already have and search your video, images, audio, and documents the way this guide describes. Build starts at $25/mo for up to 1M vectors.

[Search your own archive](https://studio.mixpeek.com/namespaces/create?mode=managed&utm_source=homepage&utm_medium=guide_cta&utm_campaign=mvs_onramp)[Read Docs](/docs)

[Explore MVS](/mvs)[See pricing](/pricing)

## Related guides

[

Retrieval

### Should a RAG Pipeline Use a Classification Model or an LLM to Filter and Rerank Results?

Use a classification model for any filter or rerank step whose answer is a choice from a list: keep or drop, a label, a relevance score. Keep a generative LLM for steps that write new text. This compares cross-encoder rerankers, decision models such as Jev and Liquid AI d1, and LLM judges on cost, speed and how far you can trust each score.

Read guide →](/guides/decision-models-in-retrieval-pipelines)[

Retrieval

### Why Does My Docs Chatbot Return Half a Code Example?

Your docs assistant answers with a code sample that stops mid-function, or cannot say which API it belongs to. The page was chunked by length and the cut landed inside the code block. We measured how often common splitters do this on 1,539 code blocks from Mixpeek's own documentation, and how to keep every block whole.

Read guide →](/guides/why-does-my-docs-chatbot-return-half-a-code-example)[

Retrieval

### Why Does My Podcast Search Find the Right Episode but Not the Moment?

Your search returns the correct episode and you still have to scrub forty minutes to find where the guest actually said it. That is almost never a transcription problem. It is what the retrieval unit is, and this is how to tell whether you are searching episodes or moments.

Read guide →](/guides/why-does-my-podcast-search-find-the-right-episode-but-not-the-moment)