Build a RAG Chatbot in Python That Answers From Your Documents
Step-by-step: build a retrieval-augmented generation (RAG) chatbot in Python with local embeddings, a NumPy vector index and Claude, with cited answers.
General-purpose LLMs don’t know your company handbook, product docs or contracts. Retrieval-augmented generation (RAG) fixes that by finding the relevant passages first and asking the model to answer from them, with citations.
In this tutorial you’ll build a RAG chatbot that:
- Loads a folder of text or Markdown documents
- Splits them into chunks and embeds them locally (free, no extra API)
- Retrieves the most relevant chunks for each question
- Asks Claude to answer only from those chunks, citing sources like
[1] - Says “I don’t know” when the answer isn’t in your documents
Not sure if RAG is right for you? Read RAG vs Fine-Tuning first.
How it works
INDEXING (once) QUERY (every question)
docs/ ─► chunk ─► embed ─► vectors.npy question ─► embed ─► top-k similar chunks
│
Claude ◄── question + chunks ◄─┘
│
▼
answer with [1][2] citations
Prerequisites
- Python 3.10+
- An Anthropic API key (
ANTHROPIC_API_KEYset in your environment) - A few documents to search. Any
.mdor.txtfiles will do.
mkdir rag-bot && cd rag-bot
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install anthropic sentence-transformers numpy
mkdir docs # put your .md / .txt files here
Step 1: Load and chunk documents
LLMs work best with focused, relevant context, so we split documents into chunks. We’ll chunk by paragraph and merge small paragraphs together up to a size limit, with a little overlap so ideas that span a boundary aren’t lost.
Create rag.py:
import json
from pathlib import Path
import anthropic
import numpy as np
from sentence_transformers import SentenceTransformer
DOCS_DIR = Path("docs")
INDEX_DIR = Path("index")
MAX_CHARS = 1200 # roughly 250-300 tokens per chunk
OVERLAP_PARAS = 1 # paragraphs carried into the next chunk
def chunk_document(text: str) -> list[str]:
paras = [p.strip() for p in text.split("\n\n") if p.strip()]
chunks, current = [], []
for para in paras:
if current and sum(len(p) for p in current) + len(para) > MAX_CHARS:
chunks.append("\n\n".join(current))
current = current[-OVERLAP_PARAS:]
current.append(para)
if current:
chunks.append("\n\n".join(current))
return chunks
def load_chunks() -> list[dict]:
chunks = []
for path in sorted(DOCS_DIR.rglob("*")):
if path.suffix.lower() not in {".md", ".txt"}:
continue
for i, text in enumerate(chunk_document(path.read_text(encoding="utf-8"))):
chunks.append({"source": str(path.relative_to(DOCS_DIR)), "chunk": i, "text": text})
return chunks
Chunking matters more than people think. For real documents, split by headings and sections, keep tables intact and store the section title with each chunk. Good chunking often improves answers more than a better model.
Step 2: Embed the chunks and build the index
An embedding is a list of numbers that captures the meaning of a piece of text. Texts with similar meaning have similar vectors. We’ll use all-MiniLM-L6-v2, a small model that runs on a laptop CPU.
embedder = SentenceTransformer("all-MiniLM-L6-v2")
def build_index() -> None:
chunks = load_chunks()
if not chunks:
raise SystemExit("No .md or .txt files found in docs/")
vectors = embedder.encode(
[c["text"] for c in chunks],
normalize_embeddings=True, # unit vectors -> dot product == cosine similarity
show_progress_bar=True,
)
INDEX_DIR.mkdir(exist_ok=True)
np.save(INDEX_DIR / "vectors.npy", vectors)
(INDEX_DIR / "chunks.json").write_text(json.dumps(chunks), encoding="utf-8")
print(f"Indexed {len(chunks)} chunks from {DOCS_DIR}/")
def load_index() -> tuple[np.ndarray, list[dict]]:
vectors = np.load(INDEX_DIR / "vectors.npy")
chunks = json.loads((INDEX_DIR / "chunks.json").read_text(encoding="utf-8"))
return vectors, chunks
Step 3: Retrieve relevant chunks
To answer a question, embed it the same way and find the chunks with the highest similarity. Because the vectors are normalised, a single matrix multiplication gives cosine similarity for every chunk at once.
def retrieve(question: str, vectors: np.ndarray, chunks: list[dict], k: int = 4, min_score: float = 0.25):
q = embedder.encode([question], normalize_embeddings=True)[0]
scores = vectors @ q
top = np.argsort(-scores)[:k]
return [(chunks[i], float(scores[i])) for i in top if scores[i] >= min_score]
The min_score threshold drops chunks that are only weakly related. Tune it by looking at scores for real questions.
Step 4: Generate a grounded, cited answer
Now we send the question plus the retrieved chunks to Claude. Wrapping each chunk in tags with a numeric ID makes citations easy, and the system prompt tells the model to stick to the sources.
client = anthropic.Anthropic()
MODEL = "claude-opus-5-5"
SYSTEM_PROMPT = """You answer questions using ONLY the provided documents.
- Cite the documents you use with their number in square brackets, e.g. [1] or [2][3].
- If the documents don't contain the answer, say you don't know and suggest who to ask.
- Be concise and accurate. Do not use outside knowledge for factual claims."""
def answer(question: str, vectors: np.ndarray, chunks: list[dict]) -> str:
hits = retrieve(question, vectors, chunks)
if not hits:
return "I couldn't find anything about that in the documents."
context = "\n".join(
f'<document id="{n}" source="{c["source"]}">\n{c["text"]}\n</document>'
for n, (c, _score) in enumerate(hits, start=1)
)
response = client.messages.create(
model=MODEL,
max_tokens=16000,
system=SYSTEM_PROMPT,
messages=[{
"role": "user",
"content": f"<documents>\n{context}\n</documents>\n\nQuestion: {question}",
}],
)
text = "".join(block.text for block in response.content if block.type == "text")
sources = "\n".join(f" [{n}] {c['source']}" for n, (c, _s) in enumerate(hits, start=1))
return f"{text}\n\nSources:\n{sources}"
Step 5: Put it together
if __name__ == "__main__":
import sys
if "--index" in sys.argv or not (INDEX_DIR / "vectors.npy").exists():
build_index()
vectors, chunks = load_index()
print("Ask about your documents. Type 'quit' to exit.\n")
while True:
q = input("You: ").strip()
if q.lower() in {"quit", "exit"}:
break
if q:
print(f"\nBot: {answer(q, vectors, chunks)}\n")
Run it (the first run builds the index; use --index to rebuild after changing documents):
python rag.py --index
Ask questions your documents answer, then ask one they don’t. A good RAG bot should cite sources for the first and admit it doesn’t know the second.
Step 6: Test retrieval before blaming the model
When a RAG bot gives a bad answer, the cause is usually retrieval, not generation. The right chunk never reached the model. Add a quick debug helper:
def debug(question: str) -> None:
vectors, chunks = load_index()
for c, score in retrieve(question, vectors, chunks, k=6, min_score=0):
print(f"{score:.3f} {c['source']}#{c['chunk']} {c['text'][:90]!r}")
If the right passage isn’t in the top results, fix chunking, add keyword search or try a stronger embedding model before you touch the prompt.
Making it production-ready
This bot is a solid foundation. Real deployments usually add:
| Upgrade | Why |
|---|---|
| Vector database (pgvector, Qdrant, Pinecone) | Scale, metadata filters, incremental updates |
| Hybrid search (BM25 + vectors) | Catches exact terms like product codes and names |
| Reranking | Re-scores the top 20–50 candidates for much better precision |
| Access control | Filter chunks by the user’s permissions before retrieval |
| Native citations | Claude’s citations feature can return exact cited passages |
| Prompt caching | Cuts cost when the system prompt and context repeat |
| Evaluation set | 50+ real questions with expected answers, run on every change |
| Conversation memory | Rewrite follow-up questions into standalone queries before retrieval |
Estimate what your bot will cost to run with our LLM cost calculator.
Need a RAG assistant for your company’s knowledge? We build RAG chatbots with secure data pipelines, citations, access control and analytics.
Frequently asked questions
Do I need a vector database for RAG?
Not for small projects. A NumPy array handles thousands of chunks comfortably. Move to a vector database such as pgvector or Qdrant when you have many documents, need filtering, or need concurrent updates.
Which embedding model should I use?
Start with a small, free local model like all-MiniLM-L6-v2 to learn. For production, test a few embedding models on your own questions; multilingual or domain-specific content may need a stronger model.
We offer rag chatbot & knowledge assistant development from $4,000, with a fixed quote after a free 30-minute call.