AI-native engineering · L2RAG: retrieval-augmented generation

RAG: retrieval-augmented generation

Ground answers in your own documents, check who may read them, and measure retrieval before you blame the model.

L2 SeniorAI-native engineering19 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 21 Oct 2026 · How we check content
AI tools change fast: we review this lesson every quarter (next by 19 Jan 2027).
Section 1 of 8

What broke

In November 2022, Jake Moffatt's grandmother died. The same day, Moffatt went to Air Canada's website to book a flight at its lower bereavement fares. Moffatt asked the website's support chatbot about these fares. 1

The chatbot said a passenger who had already travelled could ask for a reduced bereavement rate within 90 days of the ticket date. The words "bereavement fares" in its answer linked to the airline's own policy page. That page said the policy does not apply to requests made after travel is completed. 1

Moffatt trusted the chatbot, booked two flights, and applied for the lower rate within the 90 days. Air Canada staff then said the airline did not allow requests after travel. In an email, an airline representative admitted the chatbot had used "misleading words". 1

At the tribunal, Air Canada argued that it could not be held liable for what its chatbot said. The tribunal said this treats the chatbot as a separate legal entity, and called it "a remarkable submission". It said the airline is responsible for all the information on its website, whether it comes from a static page or a chatbot. It also asked why a customer should have to double-check one part of a website against another. The airline had to pay $812.02: $650.88 in damages, plus interest and tribunal fees. 1

Air Canada gave no information about how its chatbot worked, and the decision does not say how it was built. 1 But the lesson for anyone who ships one is clear. The answer and the policy page disagreed. Our advice: your system must answer from the real policy text, and show the user where the answer came from.

Section 2 of 8

The idea in simple words

A language model alone is not enough for questions about your data. There are three reasons.

  • It has a knowledge cutoff. Every model has a date after which its knowledge is not reliable. Anthropic lists this date for each Claude model. 9 Your price change from last week is not in it.
  • It has never seen your private data. Your policies, tickets and contracts were not in its training data.
  • It can hallucinate. Models sometimes write text that is false, or that does not match the text you gave them. 8

The RAG paper of 2020 described the core problem. When knowledge is stored only in model weights, it is hard to update, and hard to show where a fact came from. 2 Its answer was to add a second memory: a vector index of Wikipedia that the model reads from at answer time. 2

So RAG works like an open-book exam. Your app searches your documents, puts the few passages that matter in the prompt, and the model answers from them with citations.

The key idea. In RAG, the model can only be as good as the text you give it. When an answer is wrong, first check whether retrieval found the right text. So treat retrieval as the main part of the system, and measure it.

Section 3 of 8

How it works

Step through one request with Next and Back.

One RAG request: search, filter by permission, then answer with citations“Can I get a refund after my trip?” embed[0.12, −0.48, 0.91, …] top 3 nearest#1 Refund policy · public#2 Bereavement fares · public#3 Staff override notes · staff only user is a customer → drop #3 build promptPromptUse only these sources. Cite them.If they do not answer, say “I don't know”.[1] Refund policy · [2] Bereavement fares ✓ Answer with citations [1] [2] SeniorPath
  1. The question goes to an embedding model. It turns the text into a vector, a long list of numbers that captures its meaning.
  2. Vector search finds the 3 stored chunks whose vectors are nearest to the question. One of them is an internal note for staff.
  3. A permission filter checks each chunk against what this user may read. The user is a customer, so the staff note is dropped before the model ever sees it.
  4. The app builds the prompt. It holds the rules, the question and the 2 allowed chunks, each with a number the model can cite.
  5. The model answers from the 2 chunks and cites them. The user can open [1] and [2] to check the answer against the real policy.
Step 1 of 5

Before any question: index your documents

  1. Chunk. Split each document into small pieces. Anthropic says chunks are usually no more than a few hundred tokens. 3
  2. Embed. An embedding model turns each chunk into a vector, a list of numbers. The distance between two vectors measures how related the texts are. 4
  3. Store. Save each vector with its text, its source link, and who may read it. A vector database does this. So does Postgres with pgvector, which supports exact and approximate nearest-neighbour search. 5

At question time

  1. Retrieve. Embed the question the same way, and find the top k chunks with the nearest vectors. For how search indexes work in general, see Search systems and inverted indexes.
  2. Filter. Drop every chunk the user may not read.
  3. Prompt. Put the allowed chunks into the prompt, each with a number. Tell the model to use only these sources and to cite them. Let it say "I don't know" when the sources do not answer. Anthropic's guide lists all three methods to reduce hallucinations. 8
  4. Answer. Show the answer with links to the cited chunks, so the user can check.

