Sub topic 2
The RAG pipeline at a glance
This chapter gives you the whole retrieval-augmented generation (RAG) pipeline on one page. Later chapters cover each stage in depth. Here you learn what the stages are, what each one hands to the next, and where problems tend to appear.
Prerequisites
You should be comfortable with basic Python, with how prompts are sent to a large language model (LLM), and with vectors and the dot product. You should also know how to call an API and read JSON. You don't need any vector database or RAG library experience.
The core idea
An LLM only knows what was in its training data and what you put in its prompt. RAG exploits the second part. At question time, the system looks up passages from your own documents and places them in the prompt. The model then answers from those passages instead of from memory.
RAG is not one algorithm. It is a pipeline of separate stages, and each stage can be built, tested, and replaced on its own.
Two phases: indexing and querying
The pipeline runs in two phases that happen at different times.
- Indexing runs ahead of time, or whenever documents change. It turns raw files into searchable vectors.
- Querying runs for every user question. It finds relevant passages, builds a prompt, and generates an answer.
The two phases meet at the vector store, which indexing writes to and querying reads from.
The stages and what they exchange
Each stage has a clear input and output. Knowing these contracts lets you test stages separately.
| Stage | Input | Output | Main risk |
|---|---|---|---|
| Load and clean | Files, web pages, database rows | Clean text plus metadata | Boilerplate or garbled text enters the index |
| Chunk | Clean text | Passages of a few hundred tokens | Chunks that split an idea or mix topics |
| Embed | Chunk text | One vector per chunk | A model that fits your domain poorly |
| Store | Vectors, text, metadata | A searchable index | Stale or inaccessible content |
| Retrieve | Question vector | Top-k passages with scores | The right passage is not in the top k |
| Augment | Question and passages | A prompt | Too much context, or unclear instructions |
| Generate | Prompt | An answer, ideally with citations | Claims that the passages don't support |
Two rules link these stages:
- Use the same embedding model for chunks and questions. Vectors from different models live in different spaces, and comparing them gives meaningless scores.
- Keep metadata with every chunk. Source file, section, date, and access group are what make citations, filtering, and debugging possible.
A minimal end-to-end skeleton
The sketch below runs the whole pipeline in one file. The embed function is a toy that hashes words into a fixed-size count vector, and generate is a stub that returns the prompt. In a real system you would replace both with calls to an embedding model and an LLM. The shape of the pipeline stays the same.
import math
import re
import zlib
DOCS = [
"Refunds are issued within 5 business days of approval.",
"Shipping to Canada takes 7 to 10 days.",
"Support is available by chat from 9 to 17 UTC.",
]
def embed(text, dim=256):
# Toy embedding: hash each word into one of `dim` buckets and count.
vec = [0.0] * dim
for token in re.findall(r"[a-z0-9]+", text.lower()):
vec[zlib.crc32(token.encode()) % dim] += 1.0
return vec
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb else 0.0
def build_index(docs):
# Indexing phase: one (text, vector) pair per document.
return [(doc, embed(doc)) for doc in docs]
def retrieve(question, index, k=2):
# Querying phase: embed the question, score every chunk, keep the best k.
q = embed(question)
scored = sorted(
((cosine(q, vec), text) for text, vec in index),
reverse=True,
)
return [text for _, text in scored[:k]]
def build_prompt(question, passages):
context = "\n\n".join(f"[{i}] {p}" for i, p in enumerate(passages, start=1))
return (
"Answer using only the context below. "
"Cite passages like [1]. "
"If the context does not contain the answer, say you don't know.\n\n"
f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
)
def generate(prompt):
# Stand-in for an LLM call. Returns the prompt so you can inspect it.
return prompt
index = build_index(DOCS)
question = "How many days do refunds take?"
print(generate(build_prompt(question, retrieve(question, index))))Run it and read the printed prompt. The refund passage should appear as [1], because it shares the words "refunds" and "days" with the question. The toy embedding only matches shared words. A real embedding model also matches paraphrases, such as "money back" for "refund". The next chapters build on this skeleton one piece at a time.
Where the pipeline has decision points
Each stage has a few settings. They are listed here so you can recognize them later:
- Chunk size and overlap. Small chunks are precise but lose context. Large chunks keep context but dilute the match.
- Top-k. A small k risks missing the right passage. A large k adds noise and cost.
- Metadata filters. You can restrict search to one product, language, or user group before ranking.
- Optional stages. Hybrid search, reranking, and query rewriting sit between the question and the prompt. You add them when measurements show retrieval is the weak point.
Why stage boundaries matter for debugging
A wrong answer is a symptom, not a diagnosis. The same bad answer can come from several different faults:
- The fact was never ingested, so the loader or cleaner failed.
- The fact was ingested but split across two chunks.
- The chunk exists but ranked below position k.
- The chunk was retrieved, but the prompt buried it or contradicted it.
- The right passage was in the prompt, and the model ignored it.
To tell these apart, log the intermediate results for every request: the retrieved chunk IDs, their scores, and the final prompt. When an answer is wrong, check the retrieved passages first. If the right passage is absent, the problem is in retrieval or earlier. If it is present, the problem is in prompting or generation.
Edge cases to plan for early
- Empty or low-score retrieval. Top-k always returns k results, even when none are relevant. Decide whether a minimum score should trigger a refusal instead of an answer.
- Changing documents. Updated source files leave outdated vectors in the index unless you re-embed and delete them. Track a document ID and version on each chunk.
- Changing embedding models. Switching models means re-embedding the whole collection, because old and new vectors can't be compared.
- Context limits. The question, the instructions, and k passages must all fit in the model's context window, with room left for the answer.
- Access control. The index must not return passages the current user can't see. Filtering after generation is too late.
Summary
RAG has an offline indexing phase and an online querying phase, joined by a vector store. Each stage has a defined input and output, so you can test and replace stages independently. The most useful habit is to inspect what was retrieved before you judge the answer.
Exercise
A user asks about a policy that was updated last week. The system answers with the old policy and cites a passage that says so. Which phase of the pipeline most likely failed, and what two pieces of metadata would help you find and fix the problem?
Show answer
The indexing phase failed to refresh. The old chunk is still in the vector store, and the new version was never embedded or the old one was never deleted. A document ID and a version or last-modified date on each chunk let you find every chunk from the changed document, remove the stale ones, and re-embed the new text. Retrieval and generation worked as designed, since they correctly used what the index contained.
Exercise
In the skeleton above, you change embed to use a different model for questions than for chunks. Retrieval now returns unrelated passages. Why, and what is the fix?
Show answer
Vectors from different models are not in the same space, so cosine similarity between them has no meaning. The fix is to embed chunks and questions with the same model. If you change the model, re-embed every stored chunk.