Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 21. Naive RAG
  4. 21.1

Lesson 21.1 · 1 of 5 · 4 min read · Reviewed 24 Nov 2026

The four steps: chunk, embed, retrieve, generate

By the end, you can

  • Describe the four steps of retrieval-augmented generation.
  • Explain why RAG grounds answers in your own data.

Retrieval-augmented generationRetrieval-augmented generation (RAG): Retrieving relevant documents at request time and adding them to the prompt so the answer is grounded in them. (RAG) connects a model to your documents.

INDEXING (ahead of time)
documents --> chunk --> embed each chunk --> store vectors + text

QUERYING (per question)
question --> embed --> find nearest chunks --> put them in the prompt --> model answers

The four steps

Step What happens Detail in
Chunk Split documents into passages, often a few hundred tokens each 23.1
Embed Turn each chunk into a vector with an embedding model Chapter 4
Retrieve Embed the question; find the most similar chunks Chapter 22
Generate Give the model the question plus retrieved chunks 21.2

Why it works

The model already knows how to read and answer. RAG supplies the right pages at the right time, like handing someone the relevant section of a manual before they answer.

What it gives you

  • Answers from private or recent data
  • CitationsCitations: References in an answer that point to the exact source passages supporting each claim. back to source passages
  • Updates without retraining: re-index the changed documents

A tiny example

Question: “How many days do customers have to return shoes?” Retrieved chunkChunking: Splitting documents into smaller passages before embedding and indexing them.: “Section 4.2: Footwear may be returned within 30 days if unworn.” Answer: “30 days, if the shoes are unworn (policy section 4.2).”

Key points

  • RAG answers questions from your documents: chunk them, embed the chunks, retrieve the closest ones to a question, and generate an answer from them.
  • It lets a model use private or recent information it was never trained on.
  • Indexing (chunk and embed) happens ahead of time; retrieval and generation happen per question.
Hands-on labRuns in the Playground

Build a four-step RAG pipeline

Build chunk, embed, retrieve and generate as four small functions, so you can see each step's output.

You will have: A tiny RAG script that indexes a policy and answers a question with a citation.

Steps

  1. Chunk the policy by section, keeping each section's id.
  2. Embed every chunk with the toy embed() and store (id, text, vector).
  3. Embed the question and return the top chunk by cosine similarity. A tiny synonym map (shoe to footwear) stands in for what a real embedding model knows.
  4. Generate a templated answer that quotes the chunk and cites its id.

Done when

  • The index holds 4 chunks.
  • The shoe question retrieves section 4.2.
  • The answer ends with the cited id in brackets.

Open in the Playground No API key needed.

Starter code (Python)
import math, re
from collections import Counter

STOP = {"a", "an", "the", "to", "of", "and", "or", "is", "are", "be", "in", "on", "for", "if", "it", "do", "i", "my", "how", "many", "what", "can", "have", "within", "may", "by"}

def embed(text):
    """A toy embedding: counts of content words. Real systems use an embedding model."""
    words = [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP]
    return Counter(w[:-1] if w.endswith("s") and len(w) > 3 else w for w in words)

def cosine(a, b):
    dot = sum(a[k] * b[k] for k in a)
    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

DOC = ("Section 4.1: Clothing may be returned within 60 days with a receipt. "
       "Section 4.2: Footwear may be returned within 30 days if unworn. "
       "Section 4.3: Sale items are final sale unless faulty. "
       "Section 5.1: Refunds go to the original payment method within five working days.")

def chunk(doc):
    # TODO: split on "Section " and return [(id, text)], for example ("4.2", "Footwear may be ...")
    return [("all", doc)]

def build_index(chunks):
    # TODO: return [(id, text, embed(text))]
    return []

def retrieve(index, question, k=1):
    # TODO: rank by cosine(embed(question), vector) and return the top k entries
    return index[:k]

def generate(question, hits):
    # TODO: return an answer that quotes hits[0] and cites [id]
    return "I don't know yet."

index = build_index(chunk(DOC))
print("chunks indexed:", len(index))
q = "How many days do I have to return shoes?"
print(generate(q, retrieve(index, q)))
Show a solution
import math, re
from collections import Counter

STOP = {"a", "an", "the", "to", "of", "and", "or", "is", "are", "be", "in", "on", "for", "if", "it", "do", "i", "my", "how", "many", "what", "can", "have", "within", "may", "by"}

def embed(text):
    """A toy embedding: counts of content words. Real systems use an embedding model."""
    words = [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP]
    return Counter(w[:-1] if w.endswith("s") and len(w) > 3 else w for w in words)

def cosine(a, b):
    dot = sum(a[k] * b[k] for k in a)
    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

DOC = ("Section 4.1: Clothing may be returned within 60 days with a receipt. "
       "Section 4.2: Footwear may be returned within 30 days if unworn. "
       "Section 4.3: Sale items are final sale unless faulty. "
       "Section 5.1: Refunds go to the original payment method within five working days.")

SYNONYMS = {"shoe": "footwear", "trainer": "footwear", "boot": "footwear"}

def chunk(doc):
    out = []
    for part in doc.split("Section ")[1:]:
        sid, text = part.split(":", 1)
        out.append((sid.strip(), text.strip()))
    return out

def build_index(chunks):
    return [(cid, text, embed(text)) for cid, text in chunks]

def retrieve(index, question, k=1):
    qv = embed(" ".join(SYNONYMS.get(w, w) for w in embed(question)))
    return sorted(index, key=lambda e: -cosine(qv, e[2]))[:k]

def generate(question, hits):
    if not hits:
        return "The policy doesn't cover this."
    cid, text, _ = hits[0]
    return f"From the policy: {text} [{cid}]"

index = build_index(chunk(DOC))
print("chunks indexed:", len(index))
q = "How many days do I have to return shoes?"
hits = retrieve(index, q)
print("top chunk:", hits[0][0])
print(generate(q, hits))
Quick checkWhy does RAG help a model answer questions about your company's internal policies?
How sure are you?
Pick an answer and how sure you are