What you will be able to do
- Decide whether a knowledge base needs a RAG pipeline or can go into the prompt whole
- Explain how chunk size, boundaries and overlap affect retrieval, and why a split-off chunk loses its document context
- Choose a Voyage embedding model and call it with the correct input_type for documents and for queries
- Build contextual embeddings and a contextual BM25 index from the same generated chunk context, using prompt caching to keep the cost low
Key concept
Contextual retrieval — Before indexing, Claude writes a short context for each chunk that places it within its source document. That context is prepended to the chunk before it is embedded and before it is added to the BM25 index, so both indexes can find chunks that make no sense on their own.
1.Chunk size, boundaries and the context a chunk loses
Retrieval-augmented generation (RAG) finds relevant passages in a knowledge base and adds them to the prompt. The first design question is whether you need it at all. A knowledge base under about 200,000 tokens, roughly 500 pages, can go into the prompt whole, and prompt caching keeps repeated requests fast and cheap. RAG is worth its extra moving parts once the corpus no longer fits in the context window.
Most of a RAG pipeline's work happens at ingestion. The corpus is split into chunks, usually no more than a few hundred tokens each. An embedding model turns each chunk into a vector, and a vector database stores those vectors so they can be searched by semantic similarity. At query time, the closest chunks are added to the prompt sent to Claude.
Chunk size, chunk boundary and chunk overlap are three settings you tune, and each one can change retrieval performance. Splitting on headings keeps each subsection's content together. A basic character splitter cuts wherever the character count runs out, whatever the text says at that point. Overlap belongs in the same list. Removing it to speed up indexing changes retrieval, so measure the effect like any other retrieval change.
Every chunk size has the same cost: once split off, a chunk loses the document around it. Take a set of SEC filings and the chunk 'The company's revenue grew by 3% over the previous quarter.' It answers a question about ACME Corp's revenue growth in Q2 2023, but it names neither the company nor the quarter. A query about ACME in Q2 2023 has little in that chunk to match. Even if the chunk is retrieved, Claude can't tell which company it describes.
There are two ways to put that context back. One is to write it into each chunk before indexing; this is contextual retrieval, covered below. The other is a contextualized chunk embedding model such as voyage-context-4. It produces chunk-level vectors that carry the whole document's context without you adding metadata by hand. You call it with contextualized_embed() instead of embed().
Checkpoint 1 of 6· Check yourself
Your RAG pipeline indexes an HR policy library. One chunk reads: 'Employees in this region receive 25 days of paid leave per year.' The region is only named in the document's title. The query 'How many vacation days do employees in the Netherlands get?' does not return this chunk. What is the cause, and what fixes it?
A chunk split away from its document no longer names the entity or scope it describes, so a query that names that entity has little to match. Changing chunk size doesn't help, because every chunk size has this cost. The fix is to restore the document's context, either by contextualizing each chunk or by using a contextualized chunk embedding model.
“this chunk on its own doesn't specify which company it's referring to or the relevant time period, making it difficult to retrieve the right information”Source: www.anthropic.com
2.Choosing and calling the embedding model
Anthropic doesn't make an embedding model, so this step uses a third-party provider. Claude's documentation uses Voyage AI as its example and still advises comparing several vendors. Three factors separate providers. The first is how large and how domain-relevant the model's training data is. The second is inference performance, meaning lookup speed and end-to-end latency, which matters most in large production deployments. The third is customization: whether you can keep training the model on private data so it handles an unusual vocabulary.
| Model | Call with | Context length | Pick it when |
|---|---|---|---|
| voyage-4-large | embed() | 32,000 | You want the best general-purpose and multilingual retrieval quality |
| voyage-4 | embed() | 32,000 | You want to balance quality and efficiency |
| voyage-4-lite | embed() | 32,000 | Latency and cost come first |
| voyage-code-4 | embed() | 32,000 | The corpus is code, or the use is agentic coding |
| voyage-law-2 | embed() | 16,000 | You're doing legal retrieval and RAG |
| voyage-finance-2 | embed() | 32,000 | You're doing finance retrieval and RAG |
| voyage-context-4 | contextualized_embed() | 120,000 with enable_auto_chunking | You want chunk-level vectors that carry the whole document's context |
| voyage-multimodal-3.5 | multimodal_embed() | 32,000 | You need to embed text, images and video together |
Context length matters more once you add context to chunks. Some embedding models have a fixed input token limit. If contextualized chunks retrieve worse than plain ones, the added text may be pushing them past that limit so they get truncated. The fix is a model with a larger context window. voyage-law-2, for example, accepts half the input of the general-purpose models.
Embed documents and queries differently. Set input_type="document" when you embed chunks and input_type="query" when you embed the user's question. Don't omit the parameter or set it to None. Voyage prepends a different instruction to each kind of input: 'Represent the document for retrieval: ' for chunks and 'Represent the query for retrieving supporting documents: ' for questions. This gives better vectors for retrieval, which in turn improves retrieval quality.
Voyage vectors are normalized to length 1. That makes cosine similarity equal to dot product, and dot product is quicker to compute. Euclidean distance gives the same ranking too, so the similarity metric you choose won't change which chunks come back.
Two output settings make the index smaller without making retrieval more accurate. output_dtype quantizes each vector. With int8 or uint8, storage, memory and cost drop by 4x; with binary or ubinary, they drop by 32x. The default, float, keeps the highest precision and retrieval accuracy. output_dimension (for example 256 instead of the default 1024) returns shorter Matryoshka vectors, and vectors you've already stored can be cut down to their leading dimensions and normalized again. Use these settings when index size or cost is the problem. They won't help when relevant chunks are going missing.
Checkpoint 2 of 6· Match them up
Match each Voyage AI embedding model to the situation where you would pick it.
Tap a term, then the definition that fits it.
Voyage pairs each model with a use: general-purpose tiers trade quality against cost, domain models cover legal, code and finance, and the contextualized and multimodal models need their own calls (contextualized_embed() and multimodal_embed()) instead of embed().
“The following contextualized chunk embedding models produce chunk-level vectors that capture full document context without manual metadata augmentation.”Source: platform.claude.com
Checkpoint 3 of 6· Check yourself
A colleague reviewing your ingestion code removes input_type from every Voyage embed() call. They say one model embeds queries and chunks into the same vector space, so the label adds nothing. What should you do?
For retrieval, Voyage says to label chunks as documents and questions as queries. It prepends a different instruction to each, which gives better vectors for retrieval. Changing the metric does nothing here, because normalized Voyage vectors rank the same under cosine and dot product.
“Do not omit input_type or set input_type=None.”Source: platform.claude.com
3.Contextual embeddings and contextual BM25
Contextual retrieval writes the missing document context back into each chunk before indexing. For each chunk, Claude receives the whole document and the chunk and returns a short context, usually 50 to 100 tokens, that places the chunk within the document. That context is prepended to the chunk. The ACME chunk becomes 'This chunk is from an SEC filing on ACME corp's performance in Q2 2023; the previous quarter's revenue was $314 million.' followed by the original sentence.
<document>
{{WHOLE_DOCUMENT}}
</document>
Here is the chunk we want to situate within the whole document
<chunk>
{{CHUNK_CONTENT}}
</chunk>
Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk. Answer only with the succinct context and nothing else.The same contextualized chunk goes into both indexes. Pipelines keep a lexical index next to the vector index because embeddings can miss exact strings, such as error code TS-999, that BM25 matches (Semantic embeddings vs BM25, and hybrid search). Prepend the generated context before embedding the chunk; this is contextual embeddings. Prepend the same text before tokenizing the chunk for the BM25 index; this is contextual BM25. The original chunk text is still there, so BM25 still matches product codes and error strings exactly. It now also matches the company names, periods and file names that appeared only elsewhere in the document.
Each index improves measurably. Across codebases, fiction, ArXiv papers and science papers, contextual embeddings alone cut the top-20 retrieval failure rate by 35%, from 5.7% to 3.7%. Adding contextual BM25 raised the cut to 49%, bringing the failure rate to 2.9%. Contextualizing helped with every embedding model tested, and Gemini and Voyage embeddings gained the most.
The context has to be about the specific chunk. Attaching a generic document summary to every chunk gave very limited gains, and summary-based indexing performed poorly. The generic prompt above works well. A prompt tailored to your domain can work better, for example one that includes a glossary of terms defined only in other documents.
Prompt caching keeps the cost down. Each chunk's request repeats the whole document, so put the document first and mark the end of it with cache_control. The first chunk writes the document to the cache, and the following chunks read it at a 90% discount. The cache lasts five minutes, so process each document's chunks one after another instead of mixing chunks from different documents. With 800-token chunks, 8k-token documents and 100 tokens of context per chunk, generating the context costs $1.02 per million document tokens. That cost is paid once, at ingestion, not on every query. On a 737-chunk codebase dataset, caching cut input cost from about $9.20 to about $2.85.
Each document is written to the cache once and then read for that document's other chunks, and the cache lasts five minutes. When chunks from different files are interleaved, the cached document has often expired or been replaced before its next chunk arrives. Process chunks document by document.
Checkpoint 4 of 6· Check yourself
An engineer wants BM25 to keep matching product codes like TS-999 exactly. They propose prepending Claude's generated context only to the text sent to the embedding model, and indexing the raw chunks in BM25. What is the right design?
Contextual retrieval puts the same contextualized chunk into both indexes. Adding contextual BM25 to contextual embeddings raised the cut in retrieval failures from 35% to 49%. Exact matching still works because the original text is kept.
“The resulting contextual text, usually 50-100 tokens, is prepended to the chunk before embedding it and before creating the BM25 index.”Source: www.anthropic.com
Checkpoint 5 of 6· Fill the gap
Anthropic used this contextualizer prompt to generate each chunk's context. What goes in the blank?
<document>
?
</document>
Here is the chunk we want to situate within the whole document
<chunk>
{{CHUNK_CONTENT}}
</chunk>
Please give a short succinct context to situate this chunk within the overall document for the purposes of improving search retrieval of the chunk. Answer only with the succinct context and nothing else.Claude gets the whole document together with the chunk, so it can write context about that specific chunk. A generic document summary gave very limited gains. The whole document is also the part that prompt caching reuses across a document's chunks.
Source: www.anthropic.comCheckpoint 6 of 6· Exam question
A search team wants their lexical index to keep matching exact product codes and error strings verbatim, while also benefiting from the same document-level grounding they just added to their semantic embeddings. They plan to keep both a BM25 index and a vector index in the pipeline. What should they do to align the two indexes?
Correct answer: A — Prepend the same chunk-specific contextual text used for embeddings to each chunk before it is tokenized for the BM25 index.
- A. Correct. This is Contextual BM25: indexing the same contextualized chunk text used for embeddings lets the lexical index capture both exact matches and the semantic relationships from the prepended context, aligning it with the contextual embeddings.
- B. Incorrect. Replacing BM25 with another embedding index removes the exact-match lexical matching (product codes, error strings) that the team explicitly wants to preserve.
- C. Incorrect. Reducing term-frequency weighting suppresses the lexical precision the team relies on for verbatim matches and does nothing to align the index with document-level context.
- D. Incorrect. Indexing only titles and headings discards the chunk body text needed for exact lexical matches on codes and error strings, worsening rather than improving alignment.
Sources
(4)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://www.anthropic.com/engineering/contextual-retrievalSecondary source
“smaller chunks of text, usually no more than a few hundred tokens”
↩︎ Chunk size, boundaries and the context a chunk loses“The choice of chunk size, chunk boundary, and chunk overlap can affect retrieval performance”
↩︎ Chunk size, boundaries and the context a chunk loses“this chunk on its own doesn't specify which company it's referring to or the relevant time period”
↩︎ Chunk size, boundaries and the context a chunk loses“is prepended to the chunk before embedding it and before creating the BM25 index”
↩︎ Contextual embeddings and contextual BM25“Contextual Embeddings reduced the top-20-chunk retrieval failure rate by 35%”
↩︎ Contextual embeddings and contextual BM25“The resulting contextual text, usually 50-100 tokens, is prepended to the chunk before embedding it and before creating the BM25 index.”
↩︎ Key concept“is prepended to the chunk before embedding it and before creating the BM25 index”
↩︎ Exam trap 2“adding generic document summaries to chunks (we experimented and saw very limited gains)”
↩︎ Exam trap 3“If your knowledge base is smaller than 200,000 tokens (about 500 pages of material), you can just include the entire knowledge base in the prompt”
↩︎ Prediction“this chunk on its own doesn't specify which company it's referring to or the relevant time period, making it difficult to retrieve the right information”
↩︎ Checkpoint“The resulting contextual text, usually 50-100 tokens, is prepended to the chunk before embedding it and before creating the BM25 index.”
↩︎ Checkpoint - 2.
“produce chunk-level vectors that capture full document context without manual metadata augmentation”
↩︎ Chunk size, boundaries and the context a chunk loses“Anthropic does not offer its own embedding model.”
↩︎ Choosing and calling the embedding model“Do not omit input_type or set input_type=None.”
↩︎ Choosing and calling the embedding model“This is the default and provides the highest precision / retrieval accuracy.”
↩︎ Choosing and calling the embedding model“Do not omit input_type or set input_type=None.”
↩︎ Exam trap 1“The following contextualized chunk embedding models produce chunk-level vectors that capture full document context without manual metadata augmentation.”
↩︎ Checkpoint - 3.
“Some embedding models have fixed input token limits.”
↩︎ Choosing and calling the embedding model“Cache lasts 5 minutes, plenty of time to process all chunks in a document”
↩︎ Contextual embeddings and contextual BM25“This is why processing documents sequentially (rather than randomly shuffling chunks) is crucial for maximizing cache efficiency.”
↩︎ Contextual embeddings and contextual BM25 - 4.
“Mark the end of the reusable content for caching using the cache_control parameter.”
↩︎ Contextual embeddings and contextual BM25