Hybrid search and re-ranking

Vector search finds text with a similar meaning. But embeddings can miss exact matches, such as an error code like "TS-999". 3 BM25 is a keyword ranking function that finds exact words and phrases. 3 Hybrid search runs both and merges the two lists.

One way to merge them is reciprocal rank fusion (RRF). Each result gets 1 / (k + rank) from each list, and the points are added up. Elasticsearch uses k = 60 by default. 6 RRF needs no tuning, and the scores from the two lists do not need to be related. 6 For hybrid search, pgvector suggests Postgres full-text search, merged with RRF or a re-ranking model. 5

Re-ranking adds one more step. A re-ranking model scores the top results again, and only the best ones go into the prompt. It adds some latency, and you trade more re-ranked chunks against speed and cost. 3

Chunking choices

Chunk size, chunk borders and overlap all change what retrieval finds. 3 A small chunk can lose its meaning. Anthropic's example is a chunk that says revenue grew by 3%, without saying which company or which quarter. 3 Its fix, "contextual retrieval", adds a short note about the whole document to each chunk before indexing. 3

Anthropic measured this on codebases, fiction, ArXiv papers and science papers. The failure rate is the share of relevant chunks missing from the top 20, averaged over these sets. Contextual embeddings plus contextual BM25 cut the top-20 retrieval failure rate by 49%, from 5.7% to 2.9%. Adding re-ranking cut it by 67%, to 1.9%. 3 These are their numbers on their data. Your data will differ, so measure your own.

Evaluation: measure, don't guess

Test the two halves apart.

  • Retrieval quality. For each test question, write down which chunks should come back. Then measure recall@k: the share of those chunks that appear in the top k. Anthropic's study uses exactly this kind of metric. 3
  • Answer quality. Is the answer correct, and is every claim backed by a cited chunk? Anthropic's eval guide says to mirror your real task mix, include edge cases, and grade automatically where you can. 7 If a model grades the answers, it suggests using a different model from the one that wrote them. 7

Our advice: start with 30 to 50 real questions from users or support tickets. Add questions where the right answer is "I don't know". Run the set after every change to chunking, the embedding model, top-k or the prompt.

Common failures

  • Wrong chunk retrieved. The answer sounds right but cites the wrong policy. Look at the retrieved chunks first.
  • Stale index. The document changed, but the old chunks are still in the index. Re-index on every change, and delete chunks of deleted documents.
  • Prompt injection from documents. A retrieved page can contain hidden instructions. OWASP calls this indirect prompt injection, and says RAG does not fully remove the risk. 10 Mark retrieved text clearly as untrusted data, and give the model only the access and tools it needs. 10
  • Leaking documents. If the index holds documents for different users, weak access control can leak them. OWASP advises permission-aware vector stores. 11 Filter at retrieval time, not in the prompt. One trap: with approximate indexes in pgvector, a WHERE filter runs after the index scan, so you may get fewer results than you asked for. 5

Cost and latency

Each request adds steps: embed the question, search, maybe re-rank, then a longer prompt. More chunks mean more input tokens. Re-ranking costs time but can lower model cost, because the model reads less text. 3 If your whole knowledge base is under 200,000 tokens (about 500 pages), Anthropic suggests you may not need RAG at all. Put it all in the prompt and use prompt caching. 3

Section 4 of 8

Trade-offs

This table is our own summary, except where a source is cited.

ApproachFresh dataCan cite its sourceCost and latencyUse it when
Whole knowledge base in the promptYes Edit the text and it is live.Yes More tokens per call. Caching helps.The data is small, under about 200,000 tokens.
RAG with vector searchYes , if you re-index on change.Yes Embedding and a search per question.Users ask in their own words, and data is large.
RAG with keyword search (BM25)Yes Yes Cheap and fast.Users search for exact codes, names or IDs.
Hybrid search plus re-rankingYes Yes The most steps and the slowest.Both kinds of question, and quality matters most.
Fine-tuningNo Facts in model weights are hard to update. 2No The paper calls tracing facts in weights an open problem. 2Our view: a training run for every change.Our view: to change style or format, not to add facts.

Simple rule: start with the simplest design that passes your test set. Add hybrid search or re-ranking only when the numbers show you need it.

Section 5 of 8

At work: how a senior uses this

  • When an answer is wrong, first ask: "Was the right chunk retrieved?" Log the retrieved chunk IDs for every request so you can answer this.
  • Build the test set before you tune anything. Keep it in the repo and run it in CI.
  • Treat permissions as part of retrieval. Store the access rules next to each chunk, and filter in the query.
  • When a policy changes, re-index it the same day and add a test question for it.
  • Show citations in the user interface. If the model cannot cite a source, it should say it does not know.
  • Ask your team who owns the bot's answers. The tribunal's view was clear: the company does. 1
