Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

RAG fundamentals: retrieval before generation

What RAG is and how retrieval-augmented generation works, when it beats long context or fine-tuning, and a minimal working pipeline in about 80 lines of Python.

By Updated Beginner30 min hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

Retrieval-augmented generation (RAG) means finding the passages relevant to a question and putting them in the model’s context before it answers. The model then answers from your documents rather than from whatever it absorbed in training. It is the standard way to build assistants over internal docs, support articles, contracts or code, and it is less magical than it sounds: a search step followed by a prompt.

This tutorial explains the pipeline, when RAG is the right choice, and then builds a minimal working version in about 80 lines of Python so you can see every part. The follow-up, Embeddings and vector search, moves the index into Postgres.

The pipeline

A RAG system has two phases.

Indexing happens ahead of time:

  1. Load the documents (Markdown, HTML, PDFs, tickets).
  2. Chunk them into passages small enough to be specific, large enough to make sense on their own.
  3. Embed each chunk: turn it into a vector of numbers that represents its meaning.
  4. Store the vectors with the chunk text and its source.

Answering happens per question:

  1. Embed the question with the same model.
  2. Retrieve the chunks whose vectors are most similar to the question’s.
  3. Generate: give the model the question plus those chunks, with instructions to answer only from them and cite them.
docs ─► chunk ─► embed ─► store                      (once, and on every doc change)
question ─► embed ─► find nearest chunks ─► prompt ─► answer with citations

When RAG is the right tool

Models now accept very long inputs, so a fair question is why not paste all the documents in. Sometimes you should. A rough guide:

Situation Better choice
A few documents that fit comfortably in context and rarely change Put them in the prompt, and use prompt caching
A large or growing corpus, or one that changes daily RAG
Answers must cite sources, or access differs per user RAG, with permissions applied at retrieval time
You need the model to adopt a style, format or narrow skill Fine-tuning or better prompting, not RAG
The model needs to know facts it was not trained on RAG (fine-tuning is a poor way to add facts)

The article RAG vs long context vs fine-tuning goes deeper. The short version: RAG is about giving the model the right facts at the right time, and it scales to corpora no context window can hold.

Build a minimal RAG

This version keeps everything visible: embeddings from a local model through Ollama, vectors in a JSON file, similarity with NumPy, and the answer from Claude. You can swap any part later.

Set up:

ollama pull embeddinggemma
pip install ollama numpy anthropic
export ANTHROPIC_API_KEY="your-key"

Put some Markdown files in a docs/ folder. Your team’s runbooks or a project’s documentation work well.

# rag.py
import json
import sys
from pathlib import Path

import anthropic
import numpy as np
import ollama

EMBED_MODEL = "embeddinggemma"
INDEX = Path("index.json")


def chunk(text: str, source: str, max_chars: int = 1200, overlap: int = 200) -> list[dict]:
    """Split on blank lines, then pack paragraphs into chunks of roughly max_chars."""
    paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
    chunks, current = [], ""
    for p in paragraphs:
        if current and len(current) + len(p) > max_chars:
            chunks.append(current)
            current = current[-overlap:]  # carry a little context into the next chunk
        current = f"{current}\n\n{p}" if current else p
    if current:
        chunks.append(current)
    return [{"source": source, "n": i, "text": c} for i, c in enumerate(chunks)]


def embed(texts: list[str]) -> np.ndarray:
    vectors = np.array(ollama.embed(model=EMBED_MODEL, input=texts).embeddings, dtype=np.float32)
    return vectors / np.linalg.norm(vectors, axis=1, keepdims=True)  # unit length, so dot product = cosine


def build_index(folder: str) -> None:
    chunks = [c for p in sorted(Path(folder).glob("**/*.md")) for c in chunk(p.read_text(encoding="utf-8"), str(p))]
    vectors = embed([c["text"] for c in chunks])
    INDEX.write_text(json.dumps({"chunks": chunks, "vectors": vectors.tolist()}))
    print(f"indexed {len(chunks)} chunks from {folder}")


