Module 3 · Advanced retrieval
Parent-document, late chunking and contextual retrieval
6 min read
Chunking poses a dilemma. Small passages give precise retrieval — one vector per idea — but poor context for answering: "Casters are wear parts, under warranty for 2 years." does not say which product it is about. Large passages give good context, but a vector that mixes several topics. This lesson presents three techniques that escape the dilemma: parent-document retrieval, contextual retrieval and late chunking.
Measuring the effect of passage size
Prism splits articles into passages of a few sentences. Let us vary the size:
| Chunking | Passages | Dense R@5 | Dense multi-source | Hybrid R@5 |
|---|---|---|---|---|
| 1 sentence | 107 | 0.91 | 0.58 | 1.00 |
| 2 sentences (default) | 67 | 0.90 | 0.75 | 0.99 |
| 4 sentences | 36 | 0.91 | 0.83 | 0.99 |
| Whole article | 36 | 0.91 | 0.83 | 0.99 |
Prism's articles are short (rarely more than four sentences): beyond four sentences, the passage is the article. The clearest effect concerns multi-source questions: the very small passages of a single article share the five slots, at the expense of the second article needed. With real multi-page documents, the opposite effect also appears: a passage that is too large dilutes its vector and drops out of the ranking.
What does not change: the article title is added to each passage before embedding. It is the simplest form of context, and it is free:
def indexed_text(self) -> str:
"""Ce qui est vectorisé et indexé : le titre donne son contexte au passage."""
context = self.meta.get("context")
return f"{self.title}\n{context + chr(10) if context else ''}{self.text}"
Parent-document retrieval
The idea: search on small passages, return their parent document. Retrieval stays precise, the model receives the full context.
def expand_to_parents(hits: list[Hit], articles: list[Article], k: int = 5) -> list[Hit]:
"""Parent-document retrieval : on cherche sur de petits passages, on renvoie leurs articles."""
by_id = {a.id: a for a in articles}
parents: list[Hit] = []
for hit in hits:
if any(p.chunk.article_id == hit.chunk.article_id for p in parents):
continue # plusieurs passages d'un même article : un seul parent
...
Deduplication matters: three retrieved passages from the same article must not send the article three times to the model. The "parent" is not necessarily the whole document: for long documents, take the section containing the passage, or the passage widened by a few sentences on each side (sentence window). You then need to watch the size of the final context.
Contextual retrieval
Proposed by Anthropic, the technique has an LLM write, before indexing, one or two sentences that situate each passage within its document. That context is added to the embedded text and to the text indexed by BM25:
CONTEXT_PROMPT = """Voici un passage extrait du document ci-dessus :
<passage>
{chunk}
</passage>
Rédige une à deux phrases qui situent ce passage dans le document, pour améliorer sa recherche :
de quel produit ou de quelle règle il s'agit, et dans quel cas il s'applique.
Réponds uniquement par ces phrases."""
(The prompt asks for one or two sentences situating the passage in the document: which product or rule it concerns, and in which case it applies.) "Casters are wear parts, under warranty for 2 years." becomes "Warranty of the Axis ergonomic chair (CHAIR-7): warranty period of the casters, separate from that of the frame (5 years) and the gas lift (10 years). Casters are wear parts, under warranty for 2 years." — a passage that both dense search and BM25 can finally link to "chair", "Axis" and "warranty". In Prism, the article title already plays part of that role; in a 30-page manual titled "User guide", it is no longer enough.
The cost, and prompt caching
Contextualizing costs one LLM call per passage, and each call must contain the whole document for the model to situate it. For a 20-page document split into 80 passages, you would send the 20 pages 80 times. Prompt caching makes the technique affordable: the document is placed at the start of the message, marked for caching, and the following calls for the same document read it from the cache, at a fraction of the normal price.
for chunk in chunks:
article = by_id[chunk.article_id]
document = f"<document>\n# {article.title}\n{article.text}\n</document>"
context = llm.complete("contextualize", CONTEXT_PROMPT.format(chunk=chunk.text), fast=True,
max_tokens=150, cached_prefix=document)
content: list[dict] = []
if cached_prefix:
content.append({"type": "text", "text": cached_prefix, "cache_control": {"type": "ephemeral"}})
content.append({"type": "text", "text": prompt})
For the cache to work, process the passages document by document, in order: the cache expires after a few minutes without use.
A silent trap: a prefix shorter than the model's minimum (512 tokens for Claude Haiku 5.5 and Opus 5.5) is not cached, without any error. Prism's articles are below that threshold: they would not benefit from the cache. Always check the response's cache_creation_input_tokens and cache_read_input_tokens counters — Prism accumulates them in llm.USAGE — rather than assuming the cache works.
Late chunking
Late chunking achieves a comparable effect without an LLM. Instead of embedding each passage in isolation, you run the whole document through a long-context embedding model, then compute each passage's vector from the representations of its tokens (by averaging). Since each token has "seen" the whole document, the passage's vector carries its context.
Constraints: you need a long-context model (several thousand tokens) and access to per-token representations, which standard embedding APIs do not always expose. Prism does not implement it — the course's local model has a short context — but the principle is worth knowing: it only benefits dense search, whereas contextual retrieval also improves BM25.
| Technique | Indexing cost | Benefits | Constraint |
|---|---|---|---|
| Added title | None | Dense and lexical | None |
| Parent-document | None | The generation context | Size of the final context |
| Contextual retrieval | One LLM call per passage | Dense and lexical | Prompt caching essential |
| Late chunking | One long embedding per document | Dense | Long-context model, token access |
Key takeaways
- Small passages: precise retrieval, poor context; large passages: the opposite. Measure the size on your documents.
- The title added to each passage is free context: always do it.
- Parent-document: search on small passages, return the deduplicated parent.
- Contextual retrieval: an LLM situates each passage, for dense search and BM25; prompt caching makes it affordable, above the 512-token minimum.
- Late chunking contextualizes vectors without an LLM, but requires a long-context model.
Practice
- Rerun the test bench with
max_sentences=1, then3, and observe the multi-source questions. - With an API key, contextualize the passages of a document longer than 512 tokens and check in
llm.USAGEthat the cache is read from the second passage onwards. - Add a sentence window (the passage plus one sentence before and after) as a variant of parent-document, and compare the size of the context sent.