Section 6 of 8

With AI

What to ask the agent

"Here are 20 real user questions and our docs folder. For each question, list the document sections that should be retrieved. Mark any question our docs cannot answer."

"Write a script that runs our RAG pipeline on this test set and prints recall@5 and the retrieved chunk IDs for each question that failed."

"Review this retrieval code. Show me every path where a chunk can reach the prompt without the user's permission check."

What to check yourself

  • The expected chunks in the test set are right. Check a sample by hand, because the agent may guess.
  • The permission filter runs inside the search query, before the prompt is built, and a test proves it.
  • The test set includes questions that should get "I don't know".
  • Retrieved text is marked as data in the prompt, and the model has no tools it does not need.
  • You compared numbers before and after each change, not only a few examples.
Section 7 of 8

Check yourself

1. Your support bot gives a wrong answer about the refund window. What should you check first?

Show answer

Which chunks retrieval returned for that question, and whether the right policy text was among them. Check retrieval first. If the right text never reached the prompt, no model can answer from it.

2. Your index holds HR documents. Some are for managers only. Where must you enforce this?

Show answer

At retrieval time, so chunks the user may not read never enter the prompt. A prompt rule is advice the model may ignore. A filter at retrieval time means the model never sees what the user may not read.

3. Users search for error codes like "TS-999", and vector search keeps missing them. What helps most?

Show answer

Add keyword search (BM25) and merge both result lists. Embeddings capture meaning but can miss exact strings. Keyword search finds exact terms, so hybrid search covers both.

4. Your whole knowledge base is about 50 pages and changes once a month. What is the simplest good design?

Show answer

Put all the pages in the prompt, with prompt caching. Anthropic notes that a knowledge base under 200,000 tokens can go straight into the prompt. Our advice is to add RAG when it no longer fits.

5. You changed the chunk size. How do you know if it helped?

Show answer

Run your test set and compare recall@k and answer scores before and after. Measure, don't guess. A fixed test set shows whether the right chunks are now found and whether answers improved.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 11 sources and related lessons
  1. Civil Resolution Tribunal (British Columbia), Moffatt v. Air Canada, 2024 BCCRT 149, decision of 14 February 2024 (opens in a new tab)
    The full decision (a short PDF). Read paragraphs 13 to 29 for what the chatbot said and why the airline was responsible, and paragraph 44 for the amount.
  2. Lewis et al., “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks”, NeurIPS 2020 (arXiv:2005.11401) (opens in a new tab)
    The paper that named RAG. The abstract explains why knowledge stored only in model weights is hard to update and to trace.
  3. Anthropic, “Introducing Contextual Retrieval” (September 2024) (opens in a new tab)
    Chunking, BM25 plus embeddings, re-ranking, and measured retrieval failure rates. Also when to skip RAG and put everything in the prompt.
  4. OpenAI, “Vector embeddings”, API documentation (opens in a new tab)
    A neutral definition of an embedding and how distance between vectors measures relatedness.
  5. pgvector, README (GitHub) (opens in a new tab)
    Vector search inside Postgres. Index types, filtering with WHERE, and hybrid search with full-text search.
  6. Elastic, “Reciprocal rank fusion”, Elasticsearch reference (opens in a new tab)
    How to merge several result lists with one simple formula, and the default value of its constant k.
  7. Anthropic, “Define success criteria and build evaluations”, Claude documentation (opens in a new tab)
    How to write measurable success criteria and build a test set that you can grade automatically.
  8. Anthropic, “Reduce hallucinations”, Claude documentation (opens in a new tab)
    Let the model say "I don't know", ground it in quotes, and make it cite.
  9. Anthropic, “Models overview”, Claude documentation (opens in a new tab)
    Each model's "reliable knowledge cutoff" date and what that date means.
  10. OWASP, “LLM01:2025 Prompt Injection”, OWASP Top 10 for LLM Applications 2025 (opens in a new tab)
    Direct and indirect prompt injection, and why RAG does not fully fix it.
  11. OWASP, “LLM08:2025 Vector and Embedding Weaknesses”, OWASP Top 10 for LLM Applications 2025 (opens in a new tab)
    Data leaks through vector stores, and the advice to make retrieval permission-aware.

Case studies: Anthropic: Contextual retrieval: add context to chunks before indexing

Related: Prompt and context engineering · Vector databases and ANN search (coming soon) · Search systems and inverted indexes · Evals for LLM systems · Guardrails, cost and latency for LLM features (coming soon)

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper