Skip to content

Lesson 24 of 40AI in production

RAG and Embeddings

Give a model your own documents with retrieval: embeddings, chunking, top-k search, cited answers, and how to test it.

17 min read0/4 questions

Ask a model about your company's holiday policy, last week's incident, or a library released after its training, and it either says it does not know or, worse, makes up a plausible answer. The model only knows what was in its training data and what is in its context window right now. Retrieval-augmented generation (RAG) is the standard fix: before the model answers, your code searches your own documents for the passages most likely to help and puts them in the prompt. This lesson explains how that search works, how to build a small version yourself, and how to tell whether it is working.

Why the model does not know your data

A model learns from a huge snapshot of public text, then training stops. Two kinds of knowledge are missing:

  • Private data: your wiki, your tickets, your codebase, your customer contracts. The model never saw them.
  • Recent facts: anything after its training cutoff, such as a new API version or today's prices.

The model will not reliably tell you which of these it is missing. Its job is to predict likely text, so a question about your expense policy gets an answer that sounds like a typical expense policy. That is a hallucination, and it is exactly what RAG is designed to prevent.

You have three ways to give a model your data:

OptionHow it worksGood whenWatch out for
Put it in the promptPaste the documents into the contextData is small enough to fit, a few hundred pages at mostCost per request, context rot as it fills
RAGSearch first, send only the relevant passagesLarge or changing collectionsSearch quality decides answer quality
Fine-tuningTrain the model further on your examplesTeaching a style or formatSlow to update, poor at memorising facts, rarely the first choice

Fine-tuning changes how a model behaves more than what it knows. If the goal is "answer from our documents", it is almost never the right first step: it is expensive, it goes stale the moment a document changes, and it still cannot cite a source. Start with the prompt or with RAG.

Quick check
Your support bot must answer from 40,000 help articles that change every week. Which approach fits best?
Need a nudge? A hint rules out a wrong answer.

Embeddings: meaning as numbers

To search by meaning, you need a way to measure how similar two pieces of text are. That is what an embedding is: a list of numbers (a vector) that represents what a piece of text means. You get it by sending text to an embeddings model, a model trained for exactly this job.

The useful property is that texts with similar meaning get vectors that point in similar directions. "Can I expense a taxi?" and "Are cab rides reimbursed?" share almost no words, but their embeddings land close together. "Python list methods" lands far from both.

To compare two vectors, RAG systems usually use cosine similarity: a score based on the angle between them. 1.0 means the same direction (very similar meaning), 0 means unrelated. You do not need the maths to use it, but the runnable example below computes it in four lines.

A real embedding has hundreds or thousands of numbers, each capturing some learned aspect of meaning. In the toy below, each "dimension" is just a word count. That makes it easy to read, and it also shows clearly what real embeddings fix.

The RAG pipeline

RAG has two halves. Indexing happens ahead of time, whenever documents change. Querying happens on every question.

Indexing once, querying every time
Documents: wiki, PDFs, ticketsDocumentswiki, PDFs, ticketsChunker: split into passagesChunkersplit into passagesVector index: vector + text + sourceVector indexvector + text + sourceQuestion: from the userQuestionfrom the userRetriever: top-k similar chunksRetrievertop-k similar chunksModel: answers with citationsModelanswers with citationssplitembed + storeembed questionnearest chunksprompt + sources

Chunking: split each document into passages small enough to be specific, big enough to make sense alone.

1/5

Chunking matters more than beginners expect. Chunks that are too big mix several topics, so their vector is a blurry average and they match lots of questions weakly. Chunks that are too small lose context: "Taxis need a manager's approval" is fine alone, but "This also applies to trains" means nothing without the sentence before it. Common approaches split by headings or paragraphs, keep chunks to a few hundred tokens, and let neighbouring chunks overlap a little. Always store the source (file and section) with each chunk so answers can cite it.

A vector index (often called a vector database) stores the vectors and finds the nearest ones fast, even across millions of chunks. For a few thousand chunks, a plain list and a loop is fine, which is exactly what the toy does.

Build a toy RAG

This runs the whole pipeline on three tiny policy documents, with no network and no real model. The "embedding" is a word count with stop words removed, so it only matches shared words. Read the output carefully: the misses are as instructive as the hits.

