RAG Basics

How retrieval-augmented generation finds relevant passages, puts them in the prompt, and how to choose between search methods and tune retrieval.

15 minLesson 4 of 8
On this page
  1. How RAG works
  2. Retrieval by hand
  3. Code for retrieval and prompt building
  4. Choosing how to search
  5. Choosing how many passages to retrieve
  6. Improving the retrieved passages
  7. When RAG is the right tool
  8. Pitfalls
  9. What this changes in practice
  10. Check yourself
  11. What to practise next

Retrieval-augmented generation, or RAG, is a technique where the system searches your own documents for passages related to a question, adds those passages to the prompt, and asks the model to answer from them. It lets a model answer questions about material it was never trained on, such as your help pages, handbook or meeting notes, and it lets you cite where each answer came from.

Without retrieval, the model answers from its training data and produces a confident, generic answer that may not match your documents. Sending the whole collection in every prompt is usually impossible, because a real document collection is far larger than the context window.

How RAG works

A RAG system does three things for every question. It retrieves the passages most related to the question, it augments the prompt by adding those passages and telling the model to answer from them, and it generates the answer, ideally with a citation for each claim. The model itself is unchanged. RAG is a form of context engineering in which the material in the prompt is selected automatically for each question.

The search usually matches meaning rather than exact words, using embeddings, because people rarely phrase a question in the words of the document. Someone asks "when do I get my money back?" and the answer sits under a heading called "Refund processing times".

Indexing (once) documents split in chunks embed each vector store Every question question embed compare,take top k prompt withpassages answer stored vectors
Indexing runs once, and again whenever the documents change. The query path runs for every question.

Indexing is slow, so it happens ahead of time. Each document is cut into passages called chunks (the next lesson covers how), each chunk is turned into a vector, and the vectors are stored. When a question arrives, the system only has to embed the question and compare it with the stored vectors.

Retrieval by hand

The example below uses a bookshop help centre with five chunks. To keep the arithmetic readable, each embedding has only three numbers, which you can think of as "about money", "about shipping" and "about accounts". Real embeddings have hundreds or thousands of numbers, but the calculation is the same.

The question "When will I get my money back?" embeds to [5, 1, 0], which has a length of √26 ≈ 5.10. Each chunk is scored with cosine similarity (explained in Embeddings) and the two highest scores are kept.

Top 2 chunks for "When will I get my money back?"Use the arrows or ← → keys
q = embed(question)for each chunk c:  score[c] = cosine(q, vector[c])sort chunks by score, highest firstreturn the first k
  1. chunk
    0refundc
    1returns
    2delivery
    3password
    4gift card
    score
    01
    1
    2
    3
    4
    q
    [5, 1, 0]
    dot
    21

    1Refund times, [4, 1, 0]: dot = 20 + 1 + 0 = 21, length √17 ≈ 4.12. Cosine = 21 / (5.10 × 4.12) ≈ 1.00: nearly the same direction, even though the question and the chunk share no words.

  2. chunk
    0refund
    1returnsc
    2delivery
    3password
    4gift card
    score
    01
    10.92
    2
    3
    4
    q
    [5, 1, 0]
    dot
    17

    2Returns rules, [3, 2, 0]: dot = 15 + 2 = 17, length √13 ≈ 3.61. Cosine ≈ 0.92: the chunk covers money and sending items back.

  3. chunk
    0refund
    1returns
    2deliveryc
    3password
    4gift card
    score
    01
    10.92
    20.19
    3
    4
    q
    [5, 1, 0]
    dot
    5

    3Delivery times, [0, 5, 1]: dot = 0 + 5 + 0 = 5, length √26 ≈ 5.10. Cosine ≈ 0.19. The chunk is mostly about shipping, so it points away from a question about money.

  4. chunk
    0refund
    1returns
    2delivery
    3passwordc
    4gift card
    score
    01
    10.92
    20.19
    30
    4
    q
    [5, 1, 0]
    dot
    0

    4Password reset, [0, 0, 5]: dot = 0. Cosine = 0. The chunk is unrelated to the question.

  5. chunk
    0refund
    1returns
    2delivery
    3password
    4gift cardc
    score
    01
    10.92
    20.19
    30
    40.88
    q
    [5, 1, 0]
    dot
    10

    5Gift cards are non-refundable, [2, 0, 1]: dot = 10, length √5 ≈ 2.24. Cosine ≈ 0.88. This is close behind because it is also about money.

  6. chunk
    0refund
    1returns
    2gift card
    3delivery
    4password
    score
    01
    10.92
    20.88
    30.19
    40
    k
    2
    comparisons
    5

    6Sort and keep k = 2: refund times and returns rules go into the prompt. The gift card chunk came a close third, so the choice of k matters.

