AI & LLMs

How to Build a RAG Chatbot in Python: A Step-by-Step Guide

Build a RAG chatbot that answers from your own PDFs using Python, sentence-transformers, ChromaDB and an LLM API — with complete, runnable code.

What you'll build

  • A command-line chatbot that answers questions using your own documents (PDFs or text files) instead of guessing.
  • About 120 lines of Python using free, open-source components: pypdf, sentence-transformers and chromadb, plus any OpenAI-compatible LLM API.
  • Practical rules for chunk size, retrieval count and prompts that keep answers grounded — and how to tell when RAG is the wrong tool.

Large language models are impressive until you ask them about something they never saw in training: your company's leave policy, a fund's latest fact sheet, or the user manual of a product launched last month. They will often answer anyway — confidently and wrongly. Retrieval-augmented generation (RAG) fixes this by finding the relevant passages in your own documents first and handing them to the model together with the question.

RAG is the pattern behind most "chat with your documents" tools, and it is the first thing I reach for when a team asks for an internal assistant. This guide builds a minimal but honest version from scratch, so you understand each moving part before reaching for a framework.

How RAG works in one picture

A RAG system has two phases:

  1. Indexing (done once, or when documents change): load documents → split them into chunks → convert each chunk into an embedding vector → store the vectors in a vector database.
  2. Answering (every question): embed the question → retrieve the most similar chunks → build a prompt that contains those chunks → ask the LLM to answer only from them → show the answer with its sources.

An embedding is a list of numbers that represents the meaning of a piece of text. Texts with similar meaning produce vectors that are close together, which is why "How many days of annual leave do I get?" can match a paragraph titled "Leave entitlement" even though they share few words.

Step 1: Set up the project

You need Python 3.10 or newer. Create a virtual environment and install four packages:

python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install pypdf sentence-transformers chromadb openai

The openai package is only used as a client: it works with any provider that exposes an OpenAI-compatible API, including Groq, OpenAI itself, or a local server such as Ollama. Put your documents in a folder called docs/ and set your API key as an environment variable — never hard-code it:

export LLM_API_KEY="your-key-here"
export LLM_BASE_URL="https://api.groq.com/openai/v1"   # or another compatible endpoint
export LLM_MODEL="llama-3.3-70b-versatile"             # check your provider's current model list

Step 2: Load and chunk documents

Models can only read a limited amount of text at once, and retrieval works best on focused passages, so we split documents into overlapping chunks. Overlap prevents a sentence that straddles a boundary from being lost.

from pathlib import Path
from pypdf import PdfReader

def load_documents(folder="docs"):
    """Return a list of (source_name, text) tuples."""
    docs = []
    for path in Path(folder).glob("**/*"):
        if path.suffix.lower() == ".pdf":
            reader = PdfReader(path)
            for page_no, page in enumerate(reader.pages, start=1):
                text = page.extract_text() or ""
                if text.strip():
                    docs.append((f"{path.name} p.{page_no}", text))
        elif path.suffix.lower() in {".txt", ".md"}:
            docs.append((path.name, path.read_text(encoding="utf-8")))
    return docs

def chunk_text(text, size=900, overlap=150):
    """Split text into overlapping chunks of roughly `size` characters."""
    text = " ".join(text.split())          # normalise whitespace
    chunks, start = [], 0
    while start < len(text):
        end = min(start + size, len(text))
        # try to end on a sentence boundary
        cut = text.rfind(". ", start, end)
        if cut > start + size // 2:
            end = cut + 1
        chunks.append(text[start:end].strip())
        if end == len(text):
            break
        start = end - overlap
    return chunks
Choosing a chunk size

Start with 800–1,000 characters (roughly 150–250 words) and 15% overlap. Smaller chunks give precise matches but lose context; larger chunks carry context but dilute the match. If answers often feel "half right", look at the retrieved chunks before touching anything else — chunking is usually the culprit.

Step 3: Create embeddings and store them

We use all-MiniLM-L6-v2, a small embedding model that runs comfortably on a laptop CPU, and ChromaDB in persistent mode so the index survives restarts.

import chromadb
from sentence_transformers import SentenceTransformer

EMBEDDER = SentenceTransformer("all-MiniLM-L6-v2")
DB = chromadb.PersistentClient(path="./rag_db")

def build_index():
    collection = DB.get_or_create_collection("docs", metadata={"hnsw:space": "cosine"})
    ids, texts, metas = [], [], []
    for source, text in load_documents():
        for i, chunk in enumerate(chunk_text(text)):
            ids.append(f"{source}#{i}")
            texts.append(chunk)
            metas.append({"source": source})
    if not texts:
        raise SystemExit("No documents found in ./docs")
    vectors = EMBEDDER.encode(texts, normalize_embeddings=True, show_progress_bar=True)
    collection.upsert(ids=ids, documents=texts, embeddings=vectors.tolist(), metadatas=metas)
    print(f"Indexed {len(texts)} chunks")

Using upsert with deterministic IDs means you can re-run indexing after editing a document without creating duplicates.