Python
import mathimport refrom collections import Counter DOCS = { "handbook.md": "Staff get 25 days of paid holiday a year. Unused holiday days carry over until March. " "Book holiday in the HR portal at least two weeks ahead.", "expenses.md": "Submit expenses within 30 days with a receipt. Meals on business trips are covered " "up to 40 euros a day. Taxis need a manager's approval.", "it-policy.md": "Laptops are replaced every three years. Report a lost laptop to IT within 24 hours. " "Never store customer data on a personal device.",}STOP = {"a", "an", "the", "of", "to", "in", "on", "with", "and", "are", "is", "get", "do", "how", "many", "what", "i", "my", "can", "at", "up", "for", "every", "be"} def chunk(text, size=1): """Split a document into chunks of `size` sentences.""" sentences = re.split(r"(?<=\.)\s+", text.strip()) return [" ".join(sentences[i:i + size]) for i in range(0, len(sentences), size)] def embed(text): """Toy 'embedding': word counts. A real embeddings model returns a dense vector of meaning.""" words = re.findall(r"[a-z0-9']+", text.lower()) words = [w[:-1] if w.endswith("s") and len(w) > 3 else w for w in words] # crude plural fix return Counter(w for w in words if w not in STOP) def cosine(a, b): dot = sum(a[w] * b[w] for w in a) norm = math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values())) return dot / norm if norm else 0.0 # Indexing: done once, ahead of time.index = []for source, text in DOCS.items(): for n, piece in enumerate(chunk(text), start=1): index.append({"id": f"{source}#{n}", "text": piece, "vec": embed(piece)})print(f"indexed {len(index)} chunks from {len(DOCS)} documents\n") def retrieve(question, k=2, min_score=0.15): q = embed(question) scored = sorted(((cosine(q, c["vec"]), c) for c in index), key=lambda x: x[0], reverse=True) return [(round(s, 2), c) for s, c in scored[:k] if s >= min_score] def build_prompt(question): hits = retrieve(question) if not hits: return None, [] sources = "\n".join(f'<source id="{c["id"]}">{c["text"]}</source>' for _, c in hits) prompt = (f"{sources}\n\nAnswer using only the sources above and cite source ids. " f"If the answer is not in them, say so.\nQuestion: {question}") return prompt, hits for question in ["How many holiday days do I get?", "Is a taxi covered on a business trip?", "What is the office wifi password?"]: prompt, hits = build_prompt(question) print("Q:", question) if not hits: print(" no source scored high enough: answer 'not in the documents'\n") continue for score, c in hits: print(f" {score:.2f} {c['id']}") print() print("--- prompt sent to the model for the taxi question ---")print(build_prompt("Is a taxi covered on a business trip?")[0])print() # Evaluate retrieval on its own: did the right chunk come back in the top k?EVAL = [("Do unused holiday days carry over?", "handbook.md#2"), ("How fast must I report a lost laptop?", "it-policy.md#2"), ("What is the daily meal limit?", "expenses.md#2"), ("Will the company pay for my dinner when travelling?", "expenses.md#2")]found = 0for question, expected in EVAL: ids = [c["id"] for _, c in retrieve(question)] ok = expected in ids found += ok print(f"{'hit ' if ok else 'MISS'} {question} -> {ids}")print(f"recall@2: {found}/{len(EVAL)}")
Output
Press Run (⌘ Enter) to see what happens.

Three things to notice:

  1. The wifi question returned nothing. No chunk scored above the threshold, so the system can say "not in the documents" instead of letting the model guess. Without that threshold, the top two chunks would be sent anyway, and a model might stretch them into an answer.
  2. The taxi question ranked the wrong chunk first. The meals sentence shares "business" and "trip", so it beat the taxi sentence. Both made the top 2, so the model still sees the answer, but this is the problem reranking solves (below).
  3. The dinner question missed completely. "pay for my dinner when travelling" shares no words with "meals on business trips are covered". A real embeddings model would place them close together, because it compares meaning, not spelling. That gap is the whole reason embeddings exist.

Try changing min_score, k, or the chunk size, and watch the results move.

Predict the outputPython

What does this print?

