{"slug": "build-a-chatbot-and-rag-app-from-scratch-in-under-100-lines-of-python", "title": "Build a Chatbot and RAG App From Scratch in Under 100 Lines of Python", "summary": "A tutorial published on an unnamed blog shows how to build a retrieval-augmented generation (RAG) chatbot in under 100 lines of Python using only the Anthropic Claude API, the sentence-transformers library and NumPy, with no LangChain or vector database. The app reads every .txt and .md file in a folder, splits text into 150-word chunks with 30-word overlap, embeds them locally with the all-MiniLM-L6-v2 model (about a 90 MB first-run download), retrieves the top 4 chunks per question, and streams Claude answers with source citations and conversation memory. The post argues RAG's reputation for complexity is overstated: find relevant document pieces, paste them into the prompt, and ask the model to answer from them.", "body_md": "*No LangChain, no vector database, no framework. Just Python, a small embedding model, and the Claude API.*\n\nRetrieval-augmented generation (RAG) has a reputation for being complicated, with tutorials that start by installing five frameworks and a database. The core idea is much simpler: find the pieces of your documents that are relevant to a question, paste them into the prompt, and ask the model to answer from them. That’s it.\n\nIn this post we’ll build it in two steps. First, a plain chatbot in about a dozen lines. Then a complete RAG app, with streaming answers, source citations and conversation memory, in under 100 lines.\n\n## What you’ll build\n\nA terminal app that:\n\n- reads every `.txt` and`.md` file in a folder\n- splits the files into chunks and indexes them with a local embedding model\n- finds the most relevant chunks for each question\n- streams an answer from Claude that cites the source files\n- remembers the conversation\n\n## Setup\n\n```\npip install anthropic sentence-transformers numpy\nexport ANTHROPIC_API_KEY=\"your-key-here\"\n```\n\nOn Windows PowerShell, set the key with `$env:ANTHROPIC_API_KEY=\"your-key-here\"` instead.\n\nThe embedding model runs on your own machine (it downloads about 90 MB on first run), so the only thing that calls an API is the final answer. You’ll need a recent Python 3; version 3.10 or newer is a safe choice.\n\n## Step 1: A chatbot in a dozen lines\n\n``` python\nimport anthropic\n\nMODEL = \"claude-sonnet-5-5\"\nclient = anthropic.Anthropic()\nhistory = []\n\nwhile True:\n    user = input(\"You: \")\n    history.append({\"role\": \"user\", \"content\": user})\n    reply = client.messages.create(model=MODEL, max_tokens=1000, messages=history)\n    text = reply.content[0].text\n    print(\"Bot:\", text)\n    history.append({\"role\": \"assistant\", \"content\": text})\n```\n\nPress `Ctrl+C` to quit. Two things to notice. First, the API is stateless: the model remembers nothing between calls, so we resend the entire `history` every turn. Second, the model only knows what it learned in training. It has never seen your documents. Ask it about your company handbook or last month’s meeting notes and it will either say it doesn’t know or, worse, make something up.\n\n## Step 2: Add retrieval\n\nRAG fixes that by adding a search step before the model answers:\n\n1. **Chunk:** split your documents into small, overlapping passages.\n2. **Embed:** turn each chunk into a vector, a list of numbers that captures its meaning. Texts with similar meanings end up with similar vectors.\n3. **Retrieve:** embed the question, then pick the chunks whose vectors are closest to it.\n4. **Generate:** give those chunks to the model as context and ask it to answer from them.\n\nEach step becomes one small function in the code below.\n\n## The full code\n\nSave this as `rag_chat.py`:\n\n``` python\nimport sys\nfrom pathlib import Path\n\nimport anthropic\nimport numpy as np\nfrom sentence_transformers import SentenceTransformer\n\nMODEL = \"claude-sonnet-5-5\"\nCHUNK_WORDS = 150  # words per chunk\nOVERLAP = 30       # words shared between neighbouring chunks\nTOP_K = 4          # chunks sent to the model\n\nclient = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment\nembedder = SentenceTransformer(\"all-MiniLM-L6-v2\")  # small, fast, runs locally\n\ndef chunk_text(text: str) -> list[str]:\n    \"\"\"Split text into overlapping windows of words.\"\"\"\n    words = text.split()\n    step = CHUNK_WORDS - OVERLAP\n    return [\" \".join(words[i:i + CHUNK_WORDS]) for i in range(0, len(words), step)]\n\ndef load_chunks(folder: str) -> list[dict]:\n    \"\"\"Read every .txt/.md file and return chunks tagged with their source.\"\"\"\n    chunks = []\n    for path in sorted(Path(folder).rglob(\"*\")):\n        if path.suffix in {\".txt\", \".md\"}:\n            for piece in chunk_text(path.read_text(encoding=\"utf-8\")):\n                chunks.append({\"source\": path.name, \"text\": piece})\n    return chunks\n\ndef build_index(chunks: list[dict]) -> np.ndarray:\n    \"\"\"Embed all chunks. Normalised vectors make cosine similarity a dot product.\"\"\"\n    return embedder.encode([c[\"text\"] for c in chunks], normalize_embeddings=True)\n\ndef retrieve(question: str, chunks: list[dict], index: np.ndarray, k: int = TOP_K) -> list[dict]:\n    q = embedder.encode([question], normalize_embeddings=True)[0]\n    scores = index @ q  # similarity of the question to every chunk\n    return [chunks[i] for i in np.argsort(scores)[::-1][:k]]\n\nSYSTEM = (\n    \"You answer questions using ONLY the context provided in each message. \"\n    \"After each claim, cite the source file name in square brackets, e.g. [guide.md]. \"\n    \"If the context does not contain the answer, say you don't know.\"\n)\n\ndef ask(question: str, history: list[dict], chunks: list[dict], index: np.ndarray) -> None:\n    context = \"\\n\\n\".join(f\"[{c['source']}]\\n{c['text']}\" for c in retrieve(question, chunks, index))\n    prompt = f\"Context:\\n{context}\\n\\nQuestion: {question}\"\n    messages = history + [{\"role\": \"user\", \"content\": prompt}]\n    reply = \"\"\n    with client.messages.stream(model=MODEL, max_tokens=1000, system=SYSTEM, messages=messages) as stream:\n        for text in stream.text_stream:\n            print(text, end=\"\", flush=True)\n            reply += text\n    print()\n    # Save the plain question, not the bulky context, to keep the history small\n    history.extend([{\"role\": \"user\", \"content\": question},\n                    {\"role\": \"assistant\", \"content\": reply}])\n\ndef main():\n    folder = sys.argv[1] if len(sys.argv) > 1 else \"docs\"\n    chunks = load_chunks(folder)\n    if not chunks:\n        sys.exit(f\"No .txt or .md files found in '{folder}/'\")\n    index = build_index(chunks)\n    print(f\"Indexed {len(chunks)} chunks from {folder}/. Type 'quit' to exit.\\n\")\n    history = []\n    while True:\n        question = input(\"You: \").strip()\n        if question.lower() in {\"quit\", \"exit\"}:\n            break\n        if question:\n            print(\"Bot: \", end=\"\")\n            ask(question, history, chunks, index)\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## How it works\n\n**Chunking.** `chunk_text` slides a 150-word window across each file, stepping forward 120 words at a time, so neighbouring chunks share 30 words. The overlap reduces the chance of an answer being cut in half at a chunk boundary. Word-based chunks are crude, but they’re easy to understand and good enough to start with.\n\n**Embeddings and search.** `all-MiniLM-L6-v2` is a small model that turns text into 384-number vectors. We pass `normalize_embeddings=True`, which scales every vector to length 1. That makes cosine similarity just a dot product, so the whole search is `index @ q`: one matrix multiplication scores every chunk, and `argsort` picks the best four. For a few thousand chunks this is fast, so no vector database is needed.\n\n**The prompt.** Each question is sent along with the retrieved chunks, each labelled with its file name. The system prompt does the important work: it tells the model to use only the provided context, to cite its sources, and to say it doesn’t know when the context doesn’t contain the answer. That last rule helps cut down on made-up answers, though it doesn’t eliminate them.\n\n**Memory.** After each turn we save the plain question and the answer in `history`, not the bulky retrieved context. That keeps the conversation small, and every new question brings its own fresh context anyway.\n\n**Streaming.** `client.messages.stream` yields text as it’s generated, so answers appear word by word instead of after a long pause.\n\n## Try it\n\n```\nmkdir docs\n# drop a few .md or .txt files in there: a README, meeting notes, an exported wiki page\npython rag_chat.py docs\n```\n\nAsk a few questions whose answers are in your files, then ask one that isn’t. The bot should name the source files for the first kind and admit it doesn’t know for the second.\n\n## Where this breaks (and what to improve)\n\nFitting in under 100 lines means taking shortcuts. These are the ones worth fixing first:\n\n- **Follow-up questions.** A message like “what about the second option?” retrieves poorly, because search only sees the latest message. The fix is to ask the model to rewrite the question into a standalone query, using the history, before searching.\n- **Re-indexing on every launch.** Save the embeddings with`np.save` and reload them, or move to FAISS, Chroma or sqlite-vec once your collection grows.\n- **Crude chunking.** Split on headings or paragraphs instead of word counts, so chunks follow the structure of the document.\n- **Weak retrieval.** Combine keyword search (BM25) with embeddings, and add a reranker to reorder the top results.\n- **No way to measure quality.** Write 20 questions along with the file each answer should come from, then check how often the right file lands in the top four. It’s the most useful thing you can add.\n\n## Wrapping up\n\nRAG is just search plus prompting. Once you see it that way, the frameworks stop being mysterious, and you can decide for yourself when they’re worth adding. From here, a natural next step is wrapping `ask` in a FastAPI endpoint or a Streamlit chat page so other people can use it.", "url": "https://wpnews.pro/news/build-a-chatbot-and-rag-app-from-scratch-in-under-100-lines-of-python", "canonical_source": "https://zyvop.com/build-a-chatbot-and-rag-app-from-scratch-in-under-100-lines-of-python-j13jn", "published_at": "2026-11-29 10:26:31+00:00", "updated_at": "2026-11-29 10:43:49.738915+00:00", "lang": "en", "topics": ["large-language-models", "ai-tools", "developer-tools", "generative-ai"], "entities": ["Anthropic", "Claude", "sentence-transformers", "all-MiniLM-L6-v2", "NumPy", "LangChain", "Python"], "also_reported_by": [], "takeaway": "A working RAG app needs no framework or vector database: chunk documents into 150-word windows with 30-word overlap, embed them locally with all-MiniLM-L6-v2, and send the top 4 chunks to Claude as context.", "recommendation": {"advice": "Skip the vector database for small corpora: embed chunks locally with all-MiniLM-L6-v2, retrieve the top 4 by cosine similarity, and paste them into the Claude prompt with source tags.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/build-a-chatbot-and-rag-app-from-scratch-in-under-100-lines-of-python", "markdown": "https://wpnews.pro/news/build-a-chatbot-and-rag-app-from-scratch-in-under-100-lines-of-python.md", "text": "https://wpnews.pro/news/build-a-chatbot-and-rag-app-from-scratch-in-under-100-lines-of-python.txt", "jsonld": "https://wpnews.pro/news/build-a-chatbot-and-rag-app-from-scratch-in-under-100-lines-of-python.jsonld"}}