Skip to content

RAG (retrieval-augmented generation)

Run it, don't just read it

Every lab runs on your laptop with Ollama. Set up once (INSTALL), then:

git clone https://github.com/JSWOne/ai-learning.git && cd ai-learning
cd rag && python 01_embeddings.py

Lab files and data: rag/ on GitHub. In VS Code, open the repo folder and use Terminal > Run Task > Run this lab.

Small, runnable examples of RAG over a fake B2B knowledge base, local by default (Ollama) or any hosted provider through the door. Each file shows one pattern. New to RAG? Read learn-rag.md first: what it is and why, the mental model in code and diagrams, the labs in four stages, key decisions and advanced topics. Before you start: prompting; lab 10 also uses the tool loop from llm-api. After it, you can: answer from documents with citations, and measure it; read PDF and Excel files; answer questions from a database safely (labs 11-13). Done with the labs? Try the three exercises and the build-it-yourself task in PRACTICE.md. Serving it? SHIP.md puts lab 04 behind an API: streaming, Docker and user feedback.

The documents live in docs/ (returns, shipping, credit terms, tier pricing, product datasheets). Replace them with your own. Labs 11 to 13 add messy files in raw-docs/ (a PDF datasheet, an Excel register, a scanned page) and a small sales database.

Setup

Install steps for all topics are in ../INSTALL.md. RAG needs one extra model:

ollama pull nomic-embed-text      # embeddings, about 270 MB

Run any example from this folder, for example python 04_basic_rag.py. The first run creates the vector store in store/.

Files

Track: Core labs are the Core path through the course. Before you ship: safety lessons to do before anything you build goes to real users. Go further: when your work needs that pattern (see Use it when).

File Track Pattern Use it when Time
01_embeddings.py Core Text to vectors, cosine similarity, no database Understand what "semantic search" really does seconds
02_chunking.py Go further Fixed-size vs heading-aware chunks (no model needed) Deciding how to cut your documents <1 s
03_ingest_and_search.py Core Store in Chroma, re-ingest only changed docs, vector search Building the index ~30 s
04_basic_rag.py Core Retrieve, build the prompt, answer with citations, "I don't know" The core loop ~30 s
05_hybrid_search.py Core Vector + BM25 keyword search fused with RRF SKUs, part numbers, standards in queries ~10 s
06_metadata_filters.py Before you ship Filter by customer tier or doc type inside the query Access control, multi-tenant data ~1 min
07_conversational.py Go further Rewrite follow-ups into standalone questions Chat UIs ~1 min
08_reranking.py Go further Retrieve wide, rerank with the LLM, keep the best few Right chunk retrieved but ranked low ~1 min
09_evaluation.py Core Golden set, hit@k and MRR, answer fact checks Every change to chunking, model or search ~10 s
10_agentic_rag.py Go further Retrieval as a tool next to live stock and price tools Questions that need docs and live data ~2 min
11_messy_documents.py Go further PDF and Excel read by structure: headers and footers dropped, one chunk per table row, merged cells filled, scans flagged Your knowledge is in PDFs and spreadsheets, not clean text ~1-2 min
12_text_to_sql.py Go further Talk to your data: question to SQL to answer, scored by running the SQL; bare vs documented schema Questions that count, sum or rank rows in a database ~3-5 min
13_sql_guardrails.py Before you ship Read-only connection, SQL parsed and allow-listed, rows scoped to the customer in code, time and row caps; then a semantic layer Before users' questions reach your database ~2-3 min

Shared code: rag.py (load, chunk, embed, ingest, search, generate, metrics). Data: docs/*.md with a small front-matter header (title, doc_type, tier). Labs 11 to 13: messy.py (PDF and Excel to the same Doc), text_to_sql.py (sales database, schema notes, ask, scoring), sql_guard.py (the four guard layers), semantic.py (metrics in code). raw-docs/make_raw_docs.py rebuilds the messy files; the database (store/sales.db) is built from a fixed seed on first run.

Exercises to practise with: PRACTICE.md (your own files go in my-work/). Questions and answers on all of this are in FAQ.md. The learning guide is learn-rag.md (diagrams in diagrams/).

Rules of thumb

  • Debug retrieval before the prompt. If the right chunk is not in the 📄 lines, no prompt fix will help.
  • Chunk by the document's structure (headings, FAQ entries, table rows) and put "Title > Section" at the top of each chunk.
  • Use hybrid search for B2B. Buyers type SKUs and standards, and vectors handle codes badly.
  • Filter in the database, not in the prompt. A chunk that was never retrieved cannot leak.
  • Changing the embedding model or chunker means re-embedding everything. Delete store/ and ingest again.
  • Keep a golden set of real questions and run it on every change (example 09).
  • Read the extracted text before tuning search. Tables become one chunk per row, with the column names in every chunk (example 11).
  • Questions that count, sum or rank go to SQL, not RAG. Model-written SQL runs read-only, parsed and scoped to the user in code (examples 12 and 13).
  • Tell the model what to do when the answer is missing, and check citations in code.

Tests

pytest -q runs model-free tests for loading, chunking, ingest (including re-ingest), search, fusion, filters, prompt building and metrics. A fake embedding (hashed bag of words) stands in for the model. test_messy.py checks the PDF and Excel parsing on the committed files; test_sql.py checks the guard layers, customer scoping, scoring and the semantic layer on the seeded database, with a fake model writing the SQL. Retrieval quality with the real embedding model, and the answers from qwen3:8b, can only be checked by running the examples against Ollama.