惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
宝玉的分享
宝玉的分享
月光博客
月光博客
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
小众软件
小众软件
量子位
MongoDB | Blog
MongoDB | Blog
Blog — PlanetScale
Blog — PlanetScale
The Cloudflare Blog
Stack Overflow Blog
Stack Overflow Blog
U
Unit 42
Hugging Face - Blog
Hugging Face - Blog
T
The Blog of Author Tim Ferriss
H
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Build a RAG Chatbot with Python
Serhii Kalyn · 2026-05-13 · via DEV Community
Cover image for How to Build a RAG Chatbot with Python

Serhii Kalyna

A RAG (Retrieval-Augmented Generation) chatbot answers questions based on your own documents — not just its training data. This guide builds one from scratch using Python, ChromaDB, and Claude.

Originally published at kalyna.pro

What Is RAG?

RAG combines two things:

  • Retrieval: search your documents for relevant chunks
  • Generation: use an LLM to write an answer based on those chunks

Without RAG, Claude can only answer questions based on its training data. With RAG, you inject relevant context directly into the prompt.

Architecture

  1. Indexing: load docs → split into chunks → embed → store in vector DB
  2. Querying: embed question → find similar chunks → send to Claude → return answer

Step 1: Install Dependencies

pip install anthropic chromadb sentence-transformers pypdf2

Enter fullscreen mode Exit fullscreen mode

Step 2: Load and Chunk Documents

import PyPDF2
from pathlib import Path


def load_pdf(path: str) -> str:
    with open(path, "rb") as f:
        reader = PyPDF2.PdfReader(f)
        return "\n".join(page.extract_text() for page in reader.pages)


def chunk_text(text: str, chunk_size: int = 500, overlap: int = 50) -> list[str]:
    words = text.split()
    chunks = []
    i = 0
    while i < len(words):
        chunks.append(" ".join(words[i : i + chunk_size]))
        i += chunk_size - overlap
    return chunks

Enter fullscreen mode Exit fullscreen mode

Step 3: Build the Vector Index

import chromadb
from chromadb.utils import embedding_functions

embed_fn = embedding_functions.SentenceTransformerEmbeddingFunction(
    model_name="all-MiniLM-L6-v2"
)
client = chromadb.PersistentClient(path="./chroma_db")


def build_index(documents: list[dict], collection_name: str = "docs"):
    collection = client.get_or_create_collection(
        name=collection_name,
        embedding_function=embed_fn,
    )
    texts, ids, metadatas = [], [], []
    for i, doc in enumerate(documents):
        for j, chunk in enumerate(chunk_text(doc["text"])):
            texts.append(chunk)
            ids.append(f"{doc['source']}_chunk_{j}")
            metadatas.append({"source": doc["source"]})

    collection.add(documents=texts, ids=ids, metadatas=metadatas)
    return collection

Enter fullscreen mode Exit fullscreen mode

Step 4: Query + Generate Answer

def retrieve(question: str, collection, n_results: int = 5) -> list[str]:
    return collection.query(query_texts=[question], n_results=n_results)["documents"][0]


def generate_answer(question: str, chunks: list[str]) -> str:
    context = "\n\n---\n\n".join(chunks)
    response = claude.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        messages=[{
            "role": "user",
            "content": f"Answer using ONLY the context below.\n\nContext:\n{context}\n\nQuestion: {question}"
        }],
    )
    return response.content[0].text

Enter fullscreen mode Exit fullscreen mode

Step 5: Full Chatbot Script

import anthropic
import chromadb
from chromadb.utils import embedding_functions
import PyPDF2
from pathlib import Path

embed_fn = embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")
chroma = chromadb.PersistentClient(path="./chroma_db")
claude = anthropic.Anthropic()


def index_files(file_paths: list[str]) -> None:
    collection = chroma.get_or_create_collection("docs", embedding_function=embed_fn)
    texts, ids, metas = [], [], []
    for path in file_paths:
        p = Path(path)
        if p.suffix == ".pdf":
            with open(p, "rb") as f:
                text = "\n".join(page.extract_text() for page in PyPDF2.PdfReader(f).pages)
        else:
            text = p.read_text()
        for j, chunk in enumerate(chunk_text(text)):
            texts.append(chunk); ids.append(f"{p.name}_{j}"); metas.append({"source": path})
    collection.add(documents=texts, ids=ids, metadatas=metas)
    print(f"Indexed {len(texts)} chunks")


def ask(question: str) -> str:
    collection = chroma.get_collection("docs", embedding_function=embed_fn)
    chunks = collection.query(query_texts=[question], n_results=5)["documents"][0]
    context = "\n\n---\n\n".join(chunks)
    response = claude.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1024,
        messages=[{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"}],
    )
    return response.content[0].text


if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        index_files(sys.argv[1:])
    else:
        print("RAG Chatbot ready. Type 'quit' to exit.")
        while True:
            q = input("You: ").strip()
            if q.lower() in ("quit", "exit"): break
            print("Bot:", ask(q), "\n")

Enter fullscreen mode Exit fullscreen mode

Usage

# Index documents
python chatbot.py company_handbook.pdf product_docs.txt

# Start chatting
python chatbot.py

Enter fullscreen mode Exit fullscreen mode

Performance Tips

  • Chunk size: 300–600 words is a good starting range
  • Increase n_results for complex questions
  • Metadata filtering: where={'source': 'specific.pdf'} to restrict search
  • Reranking: use a cross-encoder reranker for production quality
  • Caching: cache embeddings to speed up re-indexing

Summary

You built a RAG chatbot that:

  • Loads PDF and text documents
  • Splits into overlapping chunks
  • Embeds and stores in ChromaDB
  • Retrieves relevant chunks per question
  • Generates grounded answers with Claude