def retrieve(question: str, k: int = 4) -> list[dict]:
    data = json.loads(INDEX.read_text())
    vectors = np.array(data["vectors"], dtype=np.float32)
    scores = vectors @ embed([question])[0]
    best = np.argsort(-scores)[:k]
    return [{**data["chunks"][i], "score": float(scores[i])} for i in best]


def answer(question: str) -> str:
    hits = retrieve(question)
    context = "\n\n".join(f'<source id="{h["source"]}#{h["n"]}">\n{h["text"]}\n</source>' for h in hits)
    response = anthropic.Anthropic().messages.create(
        model="claude-opus-5-5",
        max_tokens=1500,
        system=(
            "Answer using only the sources provided. After each claim, cite the source id in square brackets. "
            "If the sources do not contain the answer, say that you could not find it."
        ),
        messages=[{"role": "user", "content": f"{context}\n\nQuestion: {question}"}],
    )
    return "".join(b.text for b in response.content if b.type == "text")


if __name__ == "__main__":
    if sys.argv[1] == "index":
        build_index(sys.argv[2])
    else:
        for h in retrieve(sys.argv[2]):
            print(f'{h["score"]:.3f}  {h["source"]}#{h["n"]}')
        print()
        print(answer(sys.argv[2]))

Run it:

python rag.py index docs
python rag.py ask "How do we roll back a failed deploy?"

The script prints the retrieved chunks with their similarity scores before the answer. Always look at those first. If the right passage is not in the list, no prompt will produce a good answer.

The decisions that matter

Chunk size. Too small and a chunk loses its meaning (“Run it again.” Run what?). Too large and retrieval gets vague because one vector has to represent several topics. A few hundred to about a thousand words is a sensible start for prose; split on structure (headings, paragraphs) rather than at fixed character counts. Code and tables need their own rules.

Context around chunks. A chunk that starts mid-section has lost its heading. Cheap fixes: prepend the document title and section heading to each chunk before embedding, and keep a little overlap between neighbours, as the example does.

The embedding model. Use the same model for documents and questions, always. Changing models means re-embedding everything.

How many chunks to retrieve. Too few and you miss the answer; too many and you bury it. Start with four to eight and measure.

Keyword search as well. Vector search is good at meaning and weak at exact terms: error codes, product names, ticket numbers. Production systems usually combine it with keyword search (hybrid search) and often add a reranking step. The next tutorial shows hybrid search in Postgres.

Citations and refusals. Asking for source ids after each claim makes answers checkable, and an explicit “say you could not find it” makes the system admit gaps instead of filling them from general knowledge.

Measure retrieval separately from answers

When a RAG answer is wrong, it is either a retrieval failure (the right passage was not found) or a generation failure (it was found, and the model misused it). They need different fixes, so measure them separately.

Write 20 real questions and, for each, note which document contains the answer. Then check how often that document appears in the top results. This “hit rate” tells you whether to work on chunking and search or on the prompt. The workflow Evaluate RAG with a golden set turns this into a repeatable test.

Pitfalls

Stale index. Documents change and the index does not. Re-index on change, and store a content hash per chunk so you only re-embed what changed.

Ignoring permissions. If users should not all see all documents, filter at retrieval time by the user’s access. Do not rely on the prompt to hide things.

Garbage in. PDFs with broken text extraction, navigation menus scraped with every page, duplicate pages. Clean the input; it matters more than the choice of vector database.

Trusting the retrieved text. Retrieved documents are input written by someone else. If any of them could contain instructions aimed at the model, read Prompt injection basics.

Skipping the baseline. Before building RAG, try the simplest thing: if the docs fit in context, paste them and see how good the answers are.

Next steps

Covers

Check your understanding

RAG fundamentals quiz

How retrieval-augmented generation works, when to use it and the parts you need to build it.

6 questions · pass mark 70%

Question 1 of 60 answered
  1. What are the two main stages of a RAG system at question time?
Back to top