a = {"refund": 1, "order": 1}
b = {"refund": 1, "policy": 1}
shared = [w for w in a if w in b]
print(len(shared))
Need a nudge? Hints walk you through it.

Writing the prompt

The retrieved chunks are only useful if the prompt tells the model how to use them. Three rules carry most of the weight:

  • Label every source with an id, for example in XML-style tags, so the model can cite them and you can check the citation.
  • Tell it to answer only from the sources. Otherwise it blends in what it remembers from training.
  • Give it a way out: "If the answer is not in the sources, say you do not know." Models answer anyway unless you explicitly allow them not to.
A RAG prompt, top to bottom
  1. System promptanswer only from sources, cite ids, admit gaps
  2. Sourceslabelled chunks from the retriever
  3. Questionthe user's words, unchanged

The rules stay the same on every request, so they go first, where prompt caching can reuse them.

1/3

Here is the shape with the Claude API (not runnable here; it needs a key and the network):

answer.py
import anthropic
 
client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
 
def answer(question, chunks):
    sources = "\n".join(f'<source id="{c["id"]}">{c["text"]}</source>' for c in chunks)
    response = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=16000,
        system="Answer only from the sources. Cite source ids in brackets. "
               "If the sources do not contain the answer, say you do not know.",
        messages=[{"role": "user", "content": f"{sources}\n\nQuestion: {question}"}],
    )
    return "".join(block.text for block in response.content if block.type == "text")

Put the stable instructions in the system prompt and the changing sources and question in the message. Then check citations in code: if the answer cites expenses.md#3, confirm that id was actually among the sources you sent.

Put it in order5 steps

Put one RAG query in order, from question to answer.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Making retrieval better

Hybrid search runs keyword search and vector search together and merges the results. Keywords are good at exact things embeddings can blur: error codes, product names, function names like applyCoupon. Vectors are good at meaning and paraphrase. Together they cover each other's gaps, which is why hybrid is a common default in production.

Reranking is a second pass. Retrieve a generous set, say the top 30, then use a slower, more careful model to score each chunk against the question and keep the best 5. The first search is fast and rough; the reranker is precise. In the toy, a reranker would have put the taxi sentence above the meals sentence.

Metadata filters narrow the search before it runs: only documents from this product, this year, or this customer. Filtering also stops one customer's data from leaking into another customer's answer, which is a security property, not only a quality one.

Evaluating retrieval and answers separately

A RAG system can fail in two different places, and you fix them differently:

  • Retrieval failed: the right chunk never reached the prompt. No prompt change can fix that. Fix chunking, hybrid search, reranking or k.
  • Generation failed: the right chunk was there, but the model ignored it, misread it, or did not cite it. Fix the prompt or the model.

So test them separately. For retrieval, build a list of real questions, each with the chunk that should come back, and measure recall@k: the share of questions where the right chunk is in the top k. The toy above prints recall@2 at the end. For answers, use the methods in the evals lesson: check citations in code, and grade correctness with exact checks or a rubric.

Quick checkPick all that apply
Users say the bot gives wrong answers about refunds. You check, and the refund policy chunk is not among the retrieved chunks for those questions. What should you change first? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

When long context is simpler

RAG adds moving parts: a chunker, an embeddings model, an index, a re-indexing job, thresholds to tune. Current models have context windows of up to a million tokens, so if your whole knowledge base fits comfortably, just put it in the prompt. With prompt caching, the repeated document prefix becomes much cheaper on later requests. Long context is the better choice when the data is small, changes rarely, and questions need to connect facts from many places at once. Move to RAG when the data outgrows the window, when cost per request matters, or when you need fine-grained access control over which documents each user can see.

Key terms
RAG
Retrieval-augmented generation: search your documents first, then give the model the best passages to answer from.
embedding
A vector of numbers representing a text's meaning, so similar meanings land close together.
chunking
Splitting documents into passages small enough to be specific but complete enough to make sense alone.
vector index
A store of chunk vectors, text and sources that quickly finds the nearest vectors to a query.
top-k
The k highest-scoring chunks returned by a search, often 3 to 10.
hybrid search
Combining keyword search and vector search so exact terms and paraphrases both match.
recall@k
The share of test questions where the correct chunk appears in the top k results.