Grounding a model in your own documents: the RAG pipeline end to end with real local models, chunking, hybrid search with reciprocal rank fusion, cross-encoder reranking, query rewriting and HyDE, prompts with citations and "I don't know", Anthropic's contextual retrieval, retrieval metrics computed on a labelled set, and when long context or fine-tuning is the better choice.
RAG is the most common AI feature in production software, because it answers the question every company asks first: "can it answer from our documents?" A model on its own knows only its training data, which stops at a cut-off date and never included your help centre, your contracts or your codebase. RAG fixes that at request time: find the few passages that answer the question, put them in the prompt, and ask the model to answer from them and say where each claim came from. Most of the engineering, and most of what goes wrong, is in the finding, which is why this chapter spends more time on retrieval than on generation.
All the examples use one small, realistic knowledge base: the help centre of Meadowlark, a fictional team-calendar app, written for this page. It has 34 short sections (plans, refunds, sign-in, integrations, booking links, error messages), and a labelled set of 20 questions phrased the way real users write them, from "OC-401" to "I was charged after I cancelled". Small enough to read in full, big enough for the retrievers to disagree.
How these examples run. Every example is a Node 26 program that was run for this page, and the box under it is its real output. Retrieval uses real local models through transformers.js (@huggingface/transformers 4.3.2): Xenova/all-MiniLM-L6-v2 for embeddings and Xenova/ms-marco-MiniLM-L-6-v2, a cross-encoder, for reranking, both with 8-bit weights, so every similarity score, ranking and metric is genuine and deterministic on the machine that produced it. The Claude calls use the real Anthropic TypeScript SDK (@anthropic-ai/sdk 1.17.0) exactly as production code would, but there's no API key here: the replies in the block marked "Scripted replies" at the top of each example are written in the exact shape the API returns (including the documented shape of search-result citations), and the model's words in them were written for the example. To run one for real, delete that block and create the client with new Anthropic() and ANTHROPIC_API_KEY set.
11 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.
Retrieval-augmented generation is a pattern, not a product: retrieve relevant text at request time, put it in the prompt, and have the model answer from it. The model's knowledge stays frozen; what changes per request is the context you hand it. That gives you three things a bare model can't: answers about private and recent information, answers you can trace to a source, and a knowledge base you can update by editing documents instead of retraining anything.
The mental model is an open-book exam. A closed-book student answers from memory and, when memory fails, bluffs (that's hallucination, How LLMs Work). An open-book student is handed the right pages and asked to answer from them, quoting where they found it. The student's ability to read and reason still matters, but the facts come from the book. RAG is you, as the engineer, finding the right pages fast, and most RAG failures are "handed the wrong pages", not "couldn't read".
Use RAG when:
the answers live in documents the model wasn't trained on (help centres, policies, internal wikis, contracts, tickets, code);
the information changes (prices, stock, procedures) and must be current;
users need sources they can check, or you need an audit trail of why the model said something;
different users may see different documents, so permissions must be applied per request;
the knowledge base is too large, or too costly, to send whole on every request.
Don't reach for it when the task needs no external facts (rewriting, classification, general reasoning), when the whole knowledge base is small enough to put in the prompt and cache (Anthropic's contextual retrieval write-up suggests that knowledge bases under about 200,000 tokens can often skip retrieval; see RAG, long context or fine-tuning?), or when what you need to change is the model's behaviour (tone, format, a skill) rather than its knowledge, which is a prompting or fine-tuning question.
For each, choose RAG, long context, fine-tuning or none: (a) answering staff questions from a 40,000-page policy wiki that changes weekly; (b) summarising one 80-page contract a user uploads; (c) making replies match your brand's tone; (d) translating marketing copy.
Show answer
(a) RAG, (b) long context, (c) prompting first, fine-tuning if that isn't enough, (d) none.
What’s happening
(a) Far too large for any context window (millions of tokens), changes weekly, and staff need sources: retrieve the relevant passages per question. A textbook RAG case.
(b) One document that fits easily in the window (80 pages is tens of thousands of tokens) and is used once: put it in the prompt. Retrieval would only risk missing parts of it.
(c) Tone is behaviour, not knowledge. A system prompt with examples usually gets there; fine-tuning is the heavier option if you need it at scale or on a smaller model.
(d) The model already knows how to translate; no external facts are needed. Add a glossary to the prompt if product names must stay fixed.
A RAG system is two pipelines that meet at the index. The ingest pipeline runs ahead of time: load documents, split them into chunks, optionally add context to each chunk, embed the chunks, and store the vectors (and usually a keyword index) with each chunk's text, source and permissions. The query pipeline runs per request: optionally rewrite the question, retrieve candidate chunks (vector search, keyword search or both), rerank them, put the best few into a prompt with instructions, call the model, and return the answer with its sources.
The mental model is a library with a very fast librarian. Ingest is cataloguing: every book cut into index cards, each card filed by meaning. A question is a patron at the desk: the librarian pulls the twenty most promising cards, reads them properly to pick the best three, and hands those to the expert (the model), who writes the answer and cites the cards. Each step is a place to lose the answer: a badly cut card (chunking), a misfiled card (embedding), a hurried first pull (retrieval), a careless read (reranking), or an expert who ignores the cards (prompting).
The two halves of a RAG system. Ingest builds the index ahead of time; each query searches it, reranks, and hands the best chunks to the model.
AI LabRAG pipeline
Ask the lab's help-centre pipeline a question in your own words, such as I lost my phone and can't get past the login code, and watch each stage: the retrieved chunks with their similarity scores, the reranker's new order, and the prompt that goes to the model.
The example is the whole query pipeline in one file over the 34-chunk help centre: embed and index, retrieve 10 candidates, rerank to 3, send them to Claude as search results with citations enabled, and print the answer with numbered sources.
rag-pipeline.mjs
import Anthropic from"@anthropic-ai/sdk";import{ pipeline, AutoTokenizer, AutoModelForSequenceClassification }from"@huggingface/transformers";// Scripted replies (see "How these examples run") ---------------------------------------------// One reply in the documented shape for search-result citations; the model's words were written for the example.const reply ={id:"msg_01Rz8XqLk2VnD5tFw9JhB3Cm",type:"message",role:"assistant",content:[{type:"text",text:"That message usually means the code from your authenticator app wasn't accepted. If you no longer have the phone, "},{type:"text",text:"sign in with one of your 10 recovery codes (each works once), or ask your workspace admin to reset two-step verification for you.",citations:[{type:"search_result_location",cited_text:"You get 10 recovery codes, each usable once. If you lose your phone, sign in with a recovery code or ask your workspace admin to reset two-step verification.",source:"help/a4",title:"Two-step verification",search_result_index:0,start_block_index:0,end_block_index:1,},],},],model:"claude-opus-5-5",stop_reason:"end_turn",stop_sequence:null,usage:{input_tokens:412,output_tokens:96},};constfetch=async(url, init)=>{const body =JSON.parse(init.body);const blocks = body.messages[0].content;
console.log(`\nsent to Claude: ${blocks.filter((b)=> b.type ==="search_result").map((b)=> b.source).join(", ")} + the question`);return Response.json(reply);};const client =newAnthropic({apiKey:"sk-ant-test", fetch });// for real: new Anthropic()// ----------------------------------------------------------------------------------------------// The Meadowlark help centre (a fictional team-calendar app): 34 chunks, one per section.const chunks =[["p1","Plans and pricing","Meadowlark has three plans. Free covers up to 3 people. Team costs £8 per person per month. Business costs £15 per person per month and adds single sign-on (SSO) and the API."],["p2","Plans and pricing","Paying yearly gives you 12 months for the price of 10. Switch between monthly and yearly billing at any time in Settings > Billing."],["r1","Refunds","Monthly plans are not refunded for unused days. When you cancel, your plan stays active until the end of the month you have paid for."],["r2","Refunds","Yearly plans can be refunded within 30 days of the start or renewal date. We refund the unused months, pro rata."],["r3","Refunds","Refunds go back to the card you paid with and usually arrive within 5 to 10 working days."],["a1","Resetting your password","Choose Forgot password on the sign-in page and enter your work email. We send a reset link that expires after 30 minutes."],["a2","Resetting your password","If your company signs in with SSO, Meadowlark does not store a password for you: reset it with your identity provider, such as Okta or Google Workspace."],["a3","Two-step verification","Turn on two-step verification in Settings > Security. Meadowlark works with authenticator apps such as Google Authenticator and 1Password."],["a4","Two-step verification","You get 10 recovery codes, each usable once. If you lose your phone, sign in with a recovery code or ask your workspace admin to reset two-step verification."],["i1","Google Calendar sync","Connect Google Calendar in Settings > Integrations. Events sync both ways every 5 minutes."],["i2","Google Calendar sync","Private Google events appear in Meadowlark as Busy, without their title or attendees."],["i3","Google Calendar sync","Error GC-403 means Meadowlark lost permission to read your calendar, usually after a Google password change. Reconnect the calendar to fix it."],["i4","Slack notifications","Install the Meadowlark app for Slack from Settings > Integrations. A Slack workspace admin may need to approve it."],["i5","Slack notifications","Meadowlark sends a Slack reminder 10 minutes before each meeting. Type /meadowlark today to see your schedule."],["s1","Booking links","A booking link lets people outside your company pick a free slot in your calendar. Create one from the Booking links page."],["s2","Booking links","You can add buffer time before and after booked meetings, from 5 to 60 minutes."],["s3","Booking links","The Team plan includes up to 5 booking links per person; Business has no limit."],["d1","Exporting your data","Admins can export every calendar and booking as CSV or ICS files from Settings > Data. Export files stay available for 7 days."],["d2","Exporting your data","Business plans can also read data through the REST API, with up to 100 requests per minute per workspace."],["d3","Deleting your workspace","Only the workspace owner can delete a workspace. A deleted workspace can be restored for 14 days; after that, all data is permanently erased."],["e1","Error messages","E401 means your session expired. Sign in again; if it keeps happening, check that your browser allows cookies from meadowlark.example."],["e2","Error messages","E429 means too many requests in a short time. Wait a minute and try again; API clients should slow down and retry with backoff."],["m1","Mobile apps","Meadowlark has an iPhone app in the App Store. It shows your schedule and booking links and sends meeting reminders."],["m2","Mobile apps","On Android, use Meadowlark in your phone's browser; you can add it to your home screen for an app-like experience."],["b1","Invoices and payment","Invoices are emailed to the billing contact on the first day of each billing period. Download past invoices from Settings > Billing > Invoices."],["b2","Invoices and payment","To change the card we charge, open Settings > Billing and choose Update payment method. We accept Visa, Mastercard and American Express."],["a5","Changing your email","Change the email address you sign in with from Profile > Account. We send a confirmation link to the new address before the change takes effect."],["o1","Outlook calendar sync","Connect Outlook or Microsoft 365 in Settings > Integrations. Outlook events sync both ways every 10 minutes."],["o2","Outlook calendar sync","Error OC-401 means your Microsoft sign-in expired. Sign in to Microsoft again from Settings > Integrations to resume syncing."],["t1","Microsoft Teams notifications","Add the Meadowlark app to Microsoft Teams to get meeting reminders and a daily agenda in a Teams chat."],["s4","Booking links","People who book through your link get a confirmation email with links to reschedule or cancel, up to 2 hours before the meeting."],["s5","Booking links","Booking pages show free slots in the visitor's own time zone, detected from their browser."],["e3","Error messages","E403 means your role does not allow this action. Ask a workspace admin to change your role or do it for you."],["n1","Notifications","Turn meeting reminders off, or change how early they arrive, in Profile > Notifications. Each channel (email, Slack, Teams, mobile) has its own setting."],].map(([id, title, text])=>({ id, title, text }));// 1. INGEST: embed every chunk once and keep the vectors (a vector database in production).const embed =awaitpipeline("feature-extraction","Xenova/all-MiniLM-L6-v2",{dtype:"q8"});const vectors =(awaitembed(chunks.map((c)=> c.text),{pooling:"mean",normalize:true})).tolist();// 2. RETRIEVE: embed the question, take the 10 most similar chunks.asyncfunctionretrieve(question, k){const[q]=(awaitembed([question],{pooling:"mean",normalize:true})).tolist();return vectors
.map((v, i)=>({chunk: chunks[i],score: v.reduce((s, x, d)=> s + x * q[d],0)})).sort((a, b)=> b.score - a.score).slice(0, k);}// 3. RERANK: a cross-encoder reads the question and each candidate together and scores relevance.const rerankTokenizer =await AutoTokenizer.from_pretrained("Xenova/ms-marco-MiniLM-L-6-v2");const reranker =await AutoModelForSequenceClassification.from_pretrained("Xenova/ms-marco-MiniLM-L-6-v2",{dtype:"q8"});asyncfunctionrerank(question, candidates, k){const inputs =rerankTokenizer(candidates.map(()=> question),{text_pair: candidates.map((c)=> c.chunk.text),padding:true,truncation:true,});const{ logits }=awaitreranker(inputs);const scores = logits.tolist().map(([s])=> s);return candidates.map((c, i)=>({...c,rerank: scores[i]})).sort((a, b)=> b.rerank - a.rerank).slice(0, k);}// 4. GENERATE: send the top chunks as search results, so the answer can cite them.const question ="can't log in, it says my code is wrong";const candidates =awaitretrieve(question,10);
console.log(`retrieved: ${candidates.slice(0,5).map((c)=>`${c.chunk.id}${c.score.toFixed(2)}`).join(", ")}, …`);const top =awaitrerank(question, candidates,3);
console.log(`reranked: ${top.map((c)=>`${c.chunk.id}${c.rerank.toFixed(2)}`).join(", ")}`);const message =await client.messages.create({model:"claude-opus-5-5",max_tokens:1024,system:"You are Meadowlark's support assistant. Answer from the search results only. If they don't contain the answer, say you don't know and offer to connect the user with support.",messages:[{role:"user",content:[...top.map(({ chunk })=>({type:"search_result",source:`help/${chunk.id}`,title: chunk.title,content:[{type:"text",text: chunk.text }],citations:{enabled:true},})),{type:"text",text: question },],},],});// 5. SHOW: the answer text with numbered sources taken from the citations.const sources =[];let answer ="";for(const block of message.content){if(block.type !=="text")continue;
answer += block.text;for(const c of block.citations ??[]){if(c.type !=="search_result_location")continue;if(!sources.includes(c.source)) sources.push(c.source);
answer +=` [${sources.indexOf(c.source)+1}]`;}}
console.log(`\n${answer}`);for(const[i, s]of sources.entries()) console.log(`[${i +1}] ${chunks.find((c)=>`help/${c.id}`=== s).title} (${s})`);
Result
retrieved: e1 0.44, a1 0.31, a4 0.29, o2 0.29, a2 0.29, …
reranked: a4 -9.36, a2 -10.23, e1 -10.87
sent to Claude: help/a4, help/a2, help/e1 + the question
That message usually means the code from your authenticator app wasn't accepted. If you no longer have the phone, sign in with one of your 10 recovery codes (each works once), or ask your workspace admin to reset two-step verification for you. [1]
[1] Two-step verification (help/a4)
What’s happening
Ingest. The 34 chunks (one per help-centre section, each with an id and the article title) are embedded once and kept in memory as 384-number vectors. In production this is a batch job that writes to pgvector or a vector database, and re-runs when articles change.
Retrieve. The question "can't log in, it says my code is wrong" is embedded and compared with every chunk. The top candidates are e1 (0.44, the "session expired" error), a1, a4, o2 and a2 (all near 0.3). The right answer, a4 (recovery codes), is only third: the first stage is about recall, not order.
Rerank. The cross-encoder reads the question with each of the 10 candidates and scores them together: a4 jumps to first (−9.36), then a2 and e1. The scores are raw logits, so only their order matters; the top 3 go forward.
Generate. The top 3 chunks are sent as search_result content blocks, each with a source (help/a4), a title and citations: { enabled: true }, followed by the question as a text block. The system prompt tells the model to answer only from them and to say it doesn't know otherwise. The scripted fetch prints what was sent: help/a4, help/a2, help/e1 plus the question.
Show sources. The (scripted) reply is the documented citation shape: text blocks, some carrying a citations array of search_result_location entries with the source, title, cited_text and search_result_index (0, the first result sent). The loop appends [1] after cited text and prints the source list, so the user can check the claim against "Two-step verification".
Every later topic improves one of these steps. Notice how much depended on the reranker here: without it, the model would have been handed "your session expired" as the most relevant passage.
AdvancedGotcha: retrieval is the usual failure
?Where did it go wrong?
A user asks "can't log in, it says my code is wrong". The model answers "Your session has expired; sign in again." Using the example's numbers, which stage failed, and what would have prevented it?
Show answer
The first-stage retrieval ranked the "session expired" chunk first; a reranker (or sending more than one chunk) prevents it.
What’s happening
Dense retrieval put e1 ("E401 means your session expired…") at 0.44 and the right chunk a4 third at 0.29. "can't log in" overlaps strongly with "sign in again".
If only the top chunk were sent, the model would faithfully answer from the wrong passage: that answer isn't a hallucination, it's grounded in the wrong source.
The cross-encoder, which reads the question and the chunk together, moved a4 to the top. Sending the top three rather than one also gives the model a chance to pick the relevant passage itself.
The way to find this kind of failure systematically is a labelled retrieval set: this exact question is in this chapter's set, and it's one of the cases where reranking changes the result.
Chunking is deciding the unit of retrieval: the pieces your documents are cut into before embedding. It matters more than it looks, because a chunk is all the model sees of a document. Too small, and the answer is split across chunks, or a chunk loses the context that made it meaningful ("It expires after 30 minutes": what does?). Too large, and the chunk's embedding becomes an average of several topics (Choosing an embedding model measured the dilution), and you spend context on irrelevant text.
The three common strategies:
Fixed size with overlap: cut every N tokens (or words), repeating the last M in the next chunk so a sentence on a boundary appears whole in at least one chunk. Simple and predictable, but blind to meaning: it cuts mid-sentence and mid-list.
By structure: split along the document's own boundaries: headings, sections, paragraphs, list items, code blocks, table rows. Usually the best default for documents that have structure (help centres, docs, Markdown, HTML), because authors already grouped related sentences. Large sections are split further; tiny ones merged with a neighbour. Keep the heading path as a prefix ("Two-step verification > Lost your phone?").
Semantic: embed sentences and start a new chunk where the meaning shifts (adjacent-sentence similarity drops). Useful for long unstructured text (transcripts, emails); slower to build and sensitive to its threshold.
Typical sizes are a few hundred tokens with 10–20% overlap, but there's no universal right size: it depends on your embedding model's limit, how long your answers are, and how many chunks you send. Measure it with your retrieval eval rather than guessing. Two refinements are worth knowing: parent-child retrieval (search small chunks for precision, then send their larger parent section for context), and keeping metadata with every chunk (document id, title, URL, section, date, permissions) for filtering and citations.
The mental model is cutting a newspaper into clippings for a scrapbook. Cut along the articles (structure) and every clipping makes sense on its own; cut every ten centimetres (fixed size) and half your clippings start mid-sentence; cut wherever the topic seems to change (semantic) and you'll mostly be right, occasionally gluing the end of one story to the start of the next.
The example chunks one help article three ways and asks which chunk best matches a question whose full answer needs one particular sentence.
chunking.mjs
import{ pipeline }from"@huggingface/transformers";// One longer help article, the way it might be stored as Markdown.const article =`# Two-step verification
## Turning it on
Two-step verification adds a second check when you sign in. Open Settings > Security and choose Turn on. Scan the QR code with an authenticator app such as Google Authenticator or 1Password, then type the six-digit code it shows.
## Recovery codes
When you turn it on, Meadowlark shows 10 recovery codes. Each code works once. Store them in your password manager or print them; we can't show them again.
## Lost your phone?
If you lose your phone, choose Use a recovery code on the sign-in page and enter one of your codes. If you have no codes left, ask your workspace admin to reset two-step verification for your account. After a reset you set it up again on your new phone.
## For admins
Admins can require two-step verification for everyone in Settings > Security > Policies. People who haven't set it up are asked to do so the next time they sign in.`;const embed =awaitpipeline("feature-extraction","Xenova/all-MiniLM-L6-v2",{dtype:"q8"});constvectorsOf=async(texts)=>(awaitembed(texts,{pooling:"mean",normalize:true})).tolist();constcosine=(a, b)=> a.reduce((s, x, i)=> s + x * b[i],0);consttokens=(text)=> embed.tokenizer.encode(text).length;const body = article.split("\n").filter((l)=>!l.startsWith("#")).join(" ");const sentences = body.match(/[^.?!]+[.?!]/g).map((s)=> s.trim());// Strategy 1: fixed size. Every 35 words, with 5 words of overlap between neighbours.functionfixedSize(size =35, overlap =5){const words = body.split(/\s+/);const out =[];for(let start =0; start < words.length; start += size - overlap){
out.push(words.slice(start, start + size).join(" "));if(start + size >= words.length)break;}return out;}// Strategy 2: by structure. One chunk per "## " section, with the article and section title kept as a prefix.constbyStructure=()=>
article.split("\n## ").slice(1).map((section)=>{const[heading,...lines]= section.split("\n");return`Two-step verification > ${heading}: ${lines.join(" ")}`;});// Strategy 3: semantic. Start a new chunk where a sentence is unlike the one before it.asyncfunctionsemantic(threshold =0.3){const vectors =awaitvectorsOf(sentences);const out =[[sentences[0]]];for(let i =1; i < sentences.length; i++){if(cosine(vectors[i -1], vectors[i])< threshold) out.push([]);
out.at(-1).push(sentences[i]);}return out.map((group)=> group.join(" "));}const question ="I lost my phone and used all my codes, how do I get back in?";const[q]=awaitvectorsOf([question]);const mustContain =["no codes left","admin to reset"];// the full answer needs this sentencefor(const[name, chunks]of[["fixed size",fixedSize()],["by structure",byStructure()],["semantic",awaitsemantic()]]){const scored =(awaitvectorsOf(chunks)).map((v, i)=>({text: chunks[i],score:cosine(q, v)}));const best = scored.sort((a, b)=> b.score - a.score)[0];const complete = mustContain.every((m)=> best.text.includes(m));
console.log(`\n${name}: ${chunks.length} chunks of ${chunks.map(tokens).join(", ")} tokens`);
console.log(` best match (${best.score.toFixed(3)}), ${complete ?"contains the full answer":"MISSES part of the answer"}:`);
console.log(` "${best.text}"`);}
Result
fixed size: 5 chunks of 47, 51, 46, 47, 32 tokens
best match (0.671), MISSES part of the answer:
"print them; we can't show them again. If you lose your phone, choose Use a recovery code on the sign-in page and enter one of your codes. If you have no codes left, ask your"
by structure: 4 chunks of 63, 47, 72, 48 tokens
best match (0.646), contains the full answer:
"Two-step verification > Lost your phone?: If you lose your phone, choose Use a recovery code on the sign-in page and enter one of your codes. If you have no codes left, ask your workspace admin to reset two-step verification for your account. After a reset you set it up again on your new phone."
semantic: 5 chunks of 15, 11, 51, 80, 39 tokens
best match (0.714), contains the full answer:
"Store them in your password manager or print them; we can't show them again. If you lose your phone, choose Use a recovery code on the sign-in page and enter one of your codes. If you have no codes left, ask your workspace admin to reset two-step verification for your account. After a reset you set it up again on your new phone."
What’s happening
The article has four ## sections. body is the text without headings (what fixed-size and semantic chunking see); sentences splits it at full stops for the semantic chunker. The question needs the sentence "If you have no codes left, ask your workspace admin to reset…", so mustContain checks the best chunk has it.
Fixed size (35 words, 5 overlap) makes 5 chunks of 32–51 tokens. The best match scores 0.671 but misses part of the answer: it ends "…If you have no codes left, ask your", cut mid-sentence. The next chunk has the rest, but it scores lower, so a top-1 or top-2 retriever may never send it. Shift the boundary by a few words and the answer might land whole: fixed-size chunking makes success depend on luck.
By structure makes one chunk per section (47–72 tokens), each prefixed with Two-step verification > [heading]. The "Lost your phone?" section is the best match (0.646) and contains the whole answer, because the author kept the procedure in one section.
Semantic splits where adjacent sentences have cosine below 0.3, giving 5 uneven chunks (11 to 80 tokens). Its best match scores highest (0.714) and contains the answer, but it glued "Store them in your password manager…" from the previous section onto the start: semantic boundaries are approximate.
For structured content like this, chunking by structure is the safest default; use semantic chunking for long unstructured text, and fixed size when you have nothing better. Whatever you choose, measure it: the scores here (0.646 to 0.714) say little on their own; recall on a labelled set says whether the right chunk comes back.
AdvancedPractical chunking rules
Respect the embedding model's limit, with room to spare: a 512-token model shouldn't get 500-token chunks plus a 100-token prefix.
Never split code blocks, tables or list items in the middle; a half table is worse than a long chunk. Split long tables by rows and repeat the header row in each piece.
Keep a heading path prefix and the document title in the chunk text (or embed it with the chunk): it costs a few tokens and disambiguates short sections.
Store chunk boundaries and ids that survive re-ingestion, such as a hash of document id plus section path, so updating one article replaces only its chunks and citations stay stable.
Deduplicate: boilerplate (footers, cookie banners, "Was this helpful?") repeated in every page pollutes every search; strip it during ingestion.
PDFs and HTML need cleaning first: reading order, headers and footers, hyphenation and tables are where most real-world chunking quality is lost. Anthropic's API can read PDFs directly (Images, PDFs and files), which helps when you send whole documents rather than chunks.
?Overlap
Why do fixed-size chunkers repeat the last few words of each chunk at the start of the next, and why didn't 5 words of overlap save the example?
Show answer
Overlap lets a sentence that straddles a boundary appear whole in one chunk; 5 words is shorter than the sentence that was split.
What’s happening
Without overlap, a sentence crossing a boundary is split in two, and neither half embeds its meaning well.
With overlap of M words, the last M words of chunk k are repeated at the start of chunk k + 1, so any sentence shorter than M words that crosses the boundary appears complete in chunk k + 1.
The answer sentence ("If you have no codes left, ask your workspace admin to reset two-step verification for your account.") is 18 words. With 5 words of overlap it can't fit, so it was still split.
More overlap (say 20%) helps but stores more duplicate text; splitting at sentence or section boundaries avoids the problem entirely, which is why structure-aware chunking is usually better.
Vector search and keyword search fail in opposite places (Keyword search still matters): embeddings find paraphrases but blur exact tokens like error codes and product names; BM25 nails exact tokens but misses different wording. Hybrid search runs both and merges the results, so a query gets the best of each.
Merging is the tricky part, because the scores aren't comparable: a cosine of 0.44 and a BM25 score of 3.6 measure different things on different scales. Reciprocal rank fusion (RRF), from Cormack, Clarke and Büttcher (2009), sidesteps scores entirely and uses only ranks: each list gives every document it returns 1 / (k + rank), the contributions are added, and documents are sorted by the total. With the conventional k = 60, rank 1 is worth 1/61 ≈ 0.0164, rank 2 1/62 ≈ 0.0161, and so on, so being near the top of both lists beats being first in one. No tuning, no score normalisation, and it works for any number of lists (it's also how multi-query results are merged).
The mental model is two judges ranking contestants. Their marking scales differ, so you can't add their scores; you can add points by position. A contestant both judges put near the top wins over one that a single judge loved and the other ignored.
The example runs BM25 and dense retrieval over the help centre, fuses them with RRF, and counts how often each method gets the answer into the top 1, 3 and 5 over the 20 labelled questions.
hybrid.mjs
import{ pipeline }from"@huggingface/transformers";// The Meadowlark help centre (a fictional team-calendar app): 34 chunks, one per section.const chunks =[["p1","Plans and pricing","Meadowlark has three plans. Free covers up to 3 people. Team costs £8 per person per month. Business costs £15 per person per month and adds single sign-on (SSO) and the API."],["p2","Plans and pricing","Paying yearly gives you 12 months for the price of 10. Switch between monthly and yearly billing at any time in Settings > Billing."],["r1","Refunds","Monthly plans are not refunded for unused days. When you cancel, your plan stays active until the end of the month you have paid for."],["r2","Refunds","Yearly plans can be refunded within 30 days of the start or renewal date. We refund the unused months, pro rata."],["r3","Refunds","Refunds go back to the card you paid with and usually arrive within 5 to 10 working days."],["a1","Resetting your password","Choose Forgot password on the sign-in page and enter your work email. We send a reset link that expires after 30 minutes."],["a2","Resetting your password","If your company signs in with SSO, Meadowlark does not store a password for you: reset it with your identity provider, such as Okta or Google Workspace."],["a3","Two-step verification","Turn on two-step verification in Settings > Security. Meadowlark works with authenticator apps such as Google Authenticator and 1Password."],["a4","Two-step verification","You get 10 recovery codes, each usable once. If you lose your phone, sign in with a recovery code or ask your workspace admin to reset two-step verification."],["i1","Google Calendar sync","Connect Google Calendar in Settings > Integrations. Events sync both ways every 5 minutes."],["i2","Google Calendar sync","Private Google events appear in Meadowlark as Busy, without their title or attendees."],["i3","Google Calendar sync","Error GC-403 means Meadowlark lost permission to read your calendar, usually after a Google password change. Reconnect the calendar to fix it."],["i4","Slack notifications","Install the Meadowlark app for Slack from Settings > Integrations. A Slack workspace admin may need to approve it."],["i5","Slack notifications","Meadowlark sends a Slack reminder 10 minutes before each meeting. Type /meadowlark today to see your schedule."],["s1","Booking links","A booking link lets people outside your company pick a free slot in your calendar. Create one from the Booking links page."],["s2","Booking links","You can add buffer time before and after booked meetings, from 5 to 60 minutes."],["s3","Booking links","The Team plan includes up to 5 booking links per person; Business has no limit."],["d1","Exporting your data","Admins can export every calendar and booking as CSV or ICS files from Settings > Data. Export files stay available for 7 days."],["d2","Exporting your data","Business plans can also read data through the REST API, with up to 100 requests per minute per workspace."],["d3","Deleting your workspace","Only the workspace owner can delete a workspace. A deleted workspace can be restored for 14 days; after that, all data is permanently erased."],["e1","Error messages","E401 means your session expired. Sign in again; if it keeps happening, check that your browser allows cookies from meadowlark.example."],["e2","Error messages","E429 means too many requests in a short time. Wait a minute and try again; API clients should slow down and retry with backoff."],["m1","Mobile apps","Meadowlark has an iPhone app in the App Store. It shows your schedule and booking links and sends meeting reminders."],["m2","Mobile apps","On Android, use Meadowlark in your phone's browser; you can add it to your home screen for an app-like experience."],["b1","Invoices and payment","Invoices are emailed to the billing contact on the first day of each billing period. Download past invoices from Settings > Billing > Invoices."],["b2","Invoices and payment","To change the card we charge, open Settings > Billing and choose Update payment method. We accept Visa, Mastercard and American Express."],["a5","Changing your email","Change the email address you sign in with from Profile > Account. We send a confirmation link to the new address before the change takes effect."],["o1","Outlook calendar sync","Connect Outlook or Microsoft 365 in Settings > Integrations. Outlook events sync both ways every 10 minutes."],["o2","Outlook calendar sync","Error OC-401 means your Microsoft sign-in expired. Sign in to Microsoft again from Settings > Integrations to resume syncing."],["t1","Microsoft Teams notifications","Add the Meadowlark app to Microsoft Teams to get meeting reminders and a daily agenda in a Teams chat."],["s4","Booking links","People who book through your link get a confirmation email with links to reschedule or cancel, up to 2 hours before the meeting."],["s5","Booking links","Booking pages show free slots in the visitor's own time zone, detected from their browser."],["e3","Error messages","E403 means your role does not allow this action. Ask a workspace admin to change your role or do it for you."],["n1","Notifications","Turn meeting reminders off, or change how early they arrive, in Profile > Notifications. Each channel (email, Slack, Teams, mobile) has its own setting."],].map(([id, title, text])=>({ id, title, text }));// A small labelled set: 20 realistic questions, each with the chunk that answers it.const labelled =[["The password email you sent me doesn't work any more","a1"],["I log in through Okta. How do I change my password?","a2"],["can't log in, it says my code is wrong","a4"],["I was charged after I cancelled","r1"],["refund for annual subscription","r2"],["How long until a refund reaches my card?","r3"],["is SSO on the cheaper plan?","p1"],["Is there a discount for paying annually?","p2"],["how do I give our developers API access","d2"],["What does GC-403 mean?","i3"],["OC-401","o2"],["I keep getting E429","e2"],["it says I'm not allowed to do that","e3"],["outlook stopped updating","o2"],["the meeting reminder comes too late","n1"],["how do I move a meeting someone booked with me","s4"],["visitors see the wrong times on my booking page","s5"],["Can clients pick a meeting time themselves?","s1"],["I need receipts for my expenses","b1"],["Is there an Android app?","m2"],].map(([question, answer])=>({ question, answer }));// Dense retrieval: cosine similarity of all-MiniLM-L6-v2 embeddings.const embed =awaitpipeline("feature-extraction","Xenova/all-MiniLM-L6-v2",{dtype:"q8"});const vectors =(awaitembed(chunks.map((c)=> c.text),{pooling:"mean",normalize:true})).tolist();asyncfunctiondense(query){const[q]=(awaitembed([query],{pooling:"mean",normalize:true})).tolist();return vectors.map((v, i)=>({id: chunks[i].id,score: v.reduce((s, x, d)=> s + x * q[d],0)})).sort((a, b)=> b.score - a.score);}// Keyword retrieval: BM25 (as in chapter 5), with a small stop-word list; only chunks that match a term are returned.constSTOP=newSet("a an and are as at be by can do does for from get how i i'm in is it me my of on or our so that the this to was we what when where why with you your".split(" "));consttokenize=(t)=>(t.toLowerCase().match(/[a-z0-9]+(?:-[a-z0-9]+)*/g)??[]).filter((w)=>!STOP.has(w));const docs = chunks.map((c)=>tokenize(c.text));const avgLength = docs.reduce((s, d)=> s + d.length,0)/ docs.length;const docFreq =newMap();for(const d of docs)for(const t ofnewSet(d)) docFreq.set(t,(docFreq.get(t)??0)+1);functionbm25(query, k1 =1.2, b =0.75){const terms =tokenize(query);return docs.map((d, i)=>{let score =0;for(const t of terms){const df = docFreq.get(t);if(!df)continue;const tf = d.filter((x)=> x === t).length;
score +=(Math.log(1+(docs.length - df +0.5)/(df +0.5))* tf *(k1 +1))/(tf + k1 *(1- b +(b * d.length)/ avgLength));}return{id: chunks[i].id, score };}).filter((r)=> r.score >0).sort((a, b)=> b.score - a.score);}// Reciprocal rank fusion: each list adds 1 / (k + rank) for every chunk it ranks. Scores never mix, only ranks.functionrrf(lists, k =60){const fused =newMap();for(const list of lists) list.forEach(({ id }, rank)=> fused.set(id,(fused.get(id)??0)+1/(k + rank +1)));return[...fused].map(([id, score])=>({ id, score })).sort((a, b)=> b.score - a.score);}constrankOf=(list, id)=>{const i = list.findIndex((r)=> r.id === id);return i ===-1?"-":String(i +1);};for(const{ question, answer }of labelled.filter((l)=>["can't log in, it says my code is wrong","how do I give our developers API access","I need receipts for my expenses"].includes(l.question))){const b =bm25(question).slice(0,10), d =(awaitdense(question)).slice(0,10), h =rrf([b, d]);
console.log(`\n"${question}" (answer: ${answer})`);
console.log(` rank of the answer: BM25 ${rankOf(b, answer)}, dense ${rankOf(d, answer)}, fused ${rankOf(h, answer)}`);
console.log(` fused top 3: ${h.slice(0,3).map((r)=>`${r.id}${r.score.toFixed(4)}`).join(", ")}`);}const hits ={BM25:[0,0,0],dense:[0,0,0],hybrid:[0,0,0]};for(const{ question, answer }of labelled){const b =bm25(question).slice(0,10), d =(awaitdense(question)).slice(0,10);for(const[name, list]of[["BM25", b],["dense", d],["hybrid",rrf([b, d])]])[1,3,5].forEach((k, j)=>(hits[name][j]+= list.slice(0, k).some((r)=> r.id === answer)?1:0));}
console.log(`\nanswer found in the top k, out of ${labelled.length} questions:`);for(const[name,[h1, h3, h5]]of Object.entries(hits)) console.log(`${name.padEnd(7)} top 1: ${h1} top 3: ${h3} top 5: ${h5}`);
Result
"can't log in, it says my code is wrong" (answer: a4)
rank of the answer: BM25 1, dense 3, fused 1
fused top 3: a4 0.0323, e1 0.0164, a1 0.0161
"how do I give our developers API access" (answer: d2)
rank of the answer: BM25 1, dense 5, fused 1
fused top 3: d2 0.0318, e2 0.0313, p1 0.0306
"I need receipts for my expenses" (answer: b1)
rank of the answer: BM25 -, dense 1, fused 2
fused top 3: i4 0.0164, b1 0.0164, m1 0.0161
answer found in the top k, out of 20 questions:
BM25 top 1: 11 top 3: 13 top 5: 15
dense top 1: 14 top 3: 18 top 5: 19
hybrid top 1: 11 top 3: 19 top 5: 20
What’s happening
dense and bm25 each return a ranked list; BM25 drops chunks that match no query term (score 0), and a small stop-word list stops words like "how" and "my" from scoring. Each list is cut to its top 10 before fusing, as a real system would.
rrf adds 1 / (60 + rank) per list (ranks counted from 1). For "can't log in, it says my code is wrong", BM25 has the answer a4 first (it matches the rare word "code") and dense third, so a4 gets 1/61 + 1/63 = 0.0323 and wins clearly; e1, first in dense, only appears in one list and scores 0.0164.
For "how do I give our developers API access", dense ranks the answer d2 fifth (it sees "access" and drifts to integration articles), but BM25 matches "API" exactly and ranks it first, so fusion puts d2 first.
For "I need receipts for my expenses", BM25 matches nothing useful ("need" appears in an unrelated Slack chunk) while dense finds b1 first. Both lists' first places score exactly 1/61, a tie, and the BM25 one happens to come first. Fusion can't tell a confident keyword hit from a junk one.
Over all 20 questions: dense gets 14 answers first, BM25 11, hybrid 11, but hybrid gets the answer into the top 3 for 19 questions and the top 5 for all 20. That's the pattern to expect: fusion raises recall (the answer is somewhere near the top more often) but can blur the very top. Which is exactly why a reranker usually follows fusion.
AdvancedTuning hybrid search
Weighted RRF: multiply each list's contribution by a weight when one retriever is consistently better on your data (or for a query type, such as anything that looks like an error code). Tune the weights on your labelled set, not by intuition.
Score-based fusion (normalise each list's scores to 0–1 and add with weights) can beat RRF when the score distributions are stable, but it breaks when they shift, for example after changing the embedding model. RRF is the robust default.
How many from each list: fuse the top 20–100 from each retriever, then rerank. Fusing only the top 3 throws away exactly the candidates fusion was meant to rescue.
Where it runs: Elasticsearch, OpenSearch and several vector databases offer hybrid queries with RRF built in; in PostgreSQL you can run a pgvector query and a full-text query and fuse them in SQL or in your application code.
?Fuse by hand
A chunk is ranked 2nd by BM25 and 4th by dense retrieval. Another is 1st by dense and absent from BM25's list. Which wins with RRF (k = 60)?
Second chunk: 1/(60 + 1) = 0.01639 from dense, nothing from BM25.
Appearing near the top of both lists beats topping one list: even if the first chunk were 30th in the dense list, it would score 1/62 + 1/90 = 0.0272 and still beat a single first place (0.0164).
That's the design: agreement between independent retrievers is strong evidence of relevance. It's also the weakness seen with "receipts": a junk keyword hit at rank 1 counts as much as a real semantic hit at rank 1.
The first retrieval stage has to be fast over millions of chunks, so it uses a bi-encoder: the question and each chunk are embedded separately and compared with a dot product. That's cheap (chunk vectors are computed once, ahead of time) but crude: the model never sees the question and the chunk together, so it can't notice that "access" in the question means API access, or that a chunk answers a slightly different question. A reranker is a second stage that reads each candidate together with the question and scores relevance properly, then reorders the shortlist.
The standard reranker is a cross-encoder: one transformer gets the question and the chunk as a single input ([CLS] question [SEP] chunk [SEP]), so attention flows between every question word and every chunk word, and a small head outputs one relevance score. The example uses ms-marco-MiniLM-L-6-v2, a small open cross-encoder trained on the MS MARCO passage-ranking dataset. Hosted rerankers do the same job as an API (Voyage AI's rerank-3 and rerank-3-lite are listed in Anthropic's embeddings documentation, December 2026), and you can also use an LLM as a reranker, at higher cost.
Cross-encoders are far more accurate than bi-encoders and far slower: one forward pass per candidate at query time, with nothing precomputed. So the pattern is always retrieve many cheaply, rerank few carefully: retrieve 20–150 candidates, rerank, keep the top 3–20. Anthropic's contextual retrieval write-up, for example, retrieved 150 candidates and reranked them down to 20.
The mental model is CV screening and interviews. The bi-encoder is the keyword-and-summary screen that cuts 10,000 applications to 20 in seconds; the cross-encoder is the interview, which actually reads each candidate against the job and is too slow to give to everyone.
The example retrieves 10 candidates for two questions with the bi-encoder and reranks them with the cross-encoder.
rerank.mjs
import{ pipeline, AutoTokenizer, AutoModelForSequenceClassification }from"@huggingface/transformers";// The Meadowlark help centre (a fictional team-calendar app): 34 chunks, one per section.const chunks =[["p1","Plans and pricing","Meadowlark has three plans. Free covers up to 3 people. Team costs £8 per person per month. Business costs £15 per person per month and adds single sign-on (SSO) and the API."],["p2","Plans and pricing","Paying yearly gives you 12 months for the price of 10. Switch between monthly and yearly billing at any time in Settings > Billing."],["r1","Refunds","Monthly plans are not refunded for unused days. When you cancel, your plan stays active until the end of the month you have paid for."],["r2","Refunds","Yearly plans can be refunded within 30 days of the start or renewal date. We refund the unused months, pro rata."],["r3","Refunds","Refunds go back to the card you paid with and usually arrive within 5 to 10 working days."],["a1","Resetting your password","Choose Forgot password on the sign-in page and enter your work email. We send a reset link that expires after 30 minutes."],["a2","Resetting your password","If your company signs in with SSO, Meadowlark does not store a password for you: reset it with your identity provider, such as Okta or Google Workspace."],["a3","Two-step verification","Turn on two-step verification in Settings > Security. Meadowlark works with authenticator apps such as Google Authenticator and 1Password."],["a4","Two-step verification","You get 10 recovery codes, each usable once. If you lose your phone, sign in with a recovery code or ask your workspace admin to reset two-step verification."],["i1","Google Calendar sync","Connect Google Calendar in Settings > Integrations. Events sync both ways every 5 minutes."],["i2","Google Calendar sync","Private Google events appear in Meadowlark as Busy, without their title or attendees."],["i3","Google Calendar sync","Error GC-403 means Meadowlark lost permission to read your calendar, usually after a Google password change. Reconnect the calendar to fix it."],["i4","Slack notifications","Install the Meadowlark app for Slack from Settings > Integrations. A Slack workspace admin may need to approve it."],["i5","Slack notifications","Meadowlark sends a Slack reminder 10 minutes before each meeting. Type /meadowlark today to see your schedule."],["s1","Booking links","A booking link lets people outside your company pick a free slot in your calendar. Create one from the Booking links page."],["s2","Booking links","You can add buffer time before and after booked meetings, from 5 to 60 minutes."],["s3","Booking links","The Team plan includes up to 5 booking links per person; Business has no limit."],["d1","Exporting your data","Admins can export every calendar and booking as CSV or ICS files from Settings > Data. Export files stay available for 7 days."],["d2","Exporting your data","Business plans can also read data through the REST API, with up to 100 requests per minute per workspace."],["d3","Deleting your workspace","Only the workspace owner can delete a workspace. A deleted workspace can be restored for 14 days; after that, all data is permanently erased."],["e1","Error messages","E401 means your session expired. Sign in again; if it keeps happening, check that your browser allows cookies from meadowlark.example."],["e2","Error messages","E429 means too many requests in a short time. Wait a minute and try again; API clients should slow down and retry with backoff."],["m1","Mobile apps","Meadowlark has an iPhone app in the App Store. It shows your schedule and booking links and sends meeting reminders."],["m2","Mobile apps","On Android, use Meadowlark in your phone's browser; you can add it to your home screen for an app-like experience."],["b1","Invoices and payment","Invoices are emailed to the billing contact on the first day of each billing period. Download past invoices from Settings > Billing > Invoices."],["b2","Invoices and payment","To change the card we charge, open Settings > Billing and choose Update payment method. We accept Visa, Mastercard and American Express."],["a5","Changing your email","Change the email address you sign in with from Profile > Account. We send a confirmation link to the new address before the change takes effect."],["o1","Outlook calendar sync","Connect Outlook or Microsoft 365 in Settings > Integrations. Outlook events sync both ways every 10 minutes."],["o2","Outlook calendar sync","Error OC-401 means your Microsoft sign-in expired. Sign in to Microsoft again from Settings > Integrations to resume syncing."],["t1","Microsoft Teams notifications","Add the Meadowlark app to Microsoft Teams to get meeting reminders and a daily agenda in a Teams chat."],["s4","Booking links","People who book through your link get a confirmation email with links to reschedule or cancel, up to 2 hours before the meeting."],["s5","Booking links","Booking pages show free slots in the visitor's own time zone, detected from their browser."],["e3","Error messages","E403 means your role does not allow this action. Ask a workspace admin to change your role or do it for you."],["n1","Notifications","Turn meeting reminders off, or change how early they arrive, in Profile > Notifications. Each channel (email, Slack, Teams, mobile) has its own setting."],].map(([id, title, text])=>({ id, title, text }));// First stage: a bi-encoder embeds question and chunks separately; similarity is one dot product.const embed =awaitpipeline("feature-extraction","Xenova/all-MiniLM-L6-v2",{dtype:"q8"});const vectors =(awaitembed(chunks.map((c)=> c.text),{pooling:"mean",normalize:true})).tolist();asyncfunctionretrieve(question, k){const[q]=(awaitembed([question],{pooling:"mean",normalize:true})).tolist();return vectors.map((v, i)=>({chunk: chunks[i],cosine: v.reduce((s, x, d)=> s + x * q[d],0)})).sort((a, b)=> b.cosine - a.cosine).slice(0, k);}// Second stage: a cross-encoder reads "[question] [SEP] [chunk]" as one input and outputs one relevance score.const tokenizer =await AutoTokenizer.from_pretrained("Xenova/ms-marco-MiniLM-L-6-v2");const crossEncoder =await AutoModelForSequenceClassification.from_pretrained("Xenova/ms-marco-MiniLM-L-6-v2",{dtype:"q8"});asyncfunctionrerank(question, candidates){const inputs =tokenizer(candidates.map(()=> question),{text_pair: candidates.map((c)=> c.chunk.text),padding:true,truncation:true});const{ logits }=awaitcrossEncoder(inputs);// shape [candidates, 1]: one raw score eachreturn candidates.map((c, i)=>({...c,score: logits.data[i]})).sort((a, b)=> b.score - a.score);}for(const[question, answer]of[["how do I give our developers API access","d2"],["the meeting reminder comes too late","n1"]]){const candidates =awaitretrieve(question,10);const reranked =awaitrerank(question, candidates);
console.log(`\n"${question}" (answer: ${answer})`);
console.log(`${"first stage (cosine)".padEnd(44)}after reranking (cross-encoder)`);for(let i =0; i <4; i++){const a = candidates[i], b = reranked[i];const left =`${i +1}. ${a.chunk.id}${a.cosine.toFixed(3)}${a.chunk.title}`.padEnd(44);
console.log(`${left}${i +1}. ${b.chunk.id}${b.score.toFixed(2).padStart(6)}${b.chunk.title}`);}}
Result
"how do I give our developers API access" (answer: d2)
first stage (cosine) after reranking (cross-encoder)
1. i4 0.338 Slack notifications 1. d2 -8.25 Exporting your data
2. t1 0.279 Microsoft Teams notifications 2. e2 -8.99 Error messages
3. a3 0.255 Two-step verification 3. p1 -11.14 Plans and pricing
4. e3 0.235 Error messages 4. a3 -11.22 Two-step verification
"the meeting reminder comes too late" (answer: n1)
first stage (cosine) after reranking (cross-encoder)
1. n1 0.585 Notifications 1. n1 2.09 Notifications
2. i5 0.573 Slack notifications 2. i5 2.07 Slack notifications
3. s4 0.523 Booking links 3. t1 -4.39 Microsoft Teams notifications
4. t1 0.492 Microsoft Teams notifications 4. m1 -5.03 Mobile apps
What’s happening
retrieve is the first stage: cosine similarity between separately computed vectors, top 10. rerank builds 10 inputs that each pair the question with one candidate (text_pair), runs the cross-encoder once over the batch, and reads one logit per pair from logits.data.
"how do I give our developers API access": the bi-encoder's top four are Slack, Teams, two-step verification and an error message: all about "access" or "setup" in a loose sense, none about the API. The cross-encoder puts d2 ("Business plans can also read data through the REST API…") first at −8.25, from fifth place. Reading question and chunk together lets it match "API access" to "read data through the REST API".
The scores are raw logits (−8.25, −8.99, −11.14…). They're only meaningful relative to each other for the same question; don't compare them across questions or use a fixed threshold without calibrating on your data.
"the meeting reminder comes too late": both stages put n1 ("change how early they arrive") first, but the cross-encoder's margin over i5 (the Slack reminder timing) is 0.02 (2.09 vs 2.07): a near tie. On another run with a different batch it went the other way, because the 8-bit model's numbers shift slightly with batch contents (see Choosing an embedding model). Rerankers improve the order on average, not on every question.
On the full labelled set (Evaluating retrieval) reranking lifts the share of questions with the answer first from 0.70 to 0.85 for dense retrieval. That's the reason to pay for it: the model is usually given only the top few chunks, so order is what matters.
AdvancedGotcha: the reranker's cost
?Why not rerank everything?
If cross-encoders are more accurate, why not skip the vector index and score every chunk with the cross-encoder?
Show answer
Because it needs one forward pass per chunk per query, with nothing precomputed: millions of passes per question.
What’s happening
A bi-encoder embeds each chunk once at ingest time; a query then costs one embedding plus fast vector maths, and an ANN index avoids even most of that.
A cross-encoder's score depends on the query, so nothing can be computed ahead of time: scoring 1 million chunks means 1 million transformer passes for every question, seconds to minutes of GPU time.
So the stages split the work: cheap, approximate recall over everything, then expensive, accurate ranking over a few dozen candidates.
The cost of a mistake moves too: if the first stage misses the right chunk entirely, the reranker never sees it. That's why first-stage recall@50 matters even though the user only sees the top 5.
Users don't write good search queries. They write follow-ups that depend on the conversation ("and what about the yearly one?"), vague descriptions ("can outsiders grab a slot in my diary?") and broad complaints that could mean several things ("my calendar isn't updating"). Query transformation uses a model to turn the user's message into better search input before retrieval runs. Three techniques cover most cases:
Conversational rewriting: rewrite the latest message as a standalone question using the conversation so far. Essential for any chat-style RAG; without it, every follow-up is searched as a fragment.
HyDE (hypothetical document embeddings, Gao and colleagues, 2022): ask a model to write a plausible answer, then embed that instead of the question. Answers look like documents, so their embeddings land nearer the real documents than a short question does. The hypothetical answer may be wrong; it's only used for search, never shown.
Multi-query: generate several different queries for one question, search each, and fuse the results with RRF. It covers ambiguous questions from several angles and raises recall.
All three add a model call before retrieval (latency and cost), so use a small fast model at low effort, and skip the step when the message is already a clear standalone query.
The mental model is a reference librarian who rephrases your question before searching: "and the yearly one?" becomes "refund policy for yearly plans"; "the thing where outsiders book me" becomes a sketch of what the right page would say; "my calendar's broken" becomes three searches, one for each likely cause.
The example shows each technique with real retrieval over the help centre; the rewrites themselves come from scripted replies.
query-rewrite.mjs
import Anthropic from"@anthropic-ai/sdk";import{ pipeline }from"@huggingface/transformers";// Scripted replies (see "How these examples run") ---------------------------------------------// Three replies in the documented response shape; the model's words were written for the example.constmessage=(text)=>({id:"msg_01Hq7WcV3nT9pYz2KdL6sR4B",type:"message",role:"assistant",content:[{type:"text", text }],model:"claude-haiku-5-5",stop_reason:"end_turn",stop_sequence:null,usage:{input_tokens:96,output_tokens:24},});const replies =[message("Can I get a refund on a yearly plan?"),message("Yes. Create a booking link and share it, and people outside your company can choose a free time in your calendar."),message("Google Calendar events are not syncing\nOutlook calendar stopped syncing\ncalendar sync error after changing password"),];constfetch=async()=> Response.json(replies.shift());const client =newAnthropic({apiKey:"sk-ant-test", fetch });// for real: new Anthropic()// ----------------------------------------------------------------------------------------------// The Meadowlark help centre (a fictional team-calendar app): 34 chunks, one per section.const chunks =[["p1","Plans and pricing","Meadowlark has three plans. Free covers up to 3 people. Team costs £8 per person per month. Business costs £15 per person per month and adds single sign-on (SSO) and the API."],["p2","Plans and pricing","Paying yearly gives you 12 months for the price of 10. Switch between monthly and yearly billing at any time in Settings > Billing."],["r1","Refunds","Monthly plans are not refunded for unused days. When you cancel, your plan stays active until the end of the month you have paid for."],["r2","Refunds","Yearly plans can be refunded within 30 days of the start or renewal date. We refund the unused months, pro rata."],["r3","Refunds","Refunds go back to the card you paid with and usually arrive within 5 to 10 working days."],["a1","Resetting your password","Choose Forgot password on the sign-in page and enter your work email. We send a reset link that expires after 30 minutes."],["a2","Resetting your password","If your company signs in with SSO, Meadowlark does not store a password for you: reset it with your identity provider, such as Okta or Google Workspace."],["a3","Two-step verification","Turn on two-step verification in Settings > Security. Meadowlark works with authenticator apps such as Google Authenticator and 1Password."],["a4","Two-step verification","You get 10 recovery codes, each usable once. If you lose your phone, sign in with a recovery code or ask your workspace admin to reset two-step verification."],["i1","Google Calendar sync","Connect Google Calendar in Settings > Integrations. Events sync both ways every 5 minutes."],["i2","Google Calendar sync","Private Google events appear in Meadowlark as Busy, without their title or attendees."],["i3","Google Calendar sync","Error GC-403 means Meadowlark lost permission to read your calendar, usually after a Google password change. Reconnect the calendar to fix it."],["i4","Slack notifications","Install the Meadowlark app for Slack from Settings > Integrations. A Slack workspace admin may need to approve it."],["i5","Slack notifications","Meadowlark sends a Slack reminder 10 minutes before each meeting. Type /meadowlark today to see your schedule."],["s1","Booking links","A booking link lets people outside your company pick a free slot in your calendar. Create one from the Booking links page."],["s2","Booking links","You can add buffer time before and after booked meetings, from 5 to 60 minutes."],["s3","Booking links","The Team plan includes up to 5 booking links per person; Business has no limit."],["d1","Exporting your data","Admins can export every calendar and booking as CSV or ICS files from Settings > Data. Export files stay available for 7 days."],["d2","Exporting your data","Business plans can also read data through the REST API, with up to 100 requests per minute per workspace."],["d3","Deleting your workspace","Only the workspace owner can delete a workspace. A deleted workspace can be restored for 14 days; after that, all data is permanently erased."],["e1","Error messages","E401 means your session expired. Sign in again; if it keeps happening, check that your browser allows cookies from meadowlark.example."],["e2","Error messages","E429 means too many requests in a short time. Wait a minute and try again; API clients should slow down and retry with backoff."],["m1","Mobile apps","Meadowlark has an iPhone app in the App Store. It shows your schedule and booking links and sends meeting reminders."],["m2","Mobile apps","On Android, use Meadowlark in your phone's browser; you can add it to your home screen for an app-like experience."],["b1","Invoices and payment","Invoices are emailed to the billing contact on the first day of each billing period. Download past invoices from Settings > Billing > Invoices."],["b2","Invoices and payment","To change the card we charge, open Settings > Billing and choose Update payment method. We accept Visa, Mastercard and American Express."],["a5","Changing your email","Change the email address you sign in with from Profile > Account. We send a confirmation link to the new address before the change takes effect."],["o1","Outlook calendar sync","Connect Outlook or Microsoft 365 in Settings > Integrations. Outlook events sync both ways every 10 minutes."],["o2","Outlook calendar sync","Error OC-401 means your Microsoft sign-in expired. Sign in to Microsoft again from Settings > Integrations to resume syncing."],["t1","Microsoft Teams notifications","Add the Meadowlark app to Microsoft Teams to get meeting reminders and a daily agenda in a Teams chat."],["s4","Booking links","People who book through your link get a confirmation email with links to reschedule or cancel, up to 2 hours before the meeting."],["s5","Booking links","Booking pages show free slots in the visitor's own time zone, detected from their browser."],["e3","Error messages","E403 means your role does not allow this action. Ask a workspace admin to change your role or do it for you."],["n1","Notifications","Turn meeting reminders off, or change how early they arrive, in Profile > Notifications. Each channel (email, Slack, Teams, mobile) has its own setting."],].map(([id, title, text])=>({ id, title, text }));const embed =awaitpipeline("feature-extraction","Xenova/all-MiniLM-L6-v2",{dtype:"q8"});const vectors =(awaitembed(chunks.map((c)=> c.text),{pooling:"mean",normalize:true})).tolist();asyncfunctionsearch(text, k =4){const[q]=(awaitembed([text],{pooling:"mean",normalize:true})).tolist();return vectors.map((v, i)=>({id: chunks[i].id,score: v.reduce((s, x, d)=> s + x * q[d],0)})).sort((a, b)=> b.score - a.score).slice(0, k);}constshow=(results)=> results.map((r)=>`${r.id}${r.score.toFixed(2)}`).join(", ");asyncfunctionask(system, content){const res =await client.messages.create({model:"claude-haiku-5-5",// a small, fast model is enough for rewritingmax_tokens:200,output_config:{effort:"low"},
system,messages:[{role:"user", content }],});return res.content.find((b)=> b.type ==="text").text.trim();}// 1. Conversational rewrite: turn a follow-up into a question that stands on its own.const history ="User: Can I get a refund on my monthly plan?\nAssistant: Monthly plans aren't refunded for unused days.";const followUp ="and what about the yearly one?";const standalone =awaitask("Rewrite the user's last message as a standalone search query for a help centre. Reply with the query only.",`<conversation>\n${history}\n</conversation>\n<last_message>${followUp}</last_message>`,);
console.log(`follow-up as typed: ${show(awaitsearch(followUp))}`);
console.log(`rewritten "${standalone}": ${show(awaitsearch(standalone))}`);// 2. HyDE: embed a hypothetical answer instead of the question; answers look like documents.const vague ="can outsiders grab a slot in my diary?";const hypothetical =awaitask("Write a two-sentence help-centre answer to the question. It may be wrong; it is only used for search.", vague);
console.log(`\nvague question: ${show(awaitsearch(vague))}`);
console.log(`hypothetical answer: ${show(awaitsearch(hypothetical))}`);// 3. Multi-query: search several rephrasings and fuse the rankings (reciprocal rank fusion).const broad ="my calendar isn't updating";const variants =(awaitask("Give three different search queries, one per line, that together cover the likely causes.", broad)).split("\n");const fused =newMap();for(const v of[broad,...variants])(awaitsearch(v,10)).forEach((r, rank)=> fused.set(r.id,(fused.get(r.id)??0)+1/(60+ rank +1)));
console.log(`\nbroad question: ${show(awaitsearch(broad,6))}`);
console.log(`${variants.length} variants + fused: ${[...fused].sort((a, b)=> b[1]- a[1]).slice(0,6).map(([id, s])=>`${id}${s.toFixed(3)}`).join(", ")}`);
ask calls a small model (claude-haiku-5-5 at effort: "low") with a task-specific system prompt; search is plain dense retrieval returning the top 4 (or 6). The rewrites in the scripted replies were written for the example; the retrieval scores are real.
Rewrite: the follow-up "and what about the yearly one?" searched as typed returns p2 first (0.44: yearly billing, not refunds). Rewritten as "Can I get a refund on a yearly plan?", it returns r2 first (0.63), the yearly refund rule, because the rewrite restored the missing subject, "refund", from the conversation.
HyDE: "can outsiders grab a slot in my diary?" matches nothing well; the best score is 0.27 for the booking page time-zone chunk. The hypothetical answer ("Create a booking link and share it, and people outside your company can choose a free time…") is written in the help centre's own vocabulary, and finds s1 at 0.78.
Multi-query: "my calendar isn't updating" alone returns Google sync, the GC-403 error, Outlook sync, export, booking links and mobile chunks. Fusing it with three variants (Google, Outlook, and "error after changing password") pulls o2, the Outlook sign-in fix, into the top 6 and drops the irrelevant booking-link chunk: two causes covered instead of one.
The cost is one extra model call per question. Measure it like any other change: these techniques often help a lot on conversational and vague traffic and do nothing (or harm) on clear, specific queries, so many systems apply them selectively.
AdvancedGotcha: rewriting can change the question
?Why does HyDE work?
The vague question scored 0.27 against its best chunk, but a made-up answer to it scored 0.78 against the right chunk. Why would a possibly wrong answer retrieve better than the real question?
Show answer
Because retrieval compares texts by similarity, and an answer looks like a document while a question doesn't.
What’s happening
The help-centre chunks are statements in the company's vocabulary: "A booking link lets people outside your company pick a free slot…". The user's question uses different words ("outsiders", "grab", "diary") and a different form (a question).
The hypothetical answer is written as a help-centre statement and naturally uses the standard terms ("booking link", "people outside your company", "free time"), so its vector lands next to the real chunk.
Even if its details were wrong (say it claimed booking links cost extra), the topic and vocabulary would still match, and only the retrieved real chunk is shown to the answering model.
The risk is a hypothetical answer that confidently points to the wrong topic; combining the original query and the HyDE query with RRF limits the damage.
#Building the prompt: context, citations and "I don't know"
Added
Retrieval finds the passages; the prompt decides whether the model uses them well. A RAG prompt has a few jobs, and each needs to be explicit:
Separate instructions from data. Put retrieved chunks inside clear delimiters (XML tags such as <sources> and <source id="…">, or the API's own search_result and document blocks), never mixed into the instructions. Chunks are untrusted text: a document that says "ignore your instructions" must stay data (chapter 11 covers prompt injection).
Answer only from the sources, and say why that rule exists (a wrong answer costs the customer more than no answer): models follow rules better when they know the reason.
Make "I don't know" a defined, normal output, with exact wording your code can detect. Without it, the model fills gaps with plausible inventions.
Require citations per claim, so answers can be checked by users and by your code.
Order matters: long documents first, the question last (Anthropic's long-context guidance), and the most relevant chunk nearest the question.
Two ways to get citations. Do it yourself: give each source an id, ask for [id] after each sentence, and verify the ids in code (this topic's example). Let the API do it: send chunks as search_result blocks (or document blocks) with citations: { enabled: true }, and Claude returns text blocks with structured citations that point at the exact source and passage, as in the pipeline example. The API route gives you exact cited text and source for free; the manual route works with any model and any output format. Note that Anthropic documents citations as incompatible with structured outputs (output_config.format), so if you need JSON answers, use the manual route or request citations in your schema.
The mental model is briefing a new support agent: here are the pages (in a folder, clearly labelled), answer only from them, quote the page number for every statement, and if the pages don't cover it, say so and escalate; inventing a policy is the one thing that gets you fired.
The example builds a RAG prompt with XML-tagged sources, sends three questions, and checks each reply in code: a cited answer, an honest "I don't know", and a reply that cites a source it was never given.
import Anthropic from"@anthropic-ai/sdk";// Scripted replies (see "How these examples run") ---------------------------------------------// Three replies in the documented response shape; the model's words were written for the example// (the third one deliberately cites a source it wasn't given, to show what the check catches).constmessage=(text)=>({id:"msg_01Kp4ZtB8wQm2XcN7vRf5Lh9",type:"message",role:"assistant",content:[{type:"text", text }],model:"claude-opus-5-5",stop_reason:"end_turn",stop_sequence:null,usage:{input_tokens:388,output_tokens:41},});const replies =[message("Sign in with one of your recovery codes; each code works once [a4]. If you have none left, your workspace admin can reset two-step verification for you [a4]."),message("I don't know: the help centre doesn't say."),message("Yes, you can pay by PayPal from Settings > Billing [b2][b7]."),];constfetch=async()=> Response.json(replies.shift());const client =newAnthropic({apiKey:"sk-ant-test", fetch });// for real: new Anthropic()// ----------------------------------------------------------------------------------------------constSYSTEM=`You are the support assistant for Meadowlark, a team calendar app.
Answer using only the sources in <sources>. After each sentence, cite the id of the source it came from in square brackets, like [a4].
If the sources don't answer the question, reply exactly: "I don't know: the help centre doesn't say." Never guess: a wrong answer costs the customer more than no answer.
Keep answers under 80 words.`;constescape=(s)=> s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");// source text is data, not markupfunctionbuildUserMessage(question, sources){const docs = sources.map((s)=>`<source id="${s.id}" title="${escape(s.title)}">\n${escape(s.text)}\n</source>`).join("\n");return`<sources>\n${docs}\n</sources>\n\n<question>\n${escape(question)}\n</question>`;}asyncfunctionanswer(question, sources){const res =await client.messages.create({model:"claude-opus-5-5",max_tokens:1024,system:SYSTEM,messages:[{role:"user",content:buildUserMessage(question, sources)}],});if(res.stop_reason !=="end_turn")return{status:`stopped: ${res.stop_reason}`};const text = res.content.filter((b)=> b.type ==="text").map((b)=> b.text).join("");if(text.startsWith("I don't know"))return{status:"abstained", text };const cited =[...text.matchAll(/\[([a-z]\d+)\]/g)].map((m)=> m[1]);const unknown = cited.filter((id)=>!sources.some((s)=> s.id === id));if(!cited.length || unknown.length)return{status:`REJECTED (cites ${unknown.join(", ")||"nothing"} not in the sources)`, text };return{status:`ok, cites ${[...newSet(cited)].join(", ")}`, text };}const sources ={a4:{id:"a4",title:"Two-step verification",text:"You get 10 recovery codes, each usable once. If you lose your phone, sign in with a recovery code or ask your workspace admin to reset two-step verification."},a3:{id:"a3",title:"Two-step verification",text:"Turn on two-step verification in Settings > Security. Meadowlark works with authenticator apps such as Google Authenticator and 1Password."},b2:{id:"b2",title:"Invoices and payment",text:"To change the card we charge, open Settings > Billing and choose Update payment method. We accept Visa, Mastercard and American Express."},p1:{id:"p1",title:"Plans and pricing",text:"Meadowlark has three plans. Free covers up to 3 people. Team costs £8 per person per month. Business costs £15 per person per month and adds single sign-on (SSO) and the API."},};const first =buildUserMessage("I lost my phone. How do I sign in?",[sources.a4, sources.a3]);
console.log(`--- user message for question 1 (${first.length} characters) ---\n${first}\n---`);for(const[question, ids]of[["I lost my phone. How do I sign in?",["a4","a3"]],["Can I pay with PayPal?",["b2","p1"]],["Can I pay with PayPal?",["b2","p1"]],]){const{ status, text }=awaitanswer(question, ids.map((id)=> sources[id]));
console.log(`\nQ: ${question}\n ${status}${text ?`\n ${text}`:""}`);}
Result
--- user message for question 1 (493 characters) ---
<sources>
<source id="a4" title="Two-step verification">
You get 10 recovery codes, each usable once. If you lose your phone, sign in with a recovery code or ask your workspace admin to reset two-step verification.
</source>
<source id="a3" title="Two-step verification">
Turn on two-step verification in Settings > Security. Meadowlark works with authenticator apps such as Google Authenticator and 1Password.
</source>
</sources>
<question>
I lost my phone. How do I sign in?
</question>
---
Q: I lost my phone. How do I sign in?
ok, cites a4
Sign in with one of your recovery codes; each code works once [a4]. If you have none left, your workspace admin can reset two-step verification for you [a4].
Q: Can I pay with PayPal?
abstained
I don't know: the help centre doesn't say.
Q: Can I pay with PayPal?
REJECTED (cites b7 not in the sources)
Yes, you can pay by PayPal from Settings > Billing [b2][b7].
What’s happening
SYSTEM holds the rules: answer only from <sources>, cite [id] after each sentence, reply with an exact sentence when the sources don't answer, never guess (with the reason), and a length limit. Exact wording makes abstention machine-detectable.
buildUserMessage wraps each chunk in <source id="…" title="…"> and the question in <question>, sources first and question last. escape turns <, > and & into entities, so a chunk containing </source> can't close the tag early; that's why the printed message shows Settings > Security, which the model reads without trouble.
Question 1 gets an answer citing [a4] twice. answer extracts every [id], checks each was among the sources sent, and reports ok, cites a4.
Question 2 ("Can I pay with PayPal?") gets the exact "I don't know" sentence: the sources mention Visa, Mastercard and American Express but not PayPal. The code recognises the prefix and reports abstained, which your UI can turn into "connect me to a person".
The third reply (written to show the check working) claims PayPal is supported and cites [b2][b7]. b7 was never sent, so the code reports REJECTED (cites b7 not in the sources) and the answer is never shown. Checking ids catches invented sources; checking that the cited text actually supports the claim needs a second model or a judge (LLM-as-judge).
AdvancedHow many chunks, and in what order?
More chunks raise the chance the answer is in the prompt and cost tokens; past a point they add noise. Anthropic's contextual retrieval experiments found passing the top 20 chunks worked better than 5 or 10, after reranking; many production systems send 5–10. Measure end-to-end answer quality at a few values of k on your eval set. Order the sources so the best-ranked chunk is closest to the question, deduplicate near-identical chunks, and group chunks from the same document together in reading order (two adjacent sections read better as one passage). If the prefix of your prompt (system prompt, tool definitions, fixed instructions) is long and stable, put it first and cache it (Prompt caching); retrieved chunks vary per question and go after the cache breakpoint.
?Where should the question go?
Your prompt is: instructions, then the user's question, then 12 retrieved chunks (about 6,000 tokens). Answers sometimes ignore the question's details. What would you change?
Show answer
Put the chunks first and the question last, nearest the instructions about how to answer.
What’s happening
Anthropic's prompting guide says to put long documents near the top, above the query, instructions and examples, and notes that queries at the end improved response quality by up to 30% in its tests, especially with complex multi-document inputs.
With the question buried before 6,000 tokens of sources, its details are far from where the model starts generating, and the most recent text it read is a chunk.
Reorder: system instructions (stable, cacheable), then <sources> with the best-ranked chunk last, then <question>, then any final reminder ("cite sources; say 'I don't know' if they don't answer").
Verify with the eval set rather than assuming: compare answer quality for both layouts on the same questions.
Chunking cuts text out of its document, and many chunks don't make sense on their own: "Entries are kept for 400 days" (entries of what? on which plan?), "It's billed per person", "Setup takes about ten minutes". Their embeddings and keywords lack the very words a user's question contains, so retrieval misses them or confuses them with similar chunks from other documents. Contextual retrieval (Anthropic, September 2024) fixes this at ingest time: for every chunk, ask a model to write a short context (50–100 tokens) that situates it within its whole document, and prepend that context to the chunk before embedding it and before indexing it for BM25.
Anthropic's write-up reports, on its benchmark, retrieval failure (1 minus recall@20) falling from 5.7% to 3.7% with contextual embeddings (a 35% reduction), to 2.9% with contextual embeddings plus contextual BM25 (49%), and to 1.9% when reranking was added as well (67%). Because every chunk of a document is sent with the same full document, prompt caching makes it cheap: Anthropic estimated a one-time cost of $1.02 per million document tokens (assuming 800-token chunks, 8,000-token documents and about 100 tokens of context each), with Claude 3 Haiku as the contextualiser at the time. They also note it pays most when chunks are ambiguous out of context; for knowledge bases small enough to fit in the prompt, skip retrieval altogether.
The mental model is writing the chapter title on every index card. A card that says "Entries are kept for 400 days" is useless in a shuffled deck; the same card headed "Business plan guide, Activity log" is findable.
The example has two plan guides with parallel sections, so several chunks are near-identical out of context ("Entries are kept for 30 days." / "Entries are kept for 400 days…"). It generates a context for each chunk (scripted replies), then compares where the right chunk ranks for five questions, with plain and contextualised chunks.
contextual.mjs
import Anthropic from"@anthropic-ai/sdk";import{ pipeline }from"@huggingface/transformers";// Scripted replies (see "How these examples run") ---------------------------------------------// Eight replies in the documented response shape, one per chunk, in the order the chunks are sent.// The context sentences were written for the example, in the style the prompt asks for.const contexts =["From the Business plan guide, section What's included: the features of the Business plan.","From the Business plan guide, section Activity log: how long the Business plan keeps activity log entries.","From the Business plan guide, section Support: how fast Business plan customers get support replies.","From the Business plan guide, section Single sign-on: how long SSO setup takes on the Business plan.","From the Team plan guide, section What's included: the features of the Team plan.","From the Team plan guide, section Activity log: how long the Team plan keeps activity log entries.","From the Team plan guide, section Support: how fast Team plan customers get support replies.","From the Team plan guide, section Sign-in: how people sign in on the Team plan and whether SSO is available.",];constfetch=async()=> Response.json({id:"msg_01Vb6YsN2kP8qTw4HcJ9mD7E",type:"message",role:"assistant",content:[{type:"text",text: contexts.shift()}],model:"claude-haiku-5-5",stop_reason:"end_turn",stop_sequence:null,usage:{input_tokens:182,output_tokens:22},});const client =newAnthropic({apiKey:"sk-ant-test", fetch });// for real: new Anthropic()// ----------------------------------------------------------------------------------------------const guides ={"Business plan guide":[["What's included","The Business plan includes everything in Team, plus single sign-on and the REST API."],["Activity log","Entries are kept for 400 days and can be exported as CSV."],["Support","Replies within 4 working hours, by email or live chat."],["Single sign-on","Setup takes about ten minutes with Okta, Microsoft Entra ID or Google Workspace."],],"Team plan guide":[["What's included","The Team plan includes shared calendars, booking links, and Slack and Teams reminders."],["Activity log","Entries are kept for 30 days."],["Support","Replies within 2 working days, by email."],["Sign-in","People sign in with email and password; single sign-on is not available on this plan."],],};// Chunk each guide by section, the way a simple chunker would: the section text only.const chunks = Object.entries(guides).flatMap(([doc, sections])=> sections.map(([section, text])=>({ doc, section, text })));// Contextualise: ask a small model to situate each chunk in its whole document (cached across that document's chunks).for(const chunk of chunks){const fullDocument = guides[chunk.doc].map(([s, t])=>`## ${s}\n${t}`).join("\n");const res =await client.messages.create({model:"claude-haiku-5-5",max_tokens:100,output_config:{effort:"low"},messages:[{role:"user",content:[{type:"text",text:`<document title="${chunk.doc}">\n${fullDocument}\n</document>`,cache_control:{type:"ephemeral"}},{type:"text",text:`<chunk>\n${chunk.text}\n</chunk>\nWrite one short sentence that situates this chunk within the document, to help search find it. Reply with the sentence only.`},],}],});
chunk.context = res.content.find((b)=> b.type ==="text").text;}// Index both versions: plain chunks, and context + chunk. Then compare where the right chunk ranks.const embed =awaitpipeline("feature-extraction","Xenova/all-MiniLM-L6-v2",{dtype:"q8"});const plainVectors =(awaitembed(chunks.map((c)=> c.text),{pooling:"mean",normalize:true})).tolist();const contextVectors =(awaitembed(chunks.map((c)=>`${c.context}${c.text}`),{pooling:"mean",normalize:true})).tolist();asyncfunctionrankOf(question, vectors, target){const[q]=(awaitembed([question],{pooling:"mean",normalize:true})).tolist();const scores = vectors.map((v)=> v.reduce((s, x, d)=> s + x * q[d],0));return scores.filter((s)=> s > scores[target]).length +1;}const questions =[["How long does the Business plan keep the activity log?","Business plan guide","Activity log"],["How long are activity log entries kept on Team?","Team plan guide","Activity log"],["How quickly does support reply on the Team plan?","Team plan guide","Support"],["Does the Business plan have live chat support?","Business plan guide","Support"],["How long does SSO setup take?","Business plan guide","Single sign-on"],];
console.log(`example context: "${chunks[1].context}"`);
console.log("\nrank of the right chunk (1 = top) plain contextual");let plainTop =0, contextTop =0;for(const[question, doc, section]of questions){const target = chunks.findIndex((c)=> c.doc === doc && c.section === section);const[a, b]=[awaitrankOf(question, plainVectors, target),awaitrankOf(question, contextVectors, target)];
plainTop += a ===1; contextTop += b ===1;
console.log(`${question.padEnd(55)}${String(a).padStart(4)}${String(b).padStart(12)}`);}
console.log(`right chunk first: plain ${plainTop} of ${questions.length}, contextual ${contextTop} of ${questions.length}`);
Result
example context: "From the Business plan guide, section Activity log: how long the Business plan keeps activity log entries."
rank of the right chunk (1 = top) plain contextual
How long does the Business plan keep the activity log? 3 1
How long are activity log entries kept on Team? 1 1
How quickly does support reply on the Team plan? 1 1
Does the Business plan have live chat support? 4 2
How long does SSO setup take? 1 1
right chunk first: plain 3 of 5, contextual 4 of 5
What’s happening
The two guides are chunked by section, keeping only the section text, as a simple chunker would. Out of context, the Business and Team "Activity log" chunks differ only in a number, and neither mentions a plan or an activity log.
For each chunk, the code sends the whole document and the chunk, asking for one sentence that situates the chunk. The document block carries cache_control: { type: "ephemeral" }, so the second to fourth chunks of the same guide would read the document from the cache instead of paying for it again: that's what makes contextualising every chunk affordable. A small model at low effort is enough.
The contexts (written for the example in the style the prompt asks for) name the guide, the section and what the chunk is about: "From the Business plan guide, section Activity log: how long the Business plan keeps activity log entries." The code embeds context + chunk as the second index; a real system would add the same text to the BM25 index too.
"How long does the Business plan keep the activity log?" finds its chunk at rank 3 with plain chunks (two other chunks outrank it) and rank 1 with context. "Does the Business plan have live chat support?" improves from 4 to 2: better, not fixed. The other three questions were already right.
Overall the right chunk comes first for 3 of 5 questions with plain chunks and 4 of 5 with context. That's the shape of Anthropic's result in miniature: the gain is concentrated on chunks that are ambiguous without their document, which in real corpora (contracts, manuals, reports) is a large share.
AdvancedDoing contextual retrieval in production
Batch it. Contextualising is an ingest job, not a request-time step: run it with the Message Batches API (half price, results within hours; Batch processing) or a queue, and re-run only for changed documents.
Cache per document. Process all chunks of one document together, with the document in a cached prefix, so each chunk costs a cache read plus a short output. Documents longer than the model's window need splitting into sections first.
Index the context everywhere you search: in the embedding, in the BM25 text, and in the reranker's input (Anthropic reported that reranking stacked on top of contextual retrieval gave the largest gain).
Show users the original chunk, not the generated context: the context is a search aid, and it could contain a model's mistakes.
Cheaper alternatives first: a heading-path prefix ("Business plan guide > Activity log") gets part of the benefit for free, and some embedding providers offer contextualised chunk embeddings directly (Voyage AI's voyage-context-4 embeds chunks with their document's context, per Anthropic's embeddings page).
?Why prompt caching matters here
A 10,000-token document is split into 25 chunks. Without caching, how many input tokens does contextualising it cost, roughly, and what changes with caching?
Show answer
About 260,000 input tokens without caching; with caching, one write of the document plus 24 cheap cache reads.
What’s happening
Each call sends the whole document (10,000 tokens) plus one chunk and the instruction (a few hundred tokens), so 25 calls send about 25 × 10,400 ≈ 260,000 input tokens at full price.
With the document as a cached prefix, the first call writes it to the cache (10,000 tokens at the write price, 1.25× the input price for a 5-minute cache) and the other 24 read it at the cache-read price, a small fraction of the input price (0.05× on Claude Opus 5.5, about 0.1× on most models).
Only the chunk and instruction (a few hundred tokens) are billed at the full input price each time, plus about 100 output tokens of context.
That's how Anthropic arrived at roughly $1 per million document tokens, a one-time ingest cost. Run the calls for one document back to back (or in one batch) so the cache stays warm.
You can't improve retrieval by reading answers and guessing. Retrieval gets its own metrics, computed on a labelled set of questions, each with the chunk ids that answer it. Given each question's ranked results, three metrics cover most needs:
Recall@k: the share of relevant chunks that appear in the top k. With one answer per question it's simply "was the answer in the top k?", averaged over questions. Pick k to match what you send to the model: if the prompt gets 5 chunks, recall@5 is what limits answer quality.
MRR (mean reciprocal rank): 1 / (rank of the first relevant result), averaged: 1 if it's first, 0.5 if second, 0.33 if third, 0 if absent. It rewards putting the answer at the very top.
nDCG@k (normalised discounted cumulative gain): handles graded relevance (a chunk can be highly or partly relevant). Each result contributes its gain, 2^grade − 1, divided by log2(rank + 1), so lower positions count less; dividing by the best possible ordering's score normalises it to 0–1.
Building the labelled set is the real work: take real user questions (logs, support tickets) or write realistic ones, including follow-ups, vague questions, identifiers and unanswerable questions, and mark the chunks that answer each. A few dozen questions already show big differences; a few hundred make small differences trustworthy. Chapter 9 covers building eval sets in depth (Building an eval set).
The mental model is marking a search engine's homework: recall asks "did the right page make the first page of results?", MRR asks "how near the top was it?", and nDCG asks "were the best pages above the merely useful ones?"
The example computes all three for five retrieval setups over the 20-question set, with graded relevance for three questions where another chunk helps partly.
retrieval-metrics.mjs
import{ pipeline, AutoTokenizer, AutoModelForSequenceClassification }from"@huggingface/transformers";// The Meadowlark help centre (a fictional team-calendar app): 34 chunks, one per section.const chunks =[["p1","Plans and pricing","Meadowlark has three plans. Free covers up to 3 people. Team costs £8 per person per month. Business costs £15 per person per month and adds single sign-on (SSO) and the API."],["p2","Plans and pricing","Paying yearly gives you 12 months for the price of 10. Switch between monthly and yearly billing at any time in Settings > Billing."],["r1","Refunds","Monthly plans are not refunded for unused days. When you cancel, your plan stays active until the end of the month you have paid for."],["r2","Refunds","Yearly plans can be refunded within 30 days of the start or renewal date. We refund the unused months, pro rata."],["r3","Refunds","Refunds go back to the card you paid with and usually arrive within 5 to 10 working days."],["a1","Resetting your password","Choose Forgot password on the sign-in page and enter your work email. We send a reset link that expires after 30 minutes."],["a2","Resetting your password","If your company signs in with SSO, Meadowlark does not store a password for you: reset it with your identity provider, such as Okta or Google Workspace."],["a3","Two-step verification","Turn on two-step verification in Settings > Security. Meadowlark works with authenticator apps such as Google Authenticator and 1Password."],["a4","Two-step verification","You get 10 recovery codes, each usable once. If you lose your phone, sign in with a recovery code or ask your workspace admin to reset two-step verification."],["i1","Google Calendar sync","Connect Google Calendar in Settings > Integrations. Events sync both ways every 5 minutes."],["i2","Google Calendar sync","Private Google events appear in Meadowlark as Busy, without their title or attendees."],["i3","Google Calendar sync","Error GC-403 means Meadowlark lost permission to read your calendar, usually after a Google password change. Reconnect the calendar to fix it."],["i4","Slack notifications","Install the Meadowlark app for Slack from Settings > Integrations. A Slack workspace admin may need to approve it."],["i5","Slack notifications","Meadowlark sends a Slack reminder 10 minutes before each meeting. Type /meadowlark today to see your schedule."],["s1","Booking links","A booking link lets people outside your company pick a free slot in your calendar. Create one from the Booking links page."],["s2","Booking links","You can add buffer time before and after booked meetings, from 5 to 60 minutes."],["s3","Booking links","The Team plan includes up to 5 booking links per person; Business has no limit."],["d1","Exporting your data","Admins can export every calendar and booking as CSV or ICS files from Settings > Data. Export files stay available for 7 days."],["d2","Exporting your data","Business plans can also read data through the REST API, with up to 100 requests per minute per workspace."],["d3","Deleting your workspace","Only the workspace owner can delete a workspace. A deleted workspace can be restored for 14 days; after that, all data is permanently erased."],["e1","Error messages","E401 means your session expired. Sign in again; if it keeps happening, check that your browser allows cookies from meadowlark.example."],["e2","Error messages","E429 means too many requests in a short time. Wait a minute and try again; API clients should slow down and retry with backoff."],["m1","Mobile apps","Meadowlark has an iPhone app in the App Store. It shows your schedule and booking links and sends meeting reminders."],["m2","Mobile apps","On Android, use Meadowlark in your phone's browser; you can add it to your home screen for an app-like experience."],["b1","Invoices and payment","Invoices are emailed to the billing contact on the first day of each billing period. Download past invoices from Settings > Billing > Invoices."],["b2","Invoices and payment","To change the card we charge, open Settings > Billing and choose Update payment method. We accept Visa, Mastercard and American Express."],["a5","Changing your email","Change the email address you sign in with from Profile > Account. We send a confirmation link to the new address before the change takes effect."],["o1","Outlook calendar sync","Connect Outlook or Microsoft 365 in Settings > Integrations. Outlook events sync both ways every 10 minutes."],["o2","Outlook calendar sync","Error OC-401 means your Microsoft sign-in expired. Sign in to Microsoft again from Settings > Integrations to resume syncing."],["t1","Microsoft Teams notifications","Add the Meadowlark app to Microsoft Teams to get meeting reminders and a daily agenda in a Teams chat."],["s4","Booking links","People who book through your link get a confirmation email with links to reschedule or cancel, up to 2 hours before the meeting."],["s5","Booking links","Booking pages show free slots in the visitor's own time zone, detected from their browser."],["e3","Error messages","E403 means your role does not allow this action. Ask a workspace admin to change your role or do it for you."],["n1","Notifications","Turn meeting reminders off, or change how early they arrive, in Profile > Notifications. Each channel (email, Slack, Teams, mobile) has its own setting."],].map(([id, title, text])=>({ id, title, text }));// A small labelled set: 20 realistic questions, each with the chunk that answers it.const labelled =[["The password email you sent me doesn't work any more","a1"],["I log in through Okta. How do I change my password?","a2"],["can't log in, it says my code is wrong","a4"],["I was charged after I cancelled","r1"],["refund for annual subscription","r2"],["How long until a refund reaches my card?","r3"],["is SSO on the cheaper plan?","p1"],["Is there a discount for paying annually?","p2"],["how do I give our developers API access","d2"],["What does GC-403 mean?","i3"],["OC-401","o2"],["I keep getting E429","e2"],["it says I'm not allowed to do that","e3"],["outlook stopped updating","o2"],["the meeting reminder comes too late","n1"],["how do I move a meeting someone booked with me","s4"],["visitors see the wrong times on my booking page","s5"],["Can clients pick a meeting time themselves?","s1"],["I need receipts for my expenses","b1"],["Is there an Android app?","m2"],].map(([question, answer])=>({ question, answer }));// Graded relevance: the labelled answer counts 2; a few chunks that help partly count 1.const partly ={"outlook stopped updating":["o1"],"the meeting reminder comes too late":["i5"],"I was charged after I cancelled":["r3"]};constrelevanceOf=({ question, answer })=>newMap([[answer,2],...(partly[question]??[]).map((id)=>[id,1])]);// The retrievers from the previous topics: dense, BM25, reciprocal rank fusion and a cross-encoder reranker.const embed =awaitpipeline("feature-extraction","Xenova/all-MiniLM-L6-v2",{dtype:"q8"});const vectors =(awaitembed(chunks.map((c)=> c.text),{pooling:"mean",normalize:true})).tolist();asyncfunctiondense(query){const[q]=(awaitembed([query],{pooling:"mean",normalize:true})).tolist();return vectors.map((v, i)=>({id: chunks[i].id,score: v.reduce((s, x, d)=> s + x * q[d],0)})).sort((a, b)=> b.score - a.score).slice(0,10);}constSTOP=newSet("a an and are as at be by can do does for from get how i i'm in is it me my of on or our so that the this to was we what when where why with you your".split(" "));consttokenize=(t)=>(t.toLowerCase().match(/[a-z0-9]+(?:-[a-z0-9]+)*/g)??[]).filter((w)=>!STOP.has(w));const docs = chunks.map((c)=>tokenize(c.text));const avgLength = docs.reduce((s, d)=> s + d.length,0)/ docs.length;const docFreq =newMap();for(const d of docs)for(const t ofnewSet(d)) docFreq.set(t,(docFreq.get(t)??0)+1);constbm25=(query)=> docs.map((d, i)=>{let score =0;for(const t oftokenize(query)){const df = docFreq.get(t);if(!df)continue;const tf = d.filter((x)=> x === t).length;
score +=(Math.log(1+(docs.length - df +0.5)/(df +0.5))* tf *2.2)/(tf +1.2*(0.25+(0.75* d.length)/ avgLength));}return{id: chunks[i].id, score };}).filter((r)=> r.score >0).sort((a, b)=> b.score - a.score).slice(0,10);constrrf=(lists)=>{const fused =newMap();for(const list of lists) list.forEach(({ id }, rank)=> fused.set(id,(fused.get(id)??0)+1/(60+ rank +1)));return[...fused].map(([id, score])=>({ id, score })).sort((a, b)=> b.score - a.score).slice(0,10);};const rerankTokenizer =await AutoTokenizer.from_pretrained("Xenova/ms-marco-MiniLM-L-6-v2");const reranker =await AutoModelForSequenceClassification.from_pretrained("Xenova/ms-marco-MiniLM-L-6-v2",{dtype:"q8"});asyncfunctionrerank(query, list){const texts = list.map(({ id })=> chunks.find((c)=> c.id === id).text);const{ logits }=awaitreranker(rerankTokenizer(texts.map(()=> query),{text_pair: texts,padding:true,truncation:true}));return list.map((r, i)=>({id: r.id,score: logits.data[i]})).sort((a, b)=> b.score - a.score);}// The metrics. `ranked` is a list of chunk ids, best first; `rel` maps relevant ids to a grade.constrecallAt=(ranked, rel, k)=> ranked.slice(0, k).filter((id)=> rel.get(id)===2).length;// 1 relevant answer per questionconstreciprocalRank=(ranked, rel)=>{const i = ranked.findIndex((id)=> rel.get(id)===2);return i ===-1?0:1/(i +1);};functionndcgAt(ranked, rel, k){const dcg = ranked.slice(0, k).reduce((s, id, i)=> s +(2**(rel.get(id)??0)-1)/ Math.log2(i +2),0);const ideal =[...rel.values()].sort((a, b)=> b - a).slice(0, k).reduce((s, g, i)=> s +(2** g -1)/ Math.log2(i +2),0);return dcg / ideal;}const systems ={"BM25":async(q)=>bm25(q),"dense":async(q)=>dense(q),"hybrid (RRF)":async(q)=>rrf([bm25(q),awaitdense(q)]),"dense + rerank":async(q)=>rerank(q,awaitdense(q)),"hybrid + rerank":async(q)=>rerank(q,rrf([bm25(q),awaitdense(q)])),};
console.log(`${labelled.length} questions recall@1 recall@5 MRR nDCG@5`);for(const[name, run]of Object.entries(systems)){const totals =[0,0,0,0];for(const item of labelled){const ranked =(awaitrun(item.question)).map((r)=> r.id);const rel =relevanceOf(item);[recallAt(ranked, rel,1),recallAt(ranked, rel,5),reciprocalRank(ranked, rel),ndcgAt(ranked, rel,5)].forEach((v, j)=>(totals[j]+= v));}
console.log(`${name.padEnd(22)}${totals.map((t)=>(t / labelled.length).toFixed(3).padStart(9)).join("")}`);}
relevanceOf turns each labelled answer into grade 2 and the extra partly-relevant chunks (for three questions) into grade 1. Recall and MRR count only the grade-2 answer; nDCG uses both grades.
recallAt checks whether the answer is in the top k; reciprocalRank returns 1 / rank of the answer (0 if missing from the top 10); ndcgAt sums (2^grade − 1) / log2(position + 1) over the top 5 and divides by the same sum for the ideal order.
Dense beats BM25 on everything (recall@1 0.700 vs 0.550, MRR 0.800 vs 0.631): most of these questions are paraphrases, where keywords fail. Hybrid keeps BM25's weak top-1 (0.550) but has the best recall@5 (1.000: every answer in the top 5), so it's the best candidate generator.
Reranking fixes the order: dense + rerank has the best recall@1 (0.850), MRR (0.907) and nDCG@5 (0.920). Hybrid + rerank is close (0.800, 0.883, 0.909) and, unexpectedly, lost one answer from the top 5 (recall@5 0.950): the reranker demoted it below five other candidates.
Read the differences with care: with 20 questions, one question is 0.05 of recall, so dense + rerank versus hybrid + rerank is a single question. The robust conclusions here are "reranking clearly helps" and "BM25 alone is weak on this traffic"; choosing between the two reranked setups needs a bigger set, ideally with more identifier-style questions where hybrid shines.
AdvancedGotcha: evaluate on questions you didn't tune on
?Compute MRR by hand
Three questions: the answer is at rank 1 for the first, rank 4 for the second, and not in the top 10 for the third. What are MRR and recall@3?
Show answer
MRR = 0.417; recall@3 = 0.333.
What’s happening
Reciprocal ranks: 1/1 = 1, 1/4 = 0.25, and 0 for the missing answer.
MRR is their mean: (1 + 0.25 + 0) / 3 = 0.4167.
Recall@3 asks whether each answer is in the top 3: yes, no (rank 4), no, so 1 of 3 = 0.333.
The two metrics tell different stories: MRR gives partial credit for rank 4, recall@3 gives none. If your prompt includes 5 chunks, recall@5 (0.667 here) is the more relevant number for answer quality.
Three ways to get your knowledge into a model's answers, often confused in interviews:
RAG
Long context
Fine-tuning
How
retrieve a few relevant chunks per request
put the whole knowledge base in the prompt (cached)
train the model's weights on your data
Good for
large or changing corpora, citations, per-user permissions
small, stable corpora; whole-document analysis
behaviour: tone, format, narrow skills, smaller models
Updating knowledge
re-index changed documents
edit the prompt
retrain
Citations
natural
possible (citations on documents)
no
Main risk
retrieval misses the answer
cost and latency per request; attention spread over a huge prompt
stale knowledge; hallucinating around learned facts
Long context has become a real alternative as windows reached 1M tokens: no retrieval pipeline to build or tune, nothing can be "not retrieved", and prompt caching makes a repeated large prefix far cheaper. Its limits are cost and latency per request (even cached tokens are read on every call), the context window as a hard cap, quality on very long inputs (Context windows), and no per-user filtering unless you build a prompt per user. Fine-tuning is the wrong tool for facts: it's slow and costly to update, gives no citations, and a model fine-tuned on documents still invents details around them; it's the right tool for behaviour (chapter 12).
The mental model: RAG is an open-book exam with a librarian, long context is an open-book exam where you carry the whole library into the room, and fine-tuning is studying before a closed-book exam: great for skills, unreliable for exact facts.
The example estimates a month of input costs for the three knowledge strategies on Claude Opus 5.5. The assumptions are for the sketch: 50,000 questions a month, a 300,000-token knowledge base, 500 tokens of system prompt, 60-token questions and 300-token answers; for caching, the cache has gone cold 20 times a day when a question arrives (gaps of more than 5 minutes); RAG sends 8 chunks of about 400 tokens.
// Monthly input cost of answering from a knowledge base: send all of it every time, cache it, or retrieve.// Claude Opus 5.5 prices (US dollars per million tokens): input $4, 5-minute cache write $5 (1.25x), cache read $0.20.const price ={input:4,cacheWrite:5,cacheRead:0.2,output:20};constperMillion=(tokens, rate)=>(tokens /1e6)* rate;// Assumptions for the sketch (stated in the prose).const questionsPerMonth =50_000;const knowledgeBase =300_000;// tokens: the whole help centre plus product docsconst question =60, systemPrompt =500, answer =300;// tokens per requestconst coldStartsPerMonth =30*20;// times the cache has expired when a question arrives (gaps over 5 minutes)const retrieved =8*400;// RAG: 8 chunks of about 400 tokensconst fixedOutput =perMillion(questionsPerMonth * answer, price.output);const options ={"long context, no caching":perMillion(questionsPerMonth *(systemPrompt + knowledgeBase + question), price.input),"long context, cached":perMillion(coldStartsPerMonth * knowledgeBase, price.cacheWrite)+perMillion((questionsPerMonth - coldStartsPerMonth)* knowledgeBase, price.cacheRead)+perMillion(questionsPerMonth *(systemPrompt + question), price.input),"RAG, 8 chunks":perMillion(questionsPerMonth *(systemPrompt + retrieved + question), price.input),};
console.log(`input tokens per request: long context ${(systemPrompt + knowledgeBase + question).toLocaleString("en-GB")}, RAG ${(systemPrompt + retrieved + question).toLocaleString("en-GB")}`);for(const[name, input]of Object.entries(options))
console.log(`${name.padEnd(26)} input $${Math.round(input).toLocaleString("en-GB").padStart(6)} + output $${Math.round(fixedOutput)} = $${Math.round(input + fixedOutput).toLocaleString("en-GB")} a month`);
Result
input tokens per request: long context 300,560, RAG 3,760
long context, no caching input $60,112 + output $300 = $60,412 a month
long context, cached input $ 3,976 + output $300 = $4,276 a month
RAG, 8 chunks input $ 752 + output $300 = $1,052 a month
What’s happening
Prices are Claude Opus 5.5's: $4 per million input tokens, $5 for writing a 5-minute cache entry (1.25×), $0.20 for reading one (0.05× on this model), $20 per million output tokens.
Long context without caching sends 300,560 input tokens per request: 50,000 × 300,560 tokens is about 15 billion tokens, $60,112 a month in input. Nobody should run it this way.
Long context with caching writes the knowledge base to the cache on 600 cold starts ($900) and reads it on the other 49,400 requests (about $2,964), plus the uncached question and system prompt: $3,976 in input. Caching cuts the cost by 15×, which is why long context is viable at all.
RAG sends 3,760 tokens per request: $752 in input, five times cheaper than cached long context, before counting the embedding and vector database costs (small here) and the engineering time (not small). Output is the same $300 in every case.
So with a 300K-token corpus and steady traffic, cached long context is a legitimate choice when you value simplicity over a 4× price difference and the latency of reading 300K cached tokens per request is acceptable. Shrink the corpus to 50K tokens and long context wins outright; grow it past the window, add per-user permissions or frequent updates, and RAG is the only option.
?When does long context win?
In the cost example, the knowledge base shrinks from 300,000 to 30,000 tokens. Roughly what happens to the cached long-context input cost, and how does it compare with RAG's $752?
Show answer
It drops to about $498 a month, now below RAG.
What’s happening
Cache writes scale with the knowledge base: 600 × 30,000 tokens × $5 per million = $90.
Cache reads: 49,400 × 30,000 tokens × $0.20 per million = $296.40.
The uncached part is unchanged: 50,000 × 560 tokens × $4 per million = $112. The total is $90 + $296.40 + $112 = $498.40.
That's below RAG's $752 for 3,760 tokens per request, with no retrieval pipeline to build, tune or evaluate and no risk of missing the right chunk. For small, stable corpora, cached long context is often the better engineering choice, as Anthropic's contextual retrieval write-up also suggests for knowledge bases under about 200,000 tokens.
Classic RAG retrieves once, before the model starts. Agentic RAG gives the model a search tool and lets it decide what to search for, look at the results, and search again until it has what it needs: a tool loop where the tool is your retriever. It handles questions that need several lookups ("compare the refund rules for monthly and yearly plans and say how long the money takes"), questions where the first search reveals what to search next, and corpora split across several sources (a help centre, a ticket system, a database). The cost is latency and tokens (several model calls instead of one) and less predictability: the model might search too little, too much, or in circles, so set a step limit and log the trajectory (Agents).
With Claude, a search tool can return search_result blocks inside its tool_result, and the final answer cites them with the same search_result_location citations as before; the citation's search_result_index counts all search results in the conversation, in order.
The example gives the model a search_help_centre tool backed by the real retriever; the model's decisions (two searches, then an answer) come from scripted replies.
agentic-rag.mjs
import Anthropic from"@anthropic-ai/sdk";import{ pipeline }from"@huggingface/transformers";// Scripted replies (see "How these examples run") ---------------------------------------------// Three replies in the documented shapes (tool_use, then text with search-result citations).// The model's words, its search queries and the citation indices were written for the example.const base ={type:"message",role:"assistant",model:"claude-opus-5-5",stop_sequence:null};constcite=(index, source, title, text)=>({type:"search_result_location",cited_text: text, source, title,search_result_index: index,start_block_index:0,end_block_index:1,});const replies =[{...base,id:"msg_01Pq2WvR8sKd5YtN3mLc7Bx4",stop_reason:"tool_use",usage:{input_tokens:520,output_tokens:61},content:[{type:"text",text:"I'll look up how cancelling a yearly plan works."},{type:"tool_use",id:"toolu_01Gf3kQ8xLm2Vb7Rt4Ns9Pw1",name:"search_help_centre",input:{query:"cancel yearly plan"}}]},{...base,id:"msg_01Tn6HbJ4wQy9Xr2Vf8Kd3Ms",stop_reason:"tool_use",usage:{input_tokens:812,output_tokens:58},content:[{type:"text",text:"That covers whether you get money back, not how long it takes. One more search."},{type:"tool_use",id:"toolu_01Hc5mT2yWq8Kd4Zp7Lx3Rb6",name:"search_help_centre",input:{query:"when does a refund arrive"}}]},{...base,id:"msg_01Wd3LcF7pRz2Nk9Tb5Hy6Qg",stop_reason:"end_turn",usage:{input_tokens:1093,output_tokens:112},content:[{type:"text",text:"Yes: within 30 days of your plan starting or renewing, we refund the unused months.",citations:[cite(1,"help/r2","Refunds","Yearly plans can be refunded within 30 days of the start or renewal date. We refund the unused months, pro rata.")]},{type:"text",text:" The money goes back to the card you paid with, usually within 5 to 10 working days.",citations:[cite(3,"help/r3","Refunds","Refunds go back to the card you paid with and usually arrive within 5 to 10 working days.")]},]},];constfetch=async()=> Response.json(replies.shift());const client =newAnthropic({apiKey:"sk-ant-test", fetch });// for real: new Anthropic()// ----------------------------------------------------------------------------------------------// The Meadowlark help centre (a fictional team-calendar app): 34 chunks, one per section.const chunks =[["p1","Plans and pricing","Meadowlark has three plans. Free covers up to 3 people. Team costs £8 per person per month. Business costs £15 per person per month and adds single sign-on (SSO) and the API."],["p2","Plans and pricing","Paying yearly gives you 12 months for the price of 10. Switch between monthly and yearly billing at any time in Settings > Billing."],["r1","Refunds","Monthly plans are not refunded for unused days. When you cancel, your plan stays active until the end of the month you have paid for."],["r2","Refunds","Yearly plans can be refunded within 30 days of the start or renewal date. We refund the unused months, pro rata."],["r3","Refunds","Refunds go back to the card you paid with and usually arrive within 5 to 10 working days."],["a1","Resetting your password","Choose Forgot password on the sign-in page and enter your work email. We send a reset link that expires after 30 minutes."],["a2","Resetting your password","If your company signs in with SSO, Meadowlark does not store a password for you: reset it with your identity provider, such as Okta or Google Workspace."],["a3","Two-step verification","Turn on two-step verification in Settings > Security. Meadowlark works with authenticator apps such as Google Authenticator and 1Password."],["a4","Two-step verification","You get 10 recovery codes, each usable once. If you lose your phone, sign in with a recovery code or ask your workspace admin to reset two-step verification."],["i1","Google Calendar sync","Connect Google Calendar in Settings > Integrations. Events sync both ways every 5 minutes."],["i2","Google Calendar sync","Private Google events appear in Meadowlark as Busy, without their title or attendees."],["i3","Google Calendar sync","Error GC-403 means Meadowlark lost permission to read your calendar, usually after a Google password change. Reconnect the calendar to fix it."],["i4","Slack notifications","Install the Meadowlark app for Slack from Settings > Integrations. A Slack workspace admin may need to approve it."],["i5","Slack notifications","Meadowlark sends a Slack reminder 10 minutes before each meeting. Type /meadowlark today to see your schedule."],["s1","Booking links","A booking link lets people outside your company pick a free slot in your calendar. Create one from the Booking links page."],["s2","Booking links","You can add buffer time before and after booked meetings, from 5 to 60 minutes."],["s3","Booking links","The Team plan includes up to 5 booking links per person; Business has no limit."],["d1","Exporting your data","Admins can export every calendar and booking as CSV or ICS files from Settings > Data. Export files stay available for 7 days."],["d2","Exporting your data","Business plans can also read data through the REST API, with up to 100 requests per minute per workspace."],["d3","Deleting your workspace","Only the workspace owner can delete a workspace. A deleted workspace can be restored for 14 days; after that, all data is permanently erased."],["e1","Error messages","E401 means your session expired. Sign in again; if it keeps happening, check that your browser allows cookies from meadowlark.example."],["e2","Error messages","E429 means too many requests in a short time. Wait a minute and try again; API clients should slow down and retry with backoff."],["m1","Mobile apps","Meadowlark has an iPhone app in the App Store. It shows your schedule and booking links and sends meeting reminders."],["m2","Mobile apps","On Android, use Meadowlark in your phone's browser; you can add it to your home screen for an app-like experience."],["b1","Invoices and payment","Invoices are emailed to the billing contact on the first day of each billing period. Download past invoices from Settings > Billing > Invoices."],["b2","Invoices and payment","To change the card we charge, open Settings > Billing and choose Update payment method. We accept Visa, Mastercard and American Express."],["a5","Changing your email","Change the email address you sign in with from Profile > Account. We send a confirmation link to the new address before the change takes effect."],["o1","Outlook calendar sync","Connect Outlook or Microsoft 365 in Settings > Integrations. Outlook events sync both ways every 10 minutes."],["o2","Outlook calendar sync","Error OC-401 means your Microsoft sign-in expired. Sign in to Microsoft again from Settings > Integrations to resume syncing."],["t1","Microsoft Teams notifications","Add the Meadowlark app to Microsoft Teams to get meeting reminders and a daily agenda in a Teams chat."],["s4","Booking links","People who book through your link get a confirmation email with links to reschedule or cancel, up to 2 hours before the meeting."],["s5","Booking links","Booking pages show free slots in the visitor's own time zone, detected from their browser."],["e3","Error messages","E403 means your role does not allow this action. Ask a workspace admin to change your role or do it for you."],["n1","Notifications","Turn meeting reminders off, or change how early they arrive, in Profile > Notifications. Each channel (email, Slack, Teams, mobile) has its own setting."],].map(([id, title, text])=>({ id, title, text }));const embed =awaitpipeline("feature-extraction","Xenova/all-MiniLM-L6-v2",{dtype:"q8"});const vectors =(awaitembed(chunks.map((c)=> c.text),{pooling:"mean",normalize:true})).tolist();asyncfunctionsearchHelpCentre(query, k =3){const[q]=(awaitembed([query],{pooling:"mean",normalize:true})).tolist();return vectors.map((v, i)=>({chunk: chunks[i],score: v.reduce((s, x, d)=> s + x * q[d],0)})).sort((a, b)=> b.score - a.score).slice(0, k).map(({ chunk })=>({type:"search_result",source:`help/${chunk.id}`,title: chunk.title,content:[{type:"text",text: chunk.text }],citations:{enabled:true}}));}const tools =[{name:"search_help_centre",description:"Search Meadowlark's help centre. Returns the 3 most relevant sections. Use short, specific queries; search again with a different query if the results don't answer the question.",input_schema:{type:"object",properties:{query:{type:"string",description:"What to search for"}},required:["query"]},}];const messages =[{role:"user",content:"I'm on a yearly plan and want to cancel. Do I get money back, and how soon?"}];// The agent loop: call the model; while it asks for searches, run them and send the results back.for(let step =1; step <=5; step++){const res =await client.messages.create({model:"claude-opus-5-5",max_tokens:4096, tools, messages,system:"You are Meadowlark's support assistant. Search the help centre before answering, and answer only from what you find.",});
messages.push({role:"assistant",content: res.content });if(res.stop_reason !=="tool_use"){const text = res.content.filter((b)=> b.type ==="text").map((b)=> b.text +(b.citations ??[]).map((c)=>` [${c.source}]`).join("")).join("");
console.log(`step ${step}: answer\n ${text}`);// Check every citation against the search results actually sent (indices count across all of them, in order).const sent = messages.flatMap((m)=>(Array.isArray(m.content)? m.content :[])).filter((b)=> b.type ==="tool_result").flatMap((b)=> b.content);const citations = res.content.flatMap((b)=> b.citations ??[]);const ok = citations.every((c)=> sent[c.search_result_index]?.source === c.source && sent[c.search_result_index].content[0].text === c.cited_text);
console.log(`${citations.length} citations, all match the results sent: ${ok}`);break;}const results =[];for(const call of res.content.filter((b)=> b.type ==="tool_use")){const found =awaitsearchHelpCentre(call.input.query);
console.log(`step ${step}: search "${call.input.query}" -> ${found.map((r)=> r.source).join(", ")}`);
results.push({type:"tool_result",tool_use_id: call.id,content: found });}
messages.push({role:"user",content: results });// every result for this turn, in one message}
Result
step 1: search "cancel yearly plan" -> help/r1, help/r2, help/p2
step 2: search "when does a refund arrive" -> help/r3, help/r2, help/r1
step 3: answer
Yes: within 30 days of your plan starting or renewing, we refund the unused months. [help/r2] The money goes back to the card you paid with, usually within 5 to 10 working days. [help/r3]
2 citations, all match the results sent: true
What’s happening
The tool definition describes what the search returns and when to search again; that description is what the model reads to decide how to use it. searchHelpCentre runs real dense retrieval and returns the top 3 chunks as search_result blocks with citations enabled.
Step 1: the model asks for cancel yearly plan. The real retriever returns r1, r2 and p2: the yearly refund rule is there, but nothing about how long refunds take. The results go back as a tool_result in a user message.
Step 2: the model (scripted) notices the gap and searches when does a refund arrive, which returns r3, r2 and r1. This decide-search-read-decide cycle is what makes it agentic: a fixed pipeline would have searched once with the user's whole question.
Step 3: the final answer cites help/r2 and help/r3. Their search_result_index values (1 and 3) count across both tool results: r2 was the second result of the first search, r3 the first of the second (index 3). The check at the end confirms every citation's source and cited text match what was actually sent.
The loop has a hard limit of 5 steps and appends every tool result for a turn in one user message. In production, log each step (query, results, tokens) so you can see when the agent searches badly, and evaluate trajectories as well as answers (Evaluating agents).
GraphRAG
Vector search finds passages similar to the question, which works for "what does X say about Y?" and fails for questions about the corpus as a whole ("what are the main themes across all customer complaints this year?") or for questions that need connections between entities scattered across documents ("which customers on the Business plan reported both sync errors and billing problems?"). GraphRAG (Microsoft Research, "From Local to Global", Edge and colleagues, 2024) builds a knowledge graph at ingest time: a model extracts entities and relationships from every chunk, the graph is clustered into communities, and each community gets a generated summary. Queries can then search the graph (follow relationships from an entity) or the community summaries (for global, "sum up everything" questions), alone or alongside vector search.
The trade-offs are significant: building the graph means running a model over the entire corpus (expensive, and it must be redone or patched as documents change), extraction errors become graph errors, and for ordinary lookup questions plain hybrid search with reranking is usually as good and far cheaper. Reach for graph approaches when your questions are genuinely relational or global and your evaluation shows vector RAG failing on them; a structured database with a text-to-SQL tool is often the simpler answer for relational questions over structured data.