Working with Nepali documents?

all-MiniLM-L6-v2 is trained mainly on English. For Nepali or mixed Nepali-English documents, switch to a multilingual embedding model (for example paraphrase-multilingual-MiniLM-L12-v2 or a multilingual E5 model) and compare retrieval quality on 20 real questions before deciding. I cover the wider challenges in Building NLP for the Nepali language.

Step 4: Retrieve relevant chunks

def retrieve(question, k=4):
    collection = DB.get_collection("docs")
    q_vec = EMBEDDER.encode([question], normalize_embeddings=True).tolist()
    res = collection.query(query_embeddings=q_vec, n_results=k)
    return [
        {"text": doc, "source": meta["source"], "distance": dist}
        for doc, meta, dist in zip(res["documents"][0], res["metadatas"][0], res["distances"][0])
    ]

With cosine distance, smaller is better. Printing the distances while you test is the fastest way to learn what a "good" match looks like for your documents. A useful habit: if even the best chunk is far away, the honest answer is "the documents don't cover this".

Step 5: Generate a grounded answer

The prompt is where RAG succeeds or fails. It must tell the model to answer only from the provided context, to admit when the context is insufficient, and to cite sources.

import os
from openai import OpenAI

LLM = OpenAI(api_key=os.environ["LLM_API_KEY"], base_url=os.environ.get("LLM_BASE_URL"))
MODEL = os.environ.get("LLM_MODEL", "llama-3.3-70b-versatile")

SYSTEM = """You answer questions using ONLY the context provided.
Rules:
- If the context does not contain the answer, say: "I couldn't find that in the documents."
- Do not use outside knowledge or guess numbers, dates or names.
- Keep answers concise. After the answer, list the sources you used in square brackets."""

def answer(question, max_distance=0.6):
    hits = [h for h in retrieve(question) if h["distance"] <= max_distance]
    if not hits:
        return "I couldn't find that in the documents."
    context = "\n\n".join(f"[{h['source']}]\n{h['text']}" for h in hits)
    resp = LLM.chat.completions.create(
        model=MODEL,
        temperature=0.1,
        messages=[
            {"role": "system", "content": SYSTEM},
            {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
        ],
    )
    return resp.choices[0].message.content

if __name__ == "__main__":
    import sys
    if "--index" in sys.argv:
        build_index()
    while True:
        q = input("\nAsk a question (or 'quit'): ").strip()
        if q.lower() in {"quit", "exit"}:
            break
        print("\n" + answer(q))

Run python rag.py --index the first time, then python rag.py afterwards. A low temperature keeps the model close to the text. The max_distance filter is a cheap but effective guard: if nothing relevant is retrieved, the model is never asked to improvise.

Step 6: Test it properly

Most RAG projects fail quietly because nobody measures them. Before showing your chatbot to anyone, write down 20–30 real questions with the answer and the page where it lives. Then check two things separately:

What to checkHowIf it fails
Retrieval: is the right chunk in the top k?Print sources from retrieve() for each test questionAdjust chunk size/overlap, try a better embedding model, add keyword search
Generation: is the answer faithful to the chunk?Compare the answer with the source textTighten the system prompt, lower temperature, use a stronger model
Refusal: does it say "not found" when it should?Include 5 questions the documents can't answerLower max_distance, make the refusal rule more explicit

Separating retrieval from generation tells you which half to fix. Most of the time, it's retrieval.

Common mistakes and how to avoid them

  • Scanned PDFs. extract_text() returns nothing for images of text. Run OCR (for example Tesseract, which supports Nepali) before indexing.
  • Tables. Text extraction flattens tables into confusing strings. For table-heavy documents, convert tables to CSV or Markdown first.
  • Stale index. If documents change and you forget to re-index, the bot answers from old versions. Store a file hash in metadata and re-index changed files automatically.
  • Leaking sensitive data. Whatever you put in the index can appear in an answer. Apply access control before retrieval, not after, and never send confidential documents to an API whose data-retention terms you haven't read.
  • Asking RAG to do maths. RAG retrieves text; it doesn't aggregate numbers across hundreds of rows. Questions like "total sales by month" belong to SQL or pandas, not RAG.

Where to go next

Once the basic loop works, the upgrades that usually pay off — in this order — are: hybrid search (combine vector similarity with keyword search such as BM25, which helps with product codes and names), re-ranking (use a cross-encoder to re-order the top 20 results), conversation memory (rewrite follow-up questions into standalone ones before retrieval), and a simple web UI with Streamlit or FastAPI.

Frameworks such as LangChain and LlamaIndex package all of this, and they're worth using once you understand the pieces. Building it by hand once, as we did here, makes debugging those frameworks far easier. For writing better prompts for the generation step, see my production prompt engineering guide, and for choosing an LLM provider see the AI tools: free vs. paid breakdown.

Spotted an error or have a question about this article? Send me a message — corrections are applied and noted with an updated date. See the editorial policy.

Keep reading

More articles you may find useful.

All articles