Home / Guides / Build with LLMs

Build with LLMs

RAG Tutorial for Beginners: Build a Document Q&A Bot in Python

Learn retrieval-augmented generation (RAG) step by step. Build a working Python app that answers questions from your own documents, with full code.

Retrieval-augmented generation (RAG) is the most common pattern in real-world LLM apps. Instead of hoping a model already knows the answer, you retrieve the relevant text from your own documents and give it to the model along with the question. The model then answers from that text.

In this tutorial you'll build a small RAG app in about 80 lines of Python, with no framework, so you can see every moving part. Once you understand this version, frameworks like LangChain and LlamaIndex become much easier to follow.

How RAG works

RAG has two phases:

Indexing (done once):

  1. Load your documents
  2. Split them into small chunks
  3. Turn each chunk into an embedding, a list of numbers that captures its meaning
  4. Store the chunks and their embeddings

Answering (every question):

  1. Embed the user's question
  2. Find the chunks whose embeddings are closest to it
  3. Put those chunks into the prompt
  4. Ask the LLM to answer using only that context

Why bother? RAG lets a model answer about private or recent information, reduces made-up answers, and lets you show sources. It's also much cheaper and faster to update than fine-tuning a model.

What you need

  • Python 3.10 or newer
  • An Anthropic API key (any chat model API works the same way)
  • A folder of .txt or .md files to ask questions about

Install the packages:

pip install anthropic sentence-transformers numpy
export ANTHROPIC_API_KEY="your-key-here"

We'll use sentence-transformers to create embeddings on your own computer for free, and Claude to write the answers.

Step 1: Load and chunk your documents

Chunks should be small enough to be specific but big enough to keep context. A few hundred words with some overlap is a good default.

from pathlib import Path

def load_documents(folder):
    docs = []
    for path in Path(folder).glob("**/*"):
        if path.suffix.lower() in {".txt", ".md"}:
            docs.append({"source": path.name, "text": path.read_text(encoding="utf-8")})
    return docs

def chunk_text(text, size=200, overlap=40):
    """Split text into chunks of about `size` words, overlapping by `overlap` words."""
    words = text.split()
    chunks = []
    step = size - overlap
    for start in range(0, max(len(words), 1), step):
        piece = " ".join(words[start:start + size])
        if piece:
            chunks.append(piece)
    return chunks

The overlap means a sentence that falls on a chunk boundary still appears whole in at least one chunk.

Step 2: Create embeddings

import numpy as np
from sentence_transformers import SentenceTransformer

embedder = SentenceTransformer("all-MiniLM-L6-v2")  # small, fast, runs on CPU

def build_index(folder):
    chunks = []
    for doc in load_documents(folder):
        for piece in chunk_text(doc["text"]):
            chunks.append({"source": doc["source"], "text": piece})
    vectors = embedder.encode([c["text"] for c in chunks], normalize_embeddings=True)
    return chunks, np.array(vectors)

normalize_embeddings=True scales every vector to length 1, so a simple dot product gives the cosine similarity: how close two pieces of text are in meaning.

Step 3: Retrieve the best chunks

def retrieve(question, chunks, vectors, k=4):
    q = embedder.encode([question], normalize_embeddings=True)[0]
    scores = vectors @ q                      # cosine similarity with every chunk
    best = np.argsort(scores)[::-1][:k]       # top k, highest first
    return [(chunks[i], float(scores[i])) for i in best]

For a few thousand chunks, a NumPy array is plenty. When you get to hundreds of thousands, move to a vector database. See our vector database comparison.

Step 4: Generate the answer

This is where the "augmented" part happens. Tell the model to answer only from the supplied context and to admit when it doesn't know.

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
MODEL = "claude-sonnet-5-5"     # check the provider's docs for current model names

SYSTEM = (
    "You answer questions using ONLY the provided context. "
    "If the answer is not in the context, say you don't know. "
    "Cite sources in square brackets, like [handbook.md]."
)

def answer(question, chunks, vectors):
    hits = retrieve(question, chunks, vectors)
    context = "\n\n".join(f"[{c['source']}]\n{c['text']}" for c, _ in hits)
    response = client.messages.create(
        model=MODEL,
        max_tokens=600,
        system=SYSTEM,
        messages=[{
            "role": "user",
            "content": f"<context>\n{context}\n</context>\n\nQuestion: {question}",
        }],
    )
    return response.content[0].text, hits

Step 5: Put it together

if __name__ == "__main__":
    chunks, vectors = build_index("docs")
    print(f"Indexed {len(chunks)} chunks. Ask a question (or 'quit').")
    while True:
        q = input("\n> ").strip()
        if q.lower() in {"quit", "exit"}:
            break
        text, hits = answer(q, chunks, vectors)
        print("\n" + text)
        print("\nRetrieved:", ", ".join(f"{c['source']} ({s:.2f})" for c, s in hits))

Put a few files in a docs/ folder, run the script, and ask questions about them. The printed similarity scores show what was retrieved, which is your first debugging tool.

Building your first LLM app?

Pair this with the step-by-step RAG tutorial and the AI agent guide.

Making your RAG app better

A basic RAG app is easy to build. A good one takes more work. These upgrades matter most, roughly in order:

  1. Evaluate first. Write 20–50 real questions with known answers. Check (a) whether the right chunk was retrieved, and (b) whether the final answer was correct. Without this, you're guessing.
  2. Better chunking. Split on headings and paragraphs instead of raw word counts, and store the document title with each chunk.
  3. Hybrid search. Combine embedding search with keyword search (BM25). Keyword search catches exact names, codes and numbers that embeddings miss.
  4. Re-ranking. Retrieve 20 candidates, then use a re-ranker model to pick the best 4.
  5. Metadata filters. Filter by date, product or department before searching.
  6. Better embeddings. Larger or domain-specific embedding models can improve retrieval a lot.

Common RAG mistakes

  • Chunks too big: the important sentence gets buried in irrelevant text.
  • No "I don't know" rule: the model fills gaps with confident guesses.
  • Ignoring tables and PDFs: text extraction can scramble them. Check what your loader actually produces.
  • Only judging by eye: a few good demo answers don't mean the system works.

Should you use LangChain or LlamaIndex instead?

For learning, writing it yourself (like above) is best. For production, a framework saves time on document loaders, vector store connections and evaluation tools. LlamaIndex focuses on retrieval and document pipelines, while LangChain and LangGraph are strongest at orchestration and agents. See LangChain vs LlamaIndex for the full comparison.

Next steps

Sources