Sub topic 2
The classic RAG pipeline
This chapter assumes you can read basic Python, know what a prompt and a completion are, and have a high-level idea of embeddings and similarity search. You don't need to build an index to follow it.
Classic retrieval-augmented generation (RAG) fixes one weakness of language models. A model only knows what was in its training data and what you put in the prompt. RAG puts the right facts in the prompt at question time. The rest of this tutorial changes who decides what goes in. First you need a clear picture of the baseline.
The four steps
A classic RAG pipeline has two phases. Indexing happens ahead of time. Answering happens on every question.
- Index (offline). Split documents into chunks, embed each chunk, and store the vectors with the chunk text and an id.
- Retrieve. Embed the user's question and ask the vector store for the k nearest chunks.
- Augment. Paste those chunks into a prompt together with the question and some instructions.
- Generate. Send the prompt to the model and return its completion.
The important property is in the control flow. Retrieval is a fixed stage. It runs exactly once, for every question, and the query is the user's own words. The model never sees the search happen and cannot ask for a second one.
A minimal implementation
The function below takes the three moving parts as arguments, so it works with any embedding model, vector store or LLM client.
def answer_with_rag(question, embed, search, generate, k=4):
# Classic RAG: retrieval always runs once, with the user's words as the query.
query_vector = embed(question)
chunks = search(query_vector, k) # each chunk: {"id": str, "text": str}
context = "\n\n".join(f"[{c['id']}] {c['text']}" for c in chunks)
prompt = (
"Answer using only the context below. "
"If the context does not contain the answer, say so.\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
return generate(prompt)Three details are worth noticing.
- Chunk ids are in the prompt. Each chunk is labeled
[id], so the model can cite the chunks it used. Later chapters rely on this. - The instruction allows "I don't know". Without a sentence like "If the context does not contain the answer, say so", models tend to fill gaps from memory.
- The question comes last. Putting the question after the context keeps it close to where the model starts writing, which usually helps with long contexts.
Running it without any services
To see the whole flow, you can swap in toy parts. The embedding below is a word count and the "model" just returns the prompt. This runs as written with only the standard library.
import math
import re
from collections import Counter
DOCS = [
{"id": "d1", "text": "The free plan allows 3 projects and 1 GB of storage."},
{"id": "d2", "text": "Paid plans allow unlimited projects and 100 GB of storage."},
{"id": "d3", "text": "Support is available by email on weekdays."},
]
def embed(text):
return Counter(re.findall(r"[a-z0-9]+", text.lower()))
def cosine(a, b):
dot = sum(a[t] * b[t] for t in a if t in b)
na = math.sqrt(sum(v * v for v in a.values()))
nb = math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
INDEX = [(d, embed(d["text"])) for d in DOCS]
def search(query_vector, k):
ranked = sorted(INDEX, key=lambda pair: cosine(query_vector, pair[1]), reverse=True)
return [doc for doc, _ in ranked[:k]]
def generate(prompt):
return prompt # a real pipeline would call a model here
def answer_with_rag(question, embed, search, generate, k=4):
query_vector = embed(question)
chunks = search(query_vector, k)
context = "\n\n".join(f"[{c['id']}] {c['text']}" for c in chunks)
prompt = (
"Answer using only the context below. "
"If the context does not contain the answer, say so.\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
return generate(prompt)
print(answer_with_rag("How much storage does the free plan have?", embed, search, generate, k=2))The printed prompt shows d1 first, because it shares the words "free", "plan" and "storage" with the question. search always returns k chunks, even when the lower-ranked ones are irrelevant. Notice that, because it matters in the next section.
Decisions inside the fixed pipeline
The pipeline looks simple, but most quality problems come from a few settings.
| Setting | Too small or strict | Too large or loose |
|---|---|---|
| Chunk size | Chunks lose the sentences that give them meaning | Each chunk mixes topics, so its vector is vague |
| k | The needed chunk may rank below the cutoff | Prompt fills with noise, cost rises, and the model can be distracted |
| Similarity threshold | Good but weak matches are dropped | Irrelevant chunks pass through |
| Prompt instructions | Model answers from memory | Model refuses even when the answer is present |
Two edge cases come up often.
- No good match exists. Vector search always returns the nearest chunks, however far away they are. If the question is outside your documents, the model receives unrelated text. A similarity threshold, or an instruction that allows "not found", is your only protection.
- The question is not a good query. Users write "and what about the paid one?" or "Why does this fail?". The embedding of such a sentence may land nowhere near the relevant chunk. Classic RAG embeds exactly what the user typed.
Common errors
- Embedding the question with a different model than the chunks. Vectors from different models are not comparable. Search then returns plausible-looking but meaningless rankings.
- Forgetting to re-index after documents change. The pipeline answers from stale chunks and nothing signals it.
- Splitting mid-sentence or mid-table. A chunk that begins "It is limited to 3" has lost what "it" refers to.
- Putting the whole context in without ids. The answer cannot be traced back to a source.
- Treating the prompt text as trusted. Retrieved chunks are text written by someone else. Chapter material on prompt injection comes later, but note now that the context block is not safe just because it came from your own store.
What the baseline gives you, and what it fixes in place
Classic RAG is cheap and predictable. It makes one embedding call, one search and one model call, so latency and cost are easy to estimate and failures are easy to debug. For a question that is a clean lookup in one corpus, it is often the right design.
Its limits come from the same fixed shape. The retrieval always runs, even for "hello". It runs once, so a poor first result cannot be corrected. The query is the raw question, so it cannot be rewritten. There is one index, so there is no choice of source. The next chapter looks at where these limits cause real failures.
Exercise
In the pipeline above, a user asks a question that is completely unrelated to your documents. What does the vector search return, and what protects the answer from being built on irrelevant text?
Show answer
The search still returns the k nearest chunks, because nearest-neighbor search ranks everything and has no notion of "no match". Protection comes from other parts of the pipeline: a similarity threshold that drops weak matches, and a prompt instruction telling the model to say the context does not contain the answer. Neither is perfect, so logging the retrieved ids helps you catch these cases.
Exercise
Name two things the classic pipeline cannot do because retrieval is a fixed stage that runs once with the user's raw question as the query.
Show answer
It cannot skip retrieval for questions that don't need it, such as greetings. It cannot retry with a better query when the first results are poor. Other valid answers are rewriting a vague follow-up question into a standalone query, and choosing between several sources.