
Why does a chatbot quote a price that never appeared on your pricing page, and what does it take to build one that answers from the pages you choose?
Hear the support-inbox story: a fluent general model answering from training, not from the published page.
Check the fit: you know what a database and an API are, and you are willing to look at files and run commands.
See what this course is not: ChatGPT tips, a LangChain or Llama Index tour, or a no-code PDF chat.
Bookmark the companion repo rag_tutorial, one system built on FastAPI, Scrapy, and Postgres.
You leave with one written sentence: the assistant you want to build and the pages it must answer from.
What do you need before installing anything, including paid components?
Check the prerequisites: you can explain a database and an API, have written a little code, and have used a terminal.
See the setup ahead: Git plus Docker, standardized on Docker Compose, with no GPU and no model training.
Learn where OpenAI cost comes from: one embedding call per stored chunk, and one embedding plus one chat call per ask.
Control that cost with a short page list and a spending limit set before you crawl.
You leave with a requirements note: four yes-or-no lines, plus a fifth for billing and a spending limit.
What does an answer look like when it comes from pages that were crawled and stored, not from a model's training?
Open responses/01-mentorship-pricing.md in the companion repo and read a real saved answer from a sample site.
See why RAG lets you build an assistant on pages you trust, with sources you can inspect.
Learn the limit: grounding is not a magic accuracy upgrade, so a wrong answer sends you to the stored pages and numbered chunks first.
You leave with one written fact from that saved answer, with nothing installed yet.
The page you pick now often decides whether your crawl later stores the fact you care about.
See one checkpoint per section: theory, a health check on localhost port 8000, the API and database, the crawl, and the grading.
Write an acceptance card: site, page path, question, and expected fact.
Test the page in View Page Source, since a page drawn only by JavaScript can log completion and store nothing.
You leave with the card you use later to prove the knowledge base and grade pass or fail.
Why does a model answer from the travel section when the parental-leave sentence was in the handbook you pasted? The cause is a pipeline problem, and this map lays out its eight stages in order.
Follow gather, split, embed each piece, store the vectors, embed the question, find similar pieces, call the model, and return an answer.
See what each stage takes in and sends out, and why the order cannot change.
Start a pipeline sheet: eight rows with columns for stage, input, output, choice, and likely failure.
You leave with a habit for wrong answers: ask which stage failed. Nothing is installed.
A scanned policy and an all-hands recording can sit in your folder and still return nothing from search. Every source has to become clean text before any later stage can use it.
Name the job per source: OCR for scans, speech-to-text for audio, a crawler for web pages, pass-through for plain text, and joined fields for database rows.
Check a web page with View Source: if the fact is not there, the crawler has nothing to gather.
Spot dirty text, such as scan gibberish or a JavaScript-only page, before blaming the model.
You leave with the gather row of your pipeline sheet written, with crawler circled for the lab.
When a refund rule is cut in half at a chunk boundary, retrieval can find the return rule and miss the thirty-day window. How you split text decides whether a specific fact can be found at all.
Compare three split styles: fixed size, one chunk per paragraph, and splits that follow meaning.
Weigh chunk length in tokens: around 200 is precise, around 500 is a common balance, and 1,000 or more is richer and noisier.
See how overlap keeps a boundary sentence whole, and what it costs in storage and compute.
You also see that the companion repo cuts 1,000 characters with no overlap, so the simple version is easy to recognize later.
Embed the pages with one model and the question with another, and the question never lands near the right text, even when every chunk is stored. An embedding is a long list of numbers that stands in for meaning.
See why dog, puppy, and canine sit close together without sharing a spelling.
Compare smaller and larger embedding models from OpenAI, Google, and open source. You call a model; you do not train one.
Learn why mixed models with matching vector lengths fail quietly, and why changing models means re-embedding every chunk.
You leave with one rule for embedding chunks and questions: one model, one space.
A notebook that compares the question to every stored vector works at a thousand rows and is too slow at millions. A vector store exists for search, not only for saving rows.
See what an index is for: finding similar vectors without walking every row.
Hear four stores named: Pinecone, Weaviate, Qdrant, and pgvector in Postgres, which the lab uses.
Decide which metadata to keep beside each chunk (page, source name, URL, and date) so an answer can point back to its source later.
No tables are created here. You leave with the store row of your pipeline sheet written.
Keep only the nearest chunk, and a two-part question loses its second fact. Drop the bar too low, and an unrelated chunk adds junk. This stage decides which pieces the model is allowed to see.
Read cosine similarity scores: near one is a strong match, near zero is weak.
Choose a top-k such as 1, 3, 5, or 10, and see what too few and too many cost.
Use a threshold as a second cut, and trade precision against recall on a worked example with scores of 0.8, 0.5, and 0.35.
You also see how the companion repo is set: at most five chunks, and any score under 0.3 is dropped.
A system message that said to be helpful and complete let a model invent a warranty the pages never mentioned. A grounded call is two messages with a fence, not a friendly tone.
Write the two rules for the system message: answer from this context, and say you do not know when it is not there.
Place the question in the user message and the retrieved chunks in the same call. The lab puts them right under the system rules.
Compare a soft system message with a fenced one, and see why I do not know counts as a win.
A correct paragraph can still leave a help page unfinished when the visitor needs a table and a source link. The model writes the words; the application decides the shape the person sees.
Compare four answer shapes: markdown, a table, citations built from stored metadata, and a structured object another program can read.
Walk one acceptance-card question through all eight stages and fill every row of your pipeline sheet.
See which layers stay out of the eight stages on purpose: memory, hybrid search, agents, tool calling, and reranking.
You leave with a one-page diagnostic map for asking which stage failed.
A clone command that returns "command not found: git" stops the setup before it starts. Get Git onto the machine where you will clone the companion repo, on Mac, Windows, or Linux.
Check first with git --version and skip the install if a version prints.
Install through xcode-select --install on a Mac, the git-scm.com installer on Windows, or apt, dnf, or pacman on Linux.
Fix the stale-window failure: close every terminal, open a fresh one, and run the check again without sudo.
You leave with your Git version line written in your requirements note. No GitHub account needed.
A Compose version can print while the Docker engine is not running at all. On a Mac, you check two things: the Compose version and an engine that answers.
Pick the Apple Silicon or Intel build of Docker Desktop with uname -m, install it, and wait for the whale to go idle.
Run docker compose version, then docker ps, and read the empty table as proof the engine answered.
Use docker compose with a space, and skip a second Compose from Homebrew.
You leave with your Mac Compose version line, written only after docker ps answers.
On Windows, the terminal you use has to print a Compose version and reach a running engine. Set that up on the WSL 2 backend, which works on Home, Pro, and Education.
Confirm virtualization in Task Manager, then run wsl --install and wsl --status.
Install Docker Desktop with WSL 2 checked and turn on WSL integration for your distro.
From a fresh window, run docker compose version and docker ps until the empty table appears.
Recognize the usual failures: a stale window, integration off, or the engine starting forever.
You leave with your Windows Compose version line.
An old hyphenated docker-compose can answer, while docker compose with a space says it is not a command. On Linux, install Docker Engine and the Compose plugin from Docker's own packages, not Desktop.
Add Docker's apt repository and install docker-ce and docker-compose-plugin on Ubuntu or Debian.
Confirm the service with sudo systemctl status docker.
Fix permission denied on the Docker socket with usermod -aG docker and a full logout.
You leave with your Linux Compose version line, once docker ps answers without sudo from a fresh login.
"Repository not found" usually means a typo in the address, not a missing repo. Clone the public companion repository over HTTPS and stop at the top of the tree.
Clone rag_tutorial from github.com/mmmohajer, three m's in a row, with no GitHub login.
Enter the folder once and avoid a nested rag_tutorial/rag_tutorial copy.
Confirm docker-compose.yml and secrets/ at the repo root.
Tell the clone failures apart: command not found, repository not found, folder already exists.
You leave with the repo on disk and its full path written in your requirements note.
Copied samples are not enough: the API sample ships blank, and an API with no database host gives up a minute after starting. Create all three env files Compose reads, and fill the API one on purpose.
Copy each sample to secrets/db/.env, secrets/api/.env, and secrets/scraper/.env.
Set DB_HOST=db, the Compose service name, not localhost, and match the database user, password, and name.
Paste your OpenAI key now and leave the scraper's API_URL as http://api:8000.
You leave with three real env files on disk, kept out of git.
A prompt returning after the up command doesn't prove the stack works. Two checks: three services listed, and the API responding on port 8000.
Start the stack with docker compose up -d --build from the repo root.
Read docker compose ps: db healthy, api and scraper up, the scraper idle on purpose.
Open http://localhost:8000/ and see {"success": true}, which does not call the model.
Find a stopped API with docker compose ps -a and docker compose logs api.
You leave with your first running artifact recorded in your requirements note.
With the containers running, which top-level folder is the process you just hit, which one is sleeping, and which one holds the keys? Give each name a job without opening the crawler code.
Tie docker-compose.yml to its three services: api, db with pgvector, and an idle scraper.
Place api/, scraper/, and secrets/ against what is running.
Read api.http as a menu of later requests and responses/ as saved sample answers, not a knowledge base.
You leave with a six-line folder map in your requirements note.
Why does DB_HOST=localhost look like a password problem inside the API container? Open the api and db services in docker-compose.yml and see how they reach each other.
The db service: a pgvector image, the pgdata volume, and a pg_isready health check
The api service: built from ./api, published on port 8000, started only once that health check passes
Why the ./api mount runs the code you edit, while the image still owns the installed packages
You leave with a four-line wiring note you can check against the running stack.
Why does a one-line code change not reinstall every library? The API image is ordered so it does not.
An Alpine Python base and a WORKDIR of /usr/src/app, the path the Compose volume mounts onto
Copy requirements.txt and run pip install first, then COPY . . so the install layer stays cached
Why EXPOSE 8000 only documents the port, and Compose is what publishes it
A non-root app user that runs the entrypoint, the migrations, and uvicorn
You are able to explain each line and confirm the user with whoami inside the container.
The pgvector line in requirements.txt is not the database. It is a Python package that lets SQLAlchemy describe a vector column.
FastAPI and uvicorn for app/main.py and the entrypoint
pydantic-settings and python-dotenv for app/settings.py
SQLAlchemy, Alembic, and psycopg for the database session, the models, and the migrations
The openai package for app/providers/rag.py
You leave knowing which file uses each pinned library, and why a pin change needs an image rebuild while a Python edit does not.
Why can the log say it is waiting for the database after Compose has already marked the DB healthy? Read docker-entrypoint.sh and see that these are two different checks.
The socket wait on DB_HOST and DB_PORT, and what happens when it times out
The boot order: wait, then alembic upgrade head, then uvicorn on port 8000
Why docker compose run goes through the entrypoint and docker compose exec does not
You are able to read Docker Compose logs api and name the step that failed.
A strong password can work for Postgres and still break the API's database URL. Read how app/settings.py turns env values into typed settings.
The six env names Settings reads from secrets/api/.env
How database_url builds postgresql+psycopg:// and escapes the user and password with quote_plus
Which values you may change, and why DB_HOST stays db under Compose
Why a missing OpenAI key crashes at import, while a blank one fails on the first paid call
A page is what you delete, and a chunk is what you search. Two SQLAlchemy models carry that split.
app/db.py: the engine, the session factory, Base, and get_db opening one session per request
KbPage: one row per unique URL in kb_pages
KbChunk: numbered pieces, unique on page plus chunk number, with a 3,072-float embedding column
Cascade delete, so dropping a page drops its chunks
Empty tables still have this shape, and empty is not broken.
The localhost URL in alembic.ini is a dummy, so pasting a real address there cannot fix a failed migration. Read the Alembic folder the repo already ships.
What alembic init created once, and why you do not run it again
version_locations pointing at app/rag/migrations, next to the feature
How env.py imports the models and injects settings.database_url
How to read Alembic history, with the newest revision at the top
Why are there two migrations, and why does the handwritten one run first? Autogenerate creates tables, but it never enables the vector extension.
The enable_pgvector revision: CREATE EXTENSION IF NOT EXISTS vector
The tables revision: kb_pages, kb_chunks, a vector(3072) column, cascade delete, and an index on page id
Checking that alembic current shows head and that \dx lists vector
You also see why upgrade head runs on every start, and why you do not rerun autogenerate on the clone.
The backend is four layers, not one large file where every path talks to Postgres. See where each job lives.
app/main.py: GET / returns success true with no database and no model
schemas.py: the JSON that may enter and leave, validated before any SQL
services.py does the database work, and router.py holds thin /rag paths that depend on get_db
constants.py: embedding dimension 3072 and the system message
You are able to say which file a new job belongs in.
Two empty lists from the API are the correct result before any crawl, not a bug. Walk each /rag route and the reason it exists.
POST /rag/pages returns 200 for a stored URL and 201 for a new one, and DELETE takes the chunks with the page
POST /rag/chunks embeds the text, then inserts, or returns 404 for a missing page
POST /rag/ask embeds the question, keeps up to 5 chunks at a 0.3 cosine threshold, and returns one answer string
You leave knowing which two routes call the OpenAI client.
Model names live in one class, so a change happens in one place. Open app/providers/rag.py and read the Rag class.
The defaults: text-embedding-3-large and gpt-6-astra, plus a client built from the settings key
build_embedding refuses empty text and checks for a 3,072-float vector
generate_response sends a system and a user message and returns the content string
Why a new embedding model means embedding every chunk again, while a chat model change needs no migration
Why can the scraper show Up in docker compose ps while the knowledge base still has no pages? Alive is not crawled, and the Compose file is built that way on purpose.
Read the scraper block in docker-compose.yml: build, env file, volume mount, and the tail -f /dev/null keep-alive.
See why the image default in scraper/Dockerfile, scrapy crawl pages, is overridden so a stack start never bills a crawl.
Check that secrets/scraper/.env holds only API_URL and SITE_URL, with no OpenAI key.
Confirm an empty GET /rag/pages is the correct picture before any crawl.
You leave with an idle scraper you understand and a place to type a crawl later.
Type scrapy crawl pages in a random folder, and Scrapy says the command is not available. Crawl only exists inside a Scrapy project, and one small file marks where that project is.
Read the three lines of scraper/requirements.txt: Scrapy, pydantic settings, and python-dotenv.
Open scrapy.cfg and see its single default key point at target_site.settings.
Learn why the command matches the spider's name line, pages, not the class name PagesSpider.
Tell apart the two settings files: one for the API and site addresses, one for how Scrapy behaves.
A path can sit in your list and still never reach the parser. That is not a broken spider; it is the site's robots.txt refusing the fetch, exactly as this repo asks.
Read ROBOTSTXT_OBEY and the SiteBot/1.0 user agent in target_site/settings.py.
See how the most specific user-agent block wins, and why your browser is not SiteBot.
Find robotstxt/forbidden in the closing stats, and learn that a missing line means zero refusals.
Use -L DEBUG in capitals to see the skip next to one address.
You are able to tell a robots skip from a request that was allowed but still saved nothing.
Which pages get crawled? Only the ones you list. There is no sitemap reader and no link following, so the path list is the crawl.
Set SITE_URL in secrets/scraper/.env, starting with https, and leave API_URL as http://api:8000.
Replace the sample PAGE_PATHS list, where an empty string means the homepage and every other path starts with a slash.
Recreate the scraper with docker compose up -d scraper and prove the value with printenv; a plain restart does not reread the env file.
You leave with a short path list on your own site, kept short because every stored chunk is a paid embedding.
How does the spider get pages into the database? It does not touch Postgres; it calls the API, and replacing a URL requires several HTTP calls, not one transaction.
Read PagesSpider in target_site/spiders/spider.py and see start_urls built from SITE_URL plus PAGE_PATHS.
Follow the helpers in order: list pages, delete the old page if an ID exists, save the page, then save each chunk.
See that the API embeds each chunk on POST /rag/chunks; the spider only posts text.
Know what a failure halfway through leaves behind, and why a re-run fixes it.
What text actually gets stored from a page? Visible text only, cut into fixed pieces, with a title that may not match the heading you see.
See the stored title come from the title tag, falling back to the URL.
Watch parse drop script, style, and noscript, then join the remaining text.
Read chunk_content in target_site/utils.py: one thousand characters per chunk, no overlap, numbered from one.
Learn why a JavaScript-only page can log Page completed successfully and store nothing.
You will be able to predict how many chunks a page becomes and why a fact can be missing.
One command turns the idle scraper into stored pages and chunks, and it is the step that spends embedding money, so you run it on purpose.
Run docker compose exec scraper scrapy crawl pages from the repo root, with no second compose up and no rebuild.
Read the Page completed successfully line for each allowed page and check the address starts with https.
Check the closing stats for robotstxt/forbidden.
Recognize the cheap failures first: a missing scheme, an empty SITE_URL, a stack that is not up, a blank key.
You leave with one real crawl of your listed pages.
Did the crawl really store your page, and does the bot answer from it? You prove it in order: list what landed, find the fact, then ask.
Run GET /rag/pages in api.http and confirm your page is listed with a title and an ID.
Search GET /rag/chunks for the expected fact before you ask anything.
Send POST /rag/ask with your own question in user_message and read the single answer string against that fact.
See why an empty knowledge base gets a polite refusal, not an invented answer.
You leave with three pieces of proof: the page, the chunk, and the reply.
The repo ships saved answers from a real public site, and they show the same crawl, store, and ask path that already worked once. They are documentation, not data.
Open responses/01-mentorship-pricing.md and see the question and the answer from the sample site.
Confirm nothing writes to this folder: not the spider, not the API, not your ask.
Tell the folder apart from the knowledge base: GET /rag/pages never lists these files.
You leave with two proofs side by side: your live ask and the archived sample.
A visitor who types a question should not stare at a silent spinner while POST /rag/ask waits for the whole reply. What belongs in front of the answer function for a real person?
See what RagAnswer returns today: one field, response, a string, with no tokens along the way and no conversation ID.
Map a conversation page and a websocket that streams the reply token by token.
Check that retrieval stays unchanged: chunks still come from Postgres.
You leave with one sentence for your next project. The page is mapped, not built in this repo.
A follow-up like the cheaper one names no plan and no price, and today every POST /rag/ask hears it as a first question. Where should recent conversation live?
Map Redis as chat memory: a conversation ID, the last few turns, and a short budget so the prompt has a ceiling.
See why pages stay in Postgres, and why moving them into Redis builds a second knowledge base.
Check that memory never supplies a price the stored chunks do not contain.
You leave with a four-line memory plan. Redis is not added to this repo.
Sometimes the expected fact is on the page and still gets cut in half between two chunks. Where is that cut made, and what could replace it?
Open chunk_content in target_site/utils.py and see the whole policy: every 1,000 characters, no overlap.
Compare overlap, paragraph splits, and meaning-based splits, and what each one costs.
See why a hand-written chunk, a new embedding model, or a second splitter is the wrong fix.
You leave knowing the one function to change in a later project, and how to measure that change with your expected fact. No recrawl happens here.
Two bad answers can sound equally wrong, and only one of them is a retrieval problem. How do you tell them apart without a formal eval harness?
Build a short list of questions you already know the answers to, from your own pages.
For each row, record whether the expected fact appears in GET /rag/chunks and whether the answer stayed inside that text.
Apply two rules: fact missing means gather or split; fact stored and answer invented means the system message or the answer shape.
You leave with a known-question list you can re-run after every change.
An answer came back from the pages you chose. Did the run actually pass? Grade that crawl-store-ask pipeline using only what the API can show you, with no chat window and no recrawl.
Check one: the URL for your page path is listed in GET /rag/pages, because a completed crawl log is not proof.
Checks two and three: numbered chunks for that page appear in GET /rag/chunks, and the expected fact sits inside one of them. Write stored, not retrieved.
Check four: POST /rag/ask states that fact and adds nothing the stored chunks lack.
You leave with a graded scorecard on your acceptance card and the name of any stage that failed.
A help page wants a source link under the reply, and the API cannot give it one. What does the person need to see beyond the answer string?
See that RagAnswer is one field, response, and that page titles and URLs never leave the server.
Learn why asking the model for markdown shapes the words but gives the UI no structure it can trust.
Compare what a help page and a dashboard each need, with the application attaching the pages.
You leave preferring citations built from the page row over links the model typed. The richer payload is sketched, not implemented.
Compose publishes the API on port 8000 so you can test it. For real users, that public port is the wrong front door. What should a visitor reach instead?
Map nginx as the first process a request meets: it terminates HTTPS, serves the chat page, and proxies /rag/ask and the websocket.
See that the FastAPI container stays as built, listening on the Compose network.
Check that Postgres, Redis, and the scraper have no public ports.
Nginx is mapped, not installed in this repo, and it never retrieves chunks.
The pipeline runs, and the card has a grade. What should you build before a real customer uses it, and in what order?
Start with a write key on POST pages, POST chunks, and DELETE pages, held by the scraper and not the chat page.
Add a model-spend limit, then a vector index once the table is no longer small.
Add hybrid search only if your known-question list justifies it.
You leave with a backlog you can defend and an acceptance sentence you can prove: you crawl pages you chose, store them, and answer from them.
This course contains the use of artificial intelligence.
The chatbot quoted a price the live page never had
A visitor books mentorship on a number the chat window invented. The invoice is different. You open the pricing page. That number was never there. Someone wired a general model to a box and shipped it. The model is fluent. It is not informed.
That gap is why this course exists. A general chat model can answer a lot of public questions. It does not know the pages on your site. You need an assistant that answers from pages you chose, that you can open and inspect, and that you can grade before a real customer uses it.
By the end you can say this: I crawled pages I chose, stored them, and got an answer drawn from those pages, and I can name what is still missing before a real customer uses it.
What you leave with
You leave with a running system and written proof, not a notebook of definitions. You can show a teammate the stack you started, the pages you listed, and the scorecard you filled.
Compose stack. The API, Postgres with pgvector, and an idle scraper, started by you on Mac, Windows, or Linux.
Two tables. Pages and chunks, including a 3,072-dimension embedding column, walked on the real files of the clone.
Your crawl. Paths you listed on a site you chose, skipped where robots.txt disallows them.
One ask. Pages and chunks you can list, and one question that answers from those chunks.
Sample answers. Saved replies from the sample site as a second proof. Your crawl does not write them, and they are not a second knowledge base.
Scorecard. One question from the first section: was the page stored, is the expected fact in a chunk, did the answer stay inside your stored pages, and which stage failed if a check did not pass.
Next-layer map. A chat UI, Redis memory, better chunks, a two-check eval, a richer answer with citations, and nginx. Mapped so you know what to build next. Not built in this repo.
How the course is taught
Six sections. Forty-eight short lectures, about five hours. One system, and one companion repo named rag_tutorial. It ships finished. You clone it in section 3 and run it. You do not type the backend from an empty folder.
Sections 1 and 2. Fit, then the eight RAG stages as one picture. Nothing is installed, and nothing is built.
Section 3. Git, Docker, and Compose on Mac, Windows, or Linux, and then the stack is up.
Section 4. The API folder in the order it grew: FastAPI, SQLAlchemy, Alembic, and pgvector, on the real lines.
Section 5. Scrapy on the pages you list, honouring robots.txt. Crawl, store, ask.
Section 6. Grade your evidence, then map what a real visitor still needs. A map, not a second lab.
There is no LangChain lab. The chat model in the repo is gpt-6-astra. The embedding model is text-embedding-3-large.
Who it fits
Take it if you already know what a database is and what an API is, and you want to read a small RAG system line by line instead of calling a framework you cannot explain. The usual job is a support, company-site, or docs assistant that must answer from pages you chose.
Skip it if you want ChatGPT productivity tips, a LangChain or LlamaIndex tour, a no-code chat-with-PDFs path, or a course that assumes no programming. Someone who has never used a terminal will struggle.
You need a computer that can run Docker. Section 3 installs Git, Docker, and Compose. You also need an OpenAI account with billing on and a spend limit, because from section 5 each stored chunk and each question is a paid call.
Why this course
A lot of RAG courses go wide, through a framework or a hosted store. This one stays on one readable path: FastAPI, Scrapy, Postgres, and pgvector, run with Docker Compose on your machine, on pages you choose. No orchestration framework sits between you and the code.
You will see chunking, embeddings, and metadata in Postgres, and section 6 maps reranking, hybrid retrieval, and a formal eval. Those later layers are named so you know they exist. They are not the lab. The course does not make you job-ready on its own. Take it when you want every file in a small RAG system to make sense before you add a framework.