What you will be able to do
- Decide whether a corpus belongs in the prompt with caching or needs a retrieval system
- Choose between embeddings, BM25 and hybrid search from the shape of the data and the queries
- Choose a retrieval stack by trading accuracy against per-query latency and cost
- Decide when an agent should retrieve just in time with tools instead of using a pre-built index
- Apply the same matching logic to tool catalogs and to long-running sessions
Key concept
Retrieval matched to data shape — No retrieval method is best everywhere. Pick it from what the corpus contains and how users ask: put the corpus in the prompt if it fits, use BM25 for exact identifiers, embeddings for meaning, a weighted blend for mixed traffic, and agent-driven tool search when an index would go stale.
1.First ask whether the corpus fits in the prompt
Retrieval exists because some corpora are too big for the context window. So the first design question is whether yours is. A knowledge base under 200,000 tokens, about 500 pages, can go into the prompt whole. Then there is no chunking, no index to keep fresh, and no retrieval step that can return the wrong passage.
Prompt caching is what makes the full-context option cheap. The first request processes the whole prompt and caches the prefix. Later requests that start with the same prefix reuse the cached version, which cuts processing time and cost. Anthropic reports that caching frequently used prompts cuts latency by more than 2x and cost by up to 90%. A handbook that every conversation reads is the ideal case, because the prefix is identical on every request.
Fitting in the window sets an upper limit. It does not mean you should fill the window. As the token count grows, accuracy and recall degrade, so what you put in context matters as much as how much room there is. Once the knowledge base grows past what fits, you need a retrieval method that scales, and the rest of this lesson is about choosing one.
Checkpoint 1 of 9· Check yourself
An internal assistant is grounded on a 150-page product FAQ that every conversation reads. Next year the team plans to add about 2,000 pages of engineering docs. Which plan best fits the guidance?
A corpus under about 200,000 tokens (about 500 pages) can go into the prompt whole, and caching keeps it cheap. Adding 2,000 pages pushes it past what fits, and then a retrieval method that scales is needed. Caching does not raise the window limit, and accuracy and recall degrade as the token count grows.
“However, as your knowledge base grows, you'll need a more scalable solution.”Source: www.anthropic.com
2.Embeddings match meaning, BM25 matches exact terms
The two basic retrievers fail in opposite ways. Embeddings turn text into vectors so that chunks close in meaning to the query rank high, even when they use different words. They are good at semantic relationships, but they can miss an exact match that matters.
BM25 is a lexical ranking function: it looks for the exact words or phrases in the query. It builds on TF-IDF, which scores how important a word is to one document within a collection. BM25 adds a correction for document length and a saturation function on term frequency, so common words cannot dominate the ranking. That makes it strong wherever queries carry unique identifiers or technical terms.
Take the query "Error code TS-999" against a technical support database. An embedding model may return content about error codes in general and miss the one page about TS-999. BM25 searches for that exact string and finds it. The reverse also holds: a question phrased in the user's own words, with none of the document's vocabulary, gives BM25 nothing to match, while embeddings find it through meaning.
| Query shape | Stronger retriever | Reason |
|---|---|---|
| Exact identifier, such as Error code TS-999 | BM25 | Looks for that specific text string |
| Conceptual question in the user's own words | Embeddings | Ranks by semantic similarity, not shared words |
| Mixed traffic: some identifiers, some paraphrase | Embeddings + BM25 combined | Balances exact term matching with semantic understanding |
Embedding retrieval has one setting that is easy to get wrong: input_type. Set it to query for user questions and to document for corpus text. Each value prepends its own instruction before embedding, which gives better vectors for retrieval. Leaving it out or setting it to None throws that gain away.
Checkpoint 2 of 9· Match them up
A support assistant gets three kinds of query traffic. Match each one to the retriever that suits it best.
Tap a term, then the definition that fits it.
BM25 matches the exact string, so it finds identifiers that embeddings may miss. Embeddings rank by meaning, so they find paraphrases that share no words with the document. When traffic mixes both, combining the two balances exact term matching with semantic understanding.
“By leveraging both BM25 and embedding models, traditional RAG systems can provide more comprehensive and accurate results, balancing precise term matching with broader semantic understanding.”Source: www.anthropic.com
3.Hybrid search and tuning the blend to your data
Hybrid search runs both retrievers and merges what they find. The standard pipeline:
- Split the corpus into chunks, usually a few hundred tokens or fewer.
- Build TF-IDF encodings and semantic embeddings for every chunk.
- Take the top chunks by exact match with BM25.
- Take the top chunks by semantic similarity with embeddings.
- Combine and deduplicate the two lists using rank fusion.
- Add the top-K chunks to the prompt.
The fusion step is where you tune for your data. Anthropic's reference implementation takes the top 150 candidates from each retriever and merges them with weighted Reciprocal Rank Fusion. The default is 80% weight on semantic search and 20% on BM25, and the weights are meant to be tuned. A corpus full of function names, part numbers or error codes calls for more BM25 weight. A corpus where users paraphrase calls for more semantic weight.
Even at 80/20 the lexical side does real work. In a codebase evaluation, BM25 still supplied about 39–45% of the final results after fusion, depending on how many results were kept. Code is full of exact identifiers, and those are the queries embeddings miss.
The embedding side can be matched to the data as well. Domain-specific models exist for code retrieval and agentic coding (voyage-code-4), legal work (voyage-law-2) and finance (voyage-finance-2). Providers that allow continued training on private data can improve results on unusual vocabularies. Before you add a second retriever to cover vocabulary a general model handles badly, check whether a domain model already covers it.
Checkpoint 3 of 9· Check yourself
Hybrid search over a spare-parts catalog runs with the reference defaults: 80% weight on semantic search, 20% on BM25. Logs show that queries quoting an exact part number such as "PN-77214-B" often miss the right page, while queries describing a part in plain words work well. What should the architect change first?
The fusion weights can be tuned to the data. A corpus full of part numbers or error codes needs more BM25 weight, because embeddings can miss exact strings and BM25 matches them literally. Even at 20% weight, BM25 supplied a large share of the final results in the codebase evaluation, so removing it would make the misses worse.
“The weighting system lets you balance between semantic understanding and keyword precision based on your data characteristics.”Source: platform.claude.com
4.Choosing the full stack by accuracy, latency and cost
Beyond plain hybrid search there are two more layers you can add, and each one costs something. Contextual retrieval (contextual embeddings and contextual BM25) uses Claude to prepend a short, chunk-specific context to each chunk before it is indexed. Reranking and how many chunks to pass re-scores a large candidate set with a specialised model and keeps only the best few.
| Approach | Pass@5 | Pass@10 | Pass@20 |
|---|---|---|---|
| Baseline RAG | 80.92% | 87.15% | 90.06% |
| + Contextual Embeddings | 88.12% | 92.34% | 94.29% |
| + Hybrid Search (BM25) | 86.43% | 93.21% | 94.99% |
| + Reranking | 92.15% | 95.26% | 97.45% |
Contextual retrieval pays off when the data is made of chunks that lose their meaning once cut out of the document. SEC filings are the usual example. A chunk that says "The company's revenue grew by 3% over the previous quarter" names neither the company nor the period, so neither retriever can match it to a question about ACME in Q2 2023. The cost is paid once, at ingestion: about $1.02 per million document tokens with prompt caching, and about $3 for the whole codebase dataset above. Plain hybrid search needs no LLM pass at all, but you have to run and maintain Elasticsearch.
Reranking costs something on every query: roughly 100–200 ms of extra latency and about $0.002 per query in API fees. Within reranking there is a further trade-off. Scoring more candidates improves accuracy, and scoring fewer lowers latency and cost. Rerankers come in tiers too: rerank-3 is the most accurate, and rerank-3-lite is optimised for latency and cost.
The results suggest three typical choices. For high-volume, cost-sensitive traffic, contextual embeddings alone reach about 92% Pass@10 with no per-query cost. For a balanced production system, add hybrid search for about 93% without per-query fees. When maximum accuracy matters and some latency is acceptable, add reranking to reach about 95%. For most production systems the best performance per dollar comes from contextual embeddings.
Checkpoint 4 of 9· Check yourself
Millions of low-margin search queries a day run against a large, chunked document corpus. Every extra cent per query matters, and a few points of Pass@10 matter less. Which retrieval stack fits these requirements best?
Contextual embeddings cost about $1.02 per million document tokens, paid once at ingestion, and reach about 92% Pass@10 with no per-query fees. Reranking adds latency and an API fee on every query. Hybrid search means running and maintaining Elasticsearch. The contextualising LLM pass happens at ingestion, not on each query.
“High-volume, cost-sensitive: Contextual embeddings alone (92% Pass@10, no per-query costs)”Source: platform.claude.com
5.Just-in-time retrieval: letting the agent search with tools
Everything so far assumes an index built before any query arrives. Just-in-time retrieval drops that assumption. The agent keeps lightweight references such as file paths, stored queries and web links, and uses tools to load data into context only when it needs it. Claude Code works this way on large databases: it writes targeted queries, stores the results, and uses head and tail to inspect large outputs without ever loading the full objects into context.
This approach wins when the data changes faster than an index can be rebuilt. Claude Code's glob and grep read files as they are now, which avoids stale indexes and complex syntax trees in a codebase that is edited all day. The surroundings are also information: a test_utils.py file in a tests folder means something different from one in src/core_logic/. Folder structure, naming conventions and timestamps all help the agent decide what to open next.
The cost is speed and reliability. Exploring at run time is slower than looking up precomputed results. The agent also needs the right tools and guidance, or it will misuse tools, chase dead ends and fill its context with noise. That last risk is serious, because accuracy and recall drop as the token count grows.
Many systems combine the two. Claude Code loads its CLAUDE.md files into context at the start and greps for everything else. A mixed approach suits content that changes less often, such as legal or finance material: load the stable core up front for speed, and let the agent explore the rest when it needs to.
Give the agent just-in-time tools such as glob, grep and file reads, so it searches the code as it is now. A nightly index is stale by design for code that changes during the day. Better embeddings or reranking would not fix that.
Checkpoint 5 of 9· Check yourself
For a legal-research agent, a core set of firm policies and standard clauses changes only a few times a year. A much larger archive of past case files is consulted now and then. Answers should come back quickly. Which retrieval design fits best?
Content that rarely changes, such as legal or finance material, suits the hybrid approach. Loading the stable core up front gives speed, and the agent explores the rest only when needed. Run-time exploration is slower than precomputed lookups, and filling the context hurts accuracy and recall.
“The hybrid strategy might be better suited for contexts with less dynamic content, such as legal or finance work.”Source: www.anthropic.com
6.The same logic for tool catalogs and long sessions
Tool definitions are a corpus too, and the first question is the same: do they fit? Tool search marks definitions with defer_loading: true, so they enter context only when Claude finds them by searching. It is a form of progressive discovery vs monolithic context. It comes in two built-in variants, tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119.
Tool search adds a search step before each tool call. It only pays off when the context saved and the gain in tool-selection accuracy outweigh that extra latency. Typical signals are definitions totalling more than 10K tokens or more than ten tools. Even then, keep your 3–5 most-used tools non-deferred so Claude can call them without searching. Eight small tools that nearly every request uses fall well below that threshold, so load them directly. Deferring them, with regex or BM25 search or behind a deferred MCP toolset, would add a search before every call Claude was going to make anyway.
Matching on meaning works for tools the same way it works for chunks. Both built-in variants match on words or patterns. When tool descriptions are short and related only through an embedding space, BM25 has too few shared words to match, and broad regex wildcards do not capture meaning either. Instead, build a custom search tool that queries your embeddings index and returns tool_reference blocks in its tool_result. Every tool it references must still be defined in the top-level tools array, normally with defer_loading: true.
{
"type": "tool_result",
"tool_use_id": "toolu_your_tool_id",
"content": [{ "type": "tool_reference", "tool_name": "discovered_tool_name" }]
}A long agent session can outgrow the window by itself. A research agent that retrieves and discusses documents for hours builds up a history that, like an oversized corpus, eventually stops fitting. For long-running conversations and agentic workflows, server-side compaction is the main way to manage this. It lets the session continue past the limit without the agent losing its earlier findings. Other fixes make things worse. The context window holds both the history and the new output, so raising max_tokens leaves less room for history. Re-uploading earlier documents on every turn fills the window faster. More on managing the window in context window management.
Checkpoint 6 of 9· Check yourself
Three hours into a research session, an agent that retrieves and discusses documents has built up a history that no longer fits in the context window. The team wants it to keep working without losing what it found earlier. Which change addresses this?
Like a corpus that has grown too big, a long session can outgrow the window. Compaction is the main way to keep it going without losing earlier findings. Raising max_tokens leaves less room for history, because the window holds both history and new output. Re-uploading documents fills the window faster. defer_loading applies to tool definitions, not to conversation history.
“we've developed a few techniques that address these context pollution constraints directly: compaction, structured note-taking, and multi-agent architectures.”Source: www.anthropic.com
Checkpoint 7 of 9· Exam question
An internal ops agent has 8 tools total (deploy, rollback, restart, status, logs, scale, alert, notify), each under 100 tokens, and nearly every request needs several of them. Which tool-configuration approach fits this scenario?
Correct answer: A — Call all 8 tools directly through standard tool definitions without enabling tool search or deferred loading.
- A. Correct. With fewer than 10 tools, small definitions, and near-universal use per request, standard tool calling without tool search is the better fit; deferring these tools would add search overhead for no benefit.
- B. Tool search helps when catalogs are large or selection accuracy is degrading; forcing a search step for 8 tools used in nearly every request adds latency without solving a real problem.
- C. Deferring all 8 tools behind regex search removes the 3-5 frequently used tools from immediate context, which is discouraged when most of the catalog is needed on almost every call.
- D. Deferring the whole toolset behind one MCP connector still forces a search step before nearly every request can proceed, which is unnecessary at this small scale.
Checkpoint 8 of 9· Exam question
A research agent runs for several hours, repeatedly retrieving and discussing documents, and the conversation is approaching its context window limit while still needing to reference earlier findings. Which strategy matches this query pattern?
Correct answer: A — Enable server-side compaction so earlier turns are automatically summarized while the session continues past the limit.
- A. Correct. Server-side compaction is the primary mechanism for long-running, retrieval-heavy sessions approaching the context limit: it summarizes earlier turns automatically so the conversation can continue while preserving prior findings.
- B. Raising max_tokens changes how much a single turn can output, not how much accumulated conversation history fits in the window, so it does not address the approaching limit.
- C. Re-uploading every prior document each turn accelerates hitting the context limit rather than managing it, and duplicates content already in the conversation history.
- D. Deliberately choosing a smaller context window shrinks the working space available and shifts summarization work onto the user instead of using built-in context management.
Checkpoint 9 of 9· Exam question
A platform wants Claude to discover tools using an existing embeddings index rather than the built-in regex or BM25 matching, because tool descriptions are sparse but semantically related through the embedding space. Which implementation matches this requirement?
Correct answer: A — Build a custom tool that runs the embeddings search and returns tool_reference blocks in its tool_result for Claude to expand.
- A. Correct. A custom client-side tool search implementation can run any retrieval method, including embeddings, and return standard tool_result content with tool_reference blocks, which the API expands into full tool definitions.
- B. BM25 is a term-frequency-based lexical ranking method, not a true semantic embedding similarity search, so it would not reproduce the intended embeddings-based matching.
- C. Regex matching operates on literal patterns against names and descriptions and cannot capture semantic relationships between sparse, differently worded tool descriptions.
- D. Loading every definition up front abandons retrieval entirely and reintroduces the context bloat problem that made an embeddings-based discovery approach necessary.
Sources
(8)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“If found, it uses the cached version, reducing processing time and costs.”
↩︎ First ask whether the corpus fits in the prompt - 2.
“This makes curating what's in context just as important as how much space is available.”
↩︎ First ask whether the corpus fits in the prompt“As token count grows, accuracy and recall degrade, a phenomenon known as context rot.”
↩︎ Just-in-time retrieval: letting the agent search with tools“For long-running conversations and agentic workflows, server-side compaction is the primary strategy for context management.”
↩︎ The same logic for tool catalogs and long sessions“holds the conversation history plus the new output Claude generates”
↩︎ The same logic for tool catalogs and long sessions - 3.https://www.anthropic.com/engineering/contextual-retrievalSecondary source
“reducing latency by > 2x and costs by up to 90%”
↩︎ First ask whether the corpus fits in the prompt“smaller than 200,000 tokens (about 500 pages of material), you can just include the entire knowledge base”
↩︎ First ask whether the corpus fits in the prompt“It's particularly effective for queries that include unique identifiers or technical terms.”
↩︎ Embeddings match meaning, BM25 matches exact terms“BM25 refines this by considering document length and applying a saturation function to term frequency”
↩︎ Embeddings match meaning, BM25 matches exact terms“An embedding model might find content about error codes in general”
↩︎ Embeddings match meaning, BM25 matches exact terms“Combine and deduplicate results from (3) and (4) using rank fusion techniques;”
↩︎ Hybrid search and tuning the blend to your data“this chunk on its own doesn't specify which company it's referring to or the relevant time period”
↩︎ Choosing the full stack by accuracy, latency and cost“the one-time cost to generate contextualized chunks is $1.02 per million document tokens”
↩︎ Choosing the full stack by accuracy, latency and cost“There is an inherent trade-off between reranking more chunks for better performance vs. reranking fewer for lower latency and cost.”
↩︎ Choosing the full stack by accuracy, latency and cost“smaller than 200,000 tokens (about 500 pages of material), you can just include the entire knowledge base”
↩︎ Exam trap 1“While embedding models excel at capturing semantic relationships, they can miss crucial exact matches.”
↩︎ Exam trap 2“However, as your knowledge base grows, you'll need a more scalable solution.”
↩︎ Checkpoint“By leveraging both BM25 and embedding models, traditional RAG systems can provide more comprehensive and accurate results, balancing precise term matching with broader semantic understanding.”
↩︎ Checkpoint - 4.
“Text embeddings are numerical representations of text that enable measuring semantic similarity.”
↩︎ Embeddings match meaning, BM25 matches exact terms“Do not omit input_type or set input_type=None.”
↩︎ Embeddings match meaning, BM25 matches exact terms“Code retrieval and agentic coding: voyage-code-4”
↩︎ Hybrid search and tuning the blend to your data“This can improve performance on unique vocabularies”
↩︎ Hybrid search and tuning the blend to your data“Highest accuracy. Recommended for most applications.”
↩︎ Choosing the full stack by accuracy, latency and cost - 5.
“These weights are tunable—experiment to optimize for your use case”
↩︎ Hybrid search and tuning the blend to your data“Retrieve candidates: Get top 150 results from both semantic search and BM25”
↩︎ Hybrid search and tuning the blend to your data“Reranking: Adds 100-200ms query latency and per-query API costs (~$0.002 per query)”
↩︎ Choosing the full stack by accuracy, latency and cost“For most production RAG systems, contextual embeddings provide the best performance-to-cost ratio”
↩︎ Choosing the full stack by accuracy, latency and cost“Hybrid search: Requires Elasticsearch infrastructure and maintenance”
↩︎ Choosing the full stack by accuracy, latency and cost“The weighting system lets you balance between semantic understanding and keyword precision based on your data characteristics.”
↩︎ Key concept“The weighting system lets you balance between semantic understanding and keyword precision based on your data characteristics.”
↩︎ Checkpoint“Contextual embeddings provided the largest single improvement (+5-7 percentage points)”
↩︎ Prediction“High-volume, cost-sensitive: Contextual embeddings alone (92% Pass@10, no per-query costs)”
↩︎ Checkpoint - 6.
“maintain lightweight identifiers (file paths, stored queries, web links, etc.) and use these references to dynamically load data into context at runtime using tools”
↩︎ Just-in-time retrieval: letting the agent search with tools“retrieve files just-in-time, effectively bypassing the issues of stale indexing and complex syntax trees”
↩︎ Just-in-time retrieval: letting the agent search with tools“runtime exploration is slower than retrieving pre-computed data”
↩︎ Just-in-time retrieval: letting the agent search with tools“The hybrid strategy might be better suited for contexts with less dynamic content, such as legal or finance work.”
↩︎ Just-in-time retrieval: letting the agent search with tools“we've developed a few techniques that address these context pollution constraints directly: compaction, structured note-taking, and multi-agent architectures.”
↩︎ Checkpoint - 7.
“Tools with defer_loading: true load only when Claude discovers them through search.”
↩︎ The same logic for tool catalogs and long sessions“Every tool referenced must have a corresponding tool definition in the top-level tools parameter, normally with defer_loading: true.”
↩︎ The same logic for tool catalogs and long sessions“Keep your 3–5 most frequently used tools non-deferred so Claude can call them without searching first.”
↩︎ Exam trap 3“You can implement your own tool search logic (for example, using embeddings or semantic search) by returning tool_reference blocks from a custom tool.”
↩︎ Exam trap 4 - 8.https://www.anthropic.com/engineering/advanced-tool-useSecondary source
“it delivers the best ROI when the context savings and accuracy improvements outweigh additional latency”
↩︎ The same logic for tool catalogs and long sessions