- Table of Contents
- Course Overview
- Who is this course for?
- Course Breakdown: Week by Week
- Getting Started
- Working with the project
- Week 1: Your first durable pipeline
- Week 2: Three newsletters, flow control and answers with citations
- Week 3: Conditional freshness, temporal supersession and an MCP server
- Week 4: Structured claim extraction, Memgraph ontology and three-way RRF
- Week 5: An evaluation suite built from your system's failures
- Week 6: Bounded research agent, weekly digest and production deploy
- Our Sponsor
- Contributors
This isn't your typical "call an LLM and print the result" tutorial. Most tutorials stop at the happy path. This course is about everything around it, the layer that decides whether a system survives a real Tuesday: durable execution, retries that don't double-bill an API, idempotency, and evaluation built from real failures.
So instead of a demo, we're building a real product: The Substack Brain, a knowledge base that turns technical newsletters into something your AI tools can query. It reads the articles, keeps itself fresh, understands who said what, and answers with citations. All of it runs on Inngest, the durable orchestration engine that makes it survive real-world failures.
By the end of this course, you'll have a system capable of:
- π¬ Ingesting newsletters straight from their RSS feeds, safely, from an allowlist
- βοΈ Running every pipeline as durable Inngest steps that survive crashes, retries and rate limits
- π Searching with hybrid retrieval: BM25 and dense vectors fused into one ranking, inside Postgres
- π¬ Answering questions with citations you can click and verify
- β±οΈ Staying fresh with a poller that costs almost nothing when nothing has changed
- πΈοΈ Extracting who said what into a Memgraph knowledge graph
- π Plugging into Claude Code, Cursor and Codex through an MCP server
- π Measuring quality with evals built from your own failures, not vibes
- π€ Running a bounded research agent and a weekly digest, deployed for real
We start absurdly simple (one newsletter, five articles, one Postgres table) and add one hard problem every week. Weeks 1 to 6 are available now.
Excited? Let's get started!
|
Join The Neural Maze and learn to build AI Systems that actually work, from principles to production. Every Wednesday, directly to your inbox. Don't miss out! |
This course is for Software Engineers, ML Engineers, and AI Engineers who can already write the happy path (call an LLM, chunk some text, stand up a FastAPI endpoint) and want to understand what separates that from a system you can actually leave running.
Each week, you'll unlock a new chapter of the journey. We start absurdly simple (one newsletter, five articles, one Postgres table) and add exactly one hard problem per week. You'll get:
- π§Ύ A Substack article that walks through the concepts and code in detail
- π» A new batch of code pushed directly to this repo
- π₯ A video that explores the topic
Here's what the weeks look like π
| Week | π οΈ You'll build | π§Ύ Article | π» Code | π₯ Video |
|---|---|---|---|---|
1 |
βοΈ A durable RSS importer, triggered over plain HTTP, plus a first look at sparse and dense retrieval | Week 1 | Week 1 | Coming soon |
2 |
π Backfilling three newsletters with concurrency, throttling and priority, hybrid retrieval, a first LLM answer with citations | Week 2 | Week 2 | Coming soon |
3 |
π A conditional freshness poller, article edits that keep citation history, a failures dataset and an MCP server | Week 3 | Week 3 | Coming soon |
4 |
πΈοΈ Claim extraction into a Memgraph graph, quote-span guardrail, 3-way RRF fusion and kb_sources |
Week 4 | Week 4 | Coming soon |
5 |
π An evaluation suite built from your system's failures: open/axial coding, deterministic guardrails, TPR/TNR calibrated binary judges, and Inngest variant experiments | Week 5 | Week 5 | Coming soon |
6 |
π€ A bounded research agent, a weekly digest and a production deploy | Coming soon | Week 6 | Coming soon |
Before diving in, make sure you have:
- π³ Docker running
- π¦ uv installed
- π An OpenAI API key with a little credit (used for embeddings; the whole of week 1 costs a few cents)
- π (From week 2, optional) An Anthropic API key for the answers written by
POST /askandkb_ask. Without it, they return the retrieved passages only.
Then set up the project:
git clone https://github.com/neural-maze/substack-brain-course.git cd substack-brain-course cp .env.example .env # fill in OPENAI_API_KEY (ANTHROPIC_API_KEY is optional)
Each week builds on the previous one, so follow them in order!
| Tool | URL | For |
|---|---|---|
| Adminer | localhost:8081 |
Browse Postgres and watch rows land in articles, passages, and claims. |
| Inngest dev server | localhost:8288 |
Every function, run and step, with its timeline and retries. |
| Memgraph Lab | localhost:3000 |
Visual graph explorer for Cypher queries over :Publication, :Author, :Article, :Claim, and :Topic nodes. |
| Swagger UI | localhost:8000/docs |
Try every endpoint from the browser. |
make check # lint (ruff + mypy) and tests make stop # docker compose down (your data is kept) make db-clear # destructive: empties every table and Memgraph, keeps the schema make reset # destructive: docker compose down -v, drops all data make nuke # destructive: reset, plus kills a stray app process on the port
kb/: the pipeline (functions/for Inngest,agents/for hand-written agent steps,graph/for Memgraph ontology & Cypher,evals/for deterministic checks, binary LLM judges & TPR/TNR calibration,sources/for fetch/parse/chunk/embed/quote-validation,db/,retrieval/,schemas/,mcp/for the MCP server)evals/: failure taxonomy (taxonomy.yaml), human-labeled traces (labeled_traces.jsonl), and the retrieval variant benchmark (golden_benchmark.yaml)publications.yaml: the allowlist of feeds the pipeline may ingestalembic/: database migrationsinfra/docker-compose.yml: Postgres (pgvector), Adminer, Inngest dev server, Memgraph, Memgraph Labdocs/week-1.md,docs/week-2.md,docs/week-3.md,docs/week-4.md,docs/week-5.md,docs/week-6.md: the step-by-step guidesscripts/replay_backfill.py&scripts/calibrate_judges.py: replay verifier and TPR/TNR binary judge calibration CLItests/: the unit tests, which need no Docker or API keystests/integration/: tests that need the stack frommake startrunning (they are skipped otherwise)
Goal: Build a pipeline that survives being killed mid-task, and search what it ingested.
-
π Read the guide: Start with
docs/week-1.md. It explains what Inngest is, what each container does, and why the pipeline is split into seven steps. -
π Start the system:
make start
This starts Postgres, Adminer and the Inngest dev server with Docker Compose, runs the migrations, and launches the FastAPI app. It stays in the foreground, so use a second terminal for the rest.
-
π₯ Ingest a newsletter with plain HTTP:
curl -X POST localhost:8000/publications \ -H "Content-Type: application/json" \ -d '{"feed_url": "https://theneuralmaze.com/feed"}' # β {"event_id": "...", "trace_url": "http://localhost:8288/event/...", "status": "queued"} curl localhost:8000/jobs/<event_id> # β {"status": "completed", "articles_done": 5, "articles_total": 5, ...}
-
π Search it:
curl "localhost:8000/search?q=agents&mode=sparse" # BM25 (Postgres full-text) curl "localhost:8000/search?q=agents&mode=dense" # pgvector cosine similarity
Try the same query in both modes and compare the results. They won't agree.
-
π₯ Kill it and watch it resume: Press Ctrl+C while the
embedstep is running, runmake startagain, and open the run in the Inngest UI. Onlyembedruns again. The guide walks you through it. -
π§ͺ Run the tests:
make testThe tests live in
tests/test_basics.py. They need no Docker, database or API key and run in about a second. They cover the small functions the pipeline is built from: URL cleanup, the allowlist, chunking and RSS parsing.
Goal: Ingest three newsletters at once without hammering their servers or your OpenAI quota, let urgent articles skip the queue, and answer questions with hybrid retrieval and inline citations.
-
π Read the guide:
docs/week-2.mdexplains the backfill, the three flow-control knobs oningest-article(concurrency, throttle, priority), Reciprocal Rank Fusion and the context snapshots. -
π Add your Anthropic key:
POST /askusesANTHROPIC_API_KEYto write the answer. Without it,/askstill runs retrieval and returns the passages. -
π Start the system with
make start. It applies this week's migration (thesnapshotstable) automatically. -
π₯ Backfill three newsletters at once:
curl -X POST localhost:8000/publications -H "Content-Type: application/json" -d '{"feed_url": "https://theneuralmaze.com/feed"}' curl -X POST localhost:8000/publications -H "Content-Type: application/json" -d '{"feed_url": "https://www.decodingai.com/feed"}' curl -X POST localhost:8000/publications -H "Content-Type: application/json" -d '{"feed_url": "https://magazine.sebastianraschka.com/feed"}'
-
β© Jump the queue while the backfills run:
curl -X POST localhost:8000/articles -H "Content-Type: application/json" -d '{"url": "<a Neural Maze post URL>"}'
-
β Ask a question:
curl -X POST localhost:8000/ask -H "Content-Type: application/json" \ -d '{"question": "How do durable execution engines handle failure recovery?"}'
-
π Prove replays are free:
uv run python scripts/replay_backfill.py --verify, then--all, then--verifyagain. Every count stays the same, including the number of embedding calls.
Goal: Keep the knowledge base fresh without hammering the feeds, handle article edits without breaking old citations, record every failure for the evals, and let Claude Code and Cursor use the knowledge base through MCP.
-
π Read the guide:
docs/week-3.mdexplains the asymmetry principle behind the MCP tools, conditional polling withETagandLast-Modified, temporal supersession withvalid_to, and thefailurestable. -
π Start the system with
make start. It applies this week's migration (thefailurestable and a partial unique index onpassages) automatically. -
π Poll the feeds twice:
curl -X POST localhost:8288/e/local -H "Content-Type: application/json" -d '{"name": "kb/feed.poll", "data": {}}'
The first poll gets
200 OKand saves the validators tocursors. The second gets304 Not Modifiedand finishes in milliseconds without downloading or parsing any feed. -
βοΈ Simulate an article edit: Ingest an article, change its
content_hashin Postgres, and submit it again. The old passages getvalid_toset, the new ones are inserted, and search only returns the current version. The guide has the exact commands. -
π₯ Record a failure:
curl -X POST localhost:8288/e/local -H "Content-Type: application/json" \ -d '{"name": "inngest/function.failed", "data": {"error": {"message": "Simulated failure"}, "function_id": "ingest-article"}}'
handle-function-failedsaves it to thefailurestable, ready for the week 5 evals. -
π Connect the MCP server: Try it with
npx @modelcontextprotocol/inspector uv run kb-mcp, then add it to Claude Code or Cursor:{ "mcpServers": { "substack-brain": { "command": "uv", "args": ["--directory", "/absolute/path/to/substack-brain-course", "run", "kb-mcp"] } } }Reads (
kb_search,kb_ask, ...) answer in under a second. Writes (kb_add_publication,kb_backfill,kb_sync) send an Inngest event and return a trace URL right away. -
π§ͺ Run the tests with
make check. The new tests are intests/test_week3.py.
Goal: Design a strict 5-node, 5-edge knowledge graph ontology in Memgraph, verify every extracted claim against a verbatim quote span in Python before persistence, fuse 2-hop graph traversal with BM25 and pgvector via three-way RRF, and expose full claim/passage lineage through kb_sources.
-
π Read the guide:
docs/week-4.mdwalks through Prerequisite Zero (locking the ontology before code), deterministic topic canonicalization, the hand-written agent layer (kb/agents/), the verbatim quote guardrail, and three-way Reciprocal Rank Fusion. -
π Start the system with
make start. It launches Memgraph (localhost:7687) and Memgraph Lab (localhost:3000), and applies the Week 4 migration (claimstable). -
π₯ Ingest or update an article to trigger
extract-claims:curl -X POST localhost:8000/articles -H "Content-Type: application/json" \ -d '{"url": "https://www.theneuralmaze.com/p/the-complete-guide-to-event-driven"}'
Watch
extract-claimsrun in the Inngest UI (localhost:8288) and emitkb/claims.extracted. -
πΈοΈ Explore the ontology in Memgraph Lab (
http://localhost:3000):MATCH (a1:Author)<-[:WRITTEN_BY]-(art1:Article)-[:ASSERTS]->(c1:Claim)-[:ABOUT]->(t:Topic)<-[:ABOUT]-(c2:Claim)<-[:ASSERTS]-(art2:Article)-[:WRITTEN_BY]->(a2:Author) WHERE c1.valid_to IS NULL AND c2.valid_to IS NULL AND a1.slug <> a2.slug RETURN a1, art1, c1, t, c2, art2, a2 LIMIT 25;
-
β Ask a cross-publication question and inspect provenance with
kb_sources:curl -X POST localhost:8000/ask -H "Content-Type: application/json" \ -d '{"question": "How should engineers design RAG retrieval and agent orchestration in production?"}' curl localhost:8000/sources/<cited_claim_or_passage_id>
-
π§ͺ Run the tests with
make check. The Week 4 unit tests live intests/unit/test_ontology.py,tests/unit/test_quote_span.py,tests/unit/test_rrf_three_way.py, andtests/test_week4.py; integration tests live intests/integration/test_enrich_memgraph.pyandtests/integration/test_graph_fusion.py.
Goal: Replace generic "helpfulness" scores with Hamel Husain's bottom-up error analysis (Open Coding PASS/FAIL LLM judges, calibrate judge alignment with True Positive Rate (TPR) and True Negative Rate (TNR) evaluate-answer) and multi-variant retrieval benchmarks (run-eval-suite) as durable Inngest steps.
-
π Read the guide:
docs/week-5.mdwalks through open & axial coding oversnapshotsandfailures, the 6-category failure taxonomy (FM-1βFM-6), deterministic checks vs. binary LLM judges, TPR/TNR calibration, and durable Inngest evaluation workflows. -
π Start the system with
make start. It applies the Week 5 migration (eval_resultsandeval_runstables). -
π― Calibrate the binary judges:
uv run python scripts/calibrate_judges.py --mode offline # Or against live Anthropic: uv run python scripts/calibrate_judges.py --mode live -
π¬ Ask a question and watch
evaluate-answerpopulatesnapshots.confidence:curl -X POST localhost:8000/ask -H "Content-Type: application/json" \ -d '{"question": "How do durable execution engines handle failure recovery compared to traditional queues?"}'
-
π Run the multi-variant evaluation suite (
sparsevsdensevs2-way RRFvs3-way RRF):curl -X POST localhost:8000/evals/run -H "Content-Type: application/json" \ -d '{"suite_name": "golden_v1", "include_failures_table": true}' curl localhost:8000/evals/latest
-
π§ͺ Run the tests with
make check. The Week 5 unit tests live intests/unit/test_deterministic_evals.py,tests/unit/test_judge_calibration.py, andtests/test_week5.py; integration tests live intests/integration/test_evals_pipeline.py.
Goal: Run a multi-hop research agent (run-research-agent) bounded by hard iteration, USD cost, and convergence caps, evaluate its reports with Week 5's deterministic and binary judges, publish an automated weekly newsletter digest (generate-weekly-digest), and package the stack for production deployment.
-
π Read the guide:
docs/week-6.mdwalks through the 3 research agent roles (QueryPlannerAgent,CoverageCriticAgent,ResearchSynthesizerAgent), the 3 termination guardrails (max_iterations,max_usd, and zero-new-passages convergence), the weekly digest cron workflow, the 3 new MCP tools (kb_research,kb_research_result,kb_weekly_digest), and the productionDockerfile+infra/docker-compose.prod.yml. -
π Start the system with
make start. It applies the Week 6 migration (research_runsanddigeststables). -
π€ Launch a bounded research agent run:
curl -X POST localhost:8000/research -H "Content-Type: application/json" \ -d '{"question": "How do durable execution engines, hybrid RRF retrieval, and knowledge graphs work together in production AI systems?", "max_iterations": 3, "max_usd": 0.25}' curl localhost:8000/research/<research_id>
-
π° Trigger and read the weekly digest:
curl -X POST localhost:8000/digests/run -H "Content-Type: application/json" \ -d '{"lookback_days": 7}' curl localhost:8000/digests/latest
-
π§ͺ Run the tests with
make check. The Week 6 unit tests live intests/unit/test_research_agent.pyandtests/test_week6.py.
|
Inngest is the durable execution engine behind this course. Every step's result is recorded, so a crashed run resumes instead of restarting. This course is made possible by their support. π |
![]() |
Miguel Otero Pedrido | Senior ML / AI Engineer Founder of The Neural Maze. Rick and Morty fan. YouTube The Neural Maze Newsletter |
![]() |
Antonio Zarauz Moreno | Cognitive-AI R&D / AI Engineer Doesn't build AI wrappers β builds the infrastructure that makes them profitable, from PoC to thousands of concurrent users. |



