Sub topic 2
The RAG pipeline at a glance
This chapter assumes you know basic Python, how LLMs are prompted, what a vector and a dot product are, and how to read JSON from an API. It gives you the working model of a retrieval-augmented generation (RAG) system. Later chapters cover each stage in detail.
The idea in one paragraph
A language model only knows what was in its training data and what you put in its prompt. RAG fetches relevant passages from your own documents at query time and places them in the prompt. The model then answers from that supplied text. You get private or current information without retraining.
Two phases
A RAG system has two phases that run at different times.
- Indexing (offline). You prepare the knowledge source once, and again whenever it changes.
- Query (online). You run this for every user question.
The stages
- Load and clean. Read files such as PDFs, web pages, or tickets. Convert them to plain text and remove noise like navigation menus and repeated headers.
- Chunk. Split each document into passages small enough to embed and to fit several into a prompt. The code below uses overlapping windows so a sentence cut at one boundary still appears whole in the next chunk.
- Embed. An embedding model turns each chunk into a vector, so that texts with similar meaning end up close together.
- Index. Store the vectors with their text and metadata, such as the source and date.
- Retrieve. Embed the question with the same model, then return the k chunks whose vectors are most similar.
- Augment. Put the retrieved chunks into the prompt with instructions.
- Generate. The model writes an answer from that context, ideally citing the passages.
def chunk_text(text, size=500, overlap=50):
if not 0 <= overlap < size:
raise ValueError("overlap must be in [0, size)")
step = size - overlap
chunks = []
for start in range(0, len(text), step):
chunks.append(text[start:start + size])
if start + size >= len(text):
break
return chunksHere is the final step in code. It numbers the passages and tells the model to answer only from them, cite them, and admit when the context is insufficient.
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\n"
f"Question: {question}\nAnswer:"
)Where problems come from
The stages depend on each other, and an early mistake limits everything after it. If chunking splits an answer across two chunks, retrieval may return only half. If retrieval misses the right passage, the model cannot answer correctly, however good the prompt is. For this reason you evaluate retrieval and generation separately.
| Stage | Runs | Typical failure |
|---|---|---|
| Load and clean | Indexing | Boilerplate text pollutes chunks |
| Chunk | Indexing | Answers split across chunks |
| Embed and index | Indexing | Stale index after documents change |
| Retrieve | Query | Right passage not in the top k |
| Augment and generate | Query | Model ignores or invents beyond the context |
Exercise
A user asks a question, and the correct answer exists in your documents, but the model replies "I don't know." Which phase and which stages would you check first, and why?
Show answer
Check the query phase's retrieval stage first. The prompt tells the model to refuse when the context lacks the answer, so the refusal suggests the right passage was not in the top k. Then look back at the indexing phase: the document may be missing from the index, or chunking may have split the answer across chunks.