1 / 6

Code for retrieval and prompt building

The code below does the same retrieval and builds the prompt, using the toy vectors from the trace in place of a real embedding model.

const dot = (a, b) => a.reduce((sum, x, i) => sum + x * b[i], 0);
const cosine = (a, b) => dot(a, b) / Math.sqrt(dot(a, a) * dot(b, b));
 
function topK(queryVec, chunks, k) {
  return chunks
    .map((c) => ({ ...c, score: cosine(queryVec, c.vec) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, k);
}
 
function buildPrompt(question, passages) {
  const sources = passages.map((p, i) => `[${i + 1}] ${p.text}`).join("\n");
  return `Answer using only the sources below. Cite them like [1].
If they do not contain the answer, say "I don't know."

${sources}

Question: ${question}`;
}
 
const chunks = [
  { text: "Refunds reach your card 5 to 7 days after we receive the return.", vec: [4, 1, 0] },
  { text: "You can return items within 30 days of delivery.", vec: [3, 2, 0] },
  { text: "Standard delivery takes 2 to 4 working days.", vec: [0, 5, 1] },
  { text: "Reset your password from the sign-in page.", vec: [0, 0, 5] },
  { text: "Gift cards cannot be refunded.", vec: [2, 0, 1] },
];
const best = topK([5, 1, 0], chunks, 2);
console.log(buildPrompt("When will I get my money back?", best));
import math
 
def dot(a, b):
    return sum(x * y for x, y in zip(a, b))
 
def cosine(a, b):
    return dot(a, b) / math.sqrt(dot(a, a) * dot(b, b))
 
def top_k(query_vec, chunks, k):
    scored = [{**c, "score": cosine(query_vec, c["vec"])} for c in chunks]
    scored.sort(key=lambda c: c["score"], reverse=True)
    return scored[:k]
 
def build_prompt(question, passages):
    sources = "\n".join(f"[{i + 1}] {p['text']}" for i, p in enumerate(passages))
    return (
        "Answer using only the sources below. Cite them like [1].\n"
        'If they do not contain the answer, say "I don\'t know."\n\n'
        f"{sources}\n\nQuestion: {question}"
    )
 
chunks = [
    {"text": "Refunds reach your card 5 to 7 days after we receive the return.", "vec": [4, 1, 0]},
    {"text": "You can return items within 30 days of delivery.", "vec": [3, 2, 0]},
    {"text": "Standard delivery takes 2 to 4 working days.", "vec": [0, 5, 1]},
    {"text": "Reset your password from the sign-in page.", "vec": [0, 0, 5]},
    {"text": "Gift cards cannot be refunded.", "vec": [2, 0, 1]},
]
best = top_k([5, 1, 0], chunks, 2)
print(build_prompt("When will I get my money back?", best))

The prompt it prints, together with a plausible reply from a model, looks like this.

Augmented promptIllustrative example. Real replies vary.
You
Answer using only the sources below. Cite them like [1]. If they do not contain the answer, say "I don't know." [1] Refunds reach your card 5 to 7 days after we receive the return. [2] You can return items within 30 days of delivery. Question: When will I get my money back?
Model
Your refund reaches your card 5 to 7 days after the shop receives your return [1]. You need to send the item back within 30 days of delivery [2].

The instruction to say "I don't know" is important. When retrieval finds nothing useful and that instruction is missing, the model falls back on its training data and gives an answer that sounds just as grounded as a correct one.

Retrieval does not have to use embeddings. There are three common choices, and each fails in its own way.

Embedding search compares the meaning of the question with the meaning of each chunk. It handles paraphrases well, so "money back" finds "refund". It is weaker on exact identifiers. A product code, an error number or a person's name has little meaning for an embedding model, so the chunk that contains that exact string may not rank near the top.

Keyword search scores chunks by how many of the question's words they contain, weighting rare words more heavily than common ones. It finds exact strings reliably and needs no embedding model. It fails when the question and the document use different words for the same thing, because "money back" shares no words with "refund".

Hybrid search runs both methods and merges the two ranked lists. It is the usual choice when the documents contain a mix of ordinary prose and exact identifiers, such as a support knowledge base that mentions error codes. The two rankings use scores on different scales, so they are usually merged by rank rather than by score. A common rule is reciprocal rank fusion, which gives each chunk a value of 1 divided by (a constant plus its rank) in each list and adds the values. The cost is a second index to maintain.

MethodFindsMisses
Embedding searchParaphrases and related wordingExact codes, names and numbers
Keyword searchExact words and identifiersDifferent wording for the same idea
Hybrid searchBoth kinds of matchLittle, but it needs two indexes and a rule for merging their results

Choosing how many passages to retrieve

The number of passages, called k, is a trade-off. If k is too small, the passage that holds the answer may rank just below the cutoff and never reach the model. If k is too large, the prompt fills with loosely related text, which costs tokens and gives the model more chances to latch onto the wrong passage. In the trace above, the gift card chunk scored 0.88, close behind the returns chunk at 0.92, and k = 2 left it out.

A fixed k always returns something, even for a question the documents do not cover. Adding a minimum score fixes this: passages below the threshold are dropped, and if none remain, the system can reply that it found nothing instead of passing weak matches to the model. The right threshold depends on the embedding model, so find it by testing questions whose answers you know.

Improving the retrieved passages

When the right passage exists but does not reach the prompt, three changes are the usual fixes.

Reranking retrieves a generous number of candidates, such as 30, and then reorders them with a slower model that reads the question and each candidate together. Embedding search compares two vectors that were computed separately, so it is fast but approximate; a reranker sees both texts at once and is more accurate. You then keep only the top few for the prompt.

Query rewriting is needed when the user's message is not a good search query by itself. In a conversation, "and what about for gift cards?" has no meaning without the earlier turns, so the system first asks the model to rewrite it as a standalone question, such as "What is the refund policy for gift cards?", and searches with that.

Metadata filtering restricts the search to chunks whose stored attributes match, such as the product, the document version or the language. It is also how access control works: the filter must remove the chunks the current user is not allowed to read before they are retrieved, because anything that reaches the prompt can appear in the answer.

When RAG is the right tool

Use RAG when the material is too large to send whole, changes often, or is private. Updating the documents updates the answers, with no retraining.

Skip RAG when the material is small. If the whole handbook fits comfortably in the prompt, send all of it, which removes the possibility of a retrieval miss.

Do not use fine-tuning as a substitute for facts that change. Fine-tuning is good for teaching a style or a format, but it is a poor place to store facts you will need to correct next month, and a fine-tuned model cannot point to a source.

ApproachTimeSpaceWhy
Compare with every chunkO(n·d + n log n)O(n)n chunks of d numbers each, followed by a sort. This is fast enough for thousands of chunks.
Approximate indexmuch less than O(n·d)O(n·d)Vector databases check only the promising regions, trading a little accuracy for a large speed-up at millions of chunks.

Pitfalls

What this changes in practice

When a RAG answer is wrong, look at the retrieved passages before you change the prompt. If the right passage is missing, the problem is in indexing or search. If it is present and the answer is still wrong, the problem is in the prompt or the model. Keeping these two cases apart saves a lot of wasted prompt editing.

Build a small test set of real questions, each with the passage that should answer it, and measure how often that passage appears in the top k. Rerun the test whenever you change the chunk size, the embedding model or k. Record what each change does to the result, in the same way you would for the evals of a prompt.

Try it: Retrieval or generation

A staff assistant was asked "How many days of parental leave do we get?" It answered "Most companies offer 12 weeks." The retrieved passages were: [1] "Annual leave: 25 days per year, plus public holidays." [2] "Sick leave must be reported to your manager before 10am." Find the two separate failures and say what you would change.

Show a sample answer

The first failure is in retrieval. Neither passage is about parental leave. Either the policy is not in the index, or it was chunked or embedded badly so that a generic match on "leave" ranked above it. Check that the policy is in the store, then search for it directly to see where it ranks.

The second failure is in generation. The model should have said that the passages did not answer the question, but it used general knowledge instead. Add an instruction such as "If the sources do not answer the question, reply: I couldn't find this in the staff handbook." Requiring citations also helps, because an answer with no source stands out.

Fixing only the prompt makes the assistant honest but unhelpful. Fixing only retrieval leaves it free to invent an answer the next time a question is not covered. Both need fixing.

Check yourself

Quick check

Why does RAG usually search with embeddings rather than exact keywords?

Your company's policies change monthly. What keeps a staff assistant's answers current most easily?

In the trace, the gift-card chunk scored 0.88 but was left out. What would happen with k = 3?

What to practise next

Retrieval quality starts with how documents are cut up. Chunking and Retrieval covers chunk size, overlap, and fixes for the most common misses.