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.
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:
| Option | How it works | Good when | Watch out for |
|---|---|---|---|
| Put it in the prompt | Paste the documents into the context | Data is small enough to fit, a few hundred pages at most | Cost per request, context rot as it fills |
| RAG | Search first, send only the relevant passages | Large or changing collections | Search quality decides answer quality |
| Fine-tuning | Train the model further on your examples | Teaching a style or format | Slow 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.
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.
Chunking: split each document into passages small enough to be specific, big enough to make sense alone.
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.
Press Run (⌘ Enter) to see what happens.Three things to notice:
- 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.
- 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).
- 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.
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))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.
The rules stay the same on every request, so they go first, where prompt caching can reuse them.
Here is the shape with the Claude API (not runnable here; it needs a key and the network):
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 one RAG query in order, from question to answer.
- Tap the steps below in the right order.
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.
None picked yet
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.
- 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.