RnR: reviews and ratings, an AI capstone product¶
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 rnr && python 00_generate_data.py
Lab files and data: rnr/ on GitHub. In VS Code, open the repo folder and use Terminal > Run Task > Run this lab.
A small but real product for a B2B building-materials marketplace (TMT bars, cement, pipes, sheets): buyers post reviews, AI moderates them, extracts what buyers talk about, scores products, summarises them and answers questions from them. It puts the earlier topics to work and adds what production needs: guardrails, evals, tracing and cost.
Read the guides alongside the labs: Learn guardrails (labs 02-04) · Learn evals and LLM-as-judge (labs 05, 13) · Learn to operate: tracing and cost (labs 06, 09, 11). Questions and answers are in FAQ.md, in lab order; the key decisions are below. Before you start: prompting (structured output, prompt versions); optional lab 14 also uses rag. No agents needed. After it, you can: ship a feature with guardrails, evals, tracing and a cost per request. Done with the labs? Try the three exercises and the build-it-yourself task in PRACTICE.md.
The main path is 9 labs and one story: take one AI feature, review moderation, to production. Guardrails, fail-closed handling, golden-set evals, one trace per review, a cost meter, a gateway and a calibrated LLM judge. About 15 minutes of model time in all. Six more labs are optional: they add new AI features to the same product (aspects and scores, a thinking cascade, grounded summaries, "Ask the reviews") for when your work needs them. Every lab calls the same code the product runs.
What you're building¶
What is it? An API, a database, a background worker and an admin UI, with the AI features built in lab by lab.
Unlike the other topics, the labs here call the same code the product runs (ai/, api/), so what you learn is
what you would ship.
Why a product and not more labs? Evals, guardrails and cost only make sense in context: a threshold depends on what a wrong reject costs the business, a guardrail on what can reach a buyer, a cost on how many reviews arrive per day. A product gives every number a reason.
How it works:
buyer posts review ──► API: validate, store PENDING, queue "moderate", reply 202
│
worker (background) ◄────┘ claims job ──► rules ──► model (ai/llm.py) ──► APPROVED | REJECTED | HELD
│
llm_calls: tokens, latency, prompt version
evals ──► compare decisions with review_labels (the golden truth) ──► precision, recall, cost
Two more views: review-lifecycle.svg (how a review moves PENDING → APPROVED, HELD or REJECTED, and who decides each step) and data-model.svg (the tables in four groups).
The labs¶
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.
Main path: one feature to production (9 labs)¶
Do these in order. Each one reads only the code its docstring names under Read first; the Skip line says what belongs to the optional labs.
| Step | Lab | Track | What you learn | Time |
|---|---|---|---|---|
| Data | 00_generate_data.py |
Core | Spec-first synthetic data with planted answers; builds the database | ~2 s |
| Guardrails | 02_llm_moderation.py |
Core | One structured verdict per review, then code checks what it said | ~15-50 s |
03_injection_and_pii.py |
Before you ship | Six injection attacks against three defences; PII masked before the model | ~1-4 min | |
04_fail_closed.py |
Before you ship | A broken model through the real worker: every case ends HELD (no model) | seconds | |
| Evals | 05_golden_set_eval.py |
Core | Score a prompt version on 50 labelled reviews and 20 hard cases; compare versions | ~2-3 min |
| Tracing | 06_traces.py |
Core | Six reviews as waterfalls: one trace across API, queue and worker; p50/p95 per step | ~10-50 s |
| Cost | 09_cost_meter.py |
Core | Every call priced (API and self-host), ₹ per 1,000 reviews, build vs buy (no model) | seconds |
| Gateway | 11_gateway.py |
Go further | The layer in front of the model: a response cache, budgets, rate limits, retries, a fallback model; the same with LiteLLM | ~1-2 min |
| Judge | 13_judge_calibration.py |
Go further | Measure an LLM judge on 40 claims with known answers before you trust its scores | ~3-5 min |
More: new features on the same product (optional)¶
Pick the ones your work needs; each stands on its own after the main path.
| Feature | Lab | What you learn | Time |
|---|---|---|---|
| Rules | 01_rules_first.py |
Rules decide what they can (no model); the model only for meaning | seconds |
| Aspects | 07_aspect_extraction.py |
The model extracts aspect, pos/neg and a quote; code checks the quote | ~40 s |
08_scoring_math.py |
The LLM extracts, code calculates: Bayesian score, Wilson ranking (no model) | seconds | |
| Thinking | 10_thinking_and_cascade.py |
Thinking on vs off, then think only when unsure (the cascade) | ~7 min |
| Summary | 12_sku_summary.py |
Grounded vs stuff vs map-reduce summaries, checked in code; then lab 13 --label / --strategies judge them |
~7-8 min |
| Q&A | 14_ask_the_reviews.py |
Counting questions to code, open ones to cited RAG; refusals (uses rag) | ~30 s |
Code comments say "phase N": the order the product was built in. Phase 1 guardrails (labs 01-04), 2 evals (05), 3 tracing (06), 4 aspects (07-08), 5 cost (09-11), 6 summary, judge and Q&A (12-14).
Each lab ends with an Expected output (from a real qwen3:8b run) and What can go wrong. Labs marked "no model"
run in seconds; most others take a few minutes on a 16 GB Mac. --fake runs any lab with a stand-in model.
The synthetic marketplace¶
33 SKUs in 6 categories, 15 sellers, 145 buyers, 1,100 orders (May to October 2026), deliveries, returns and 500 reviews: English and Hinglish, genuine and blunt, plus abuse, off-topic, PII, spam, prompt injection and fakes. Three stories are planted so evals have a known right answer:
| Story | What happened | Where it shows |
|---|---|---|
| Late seller | S03's deliveries go bad in October (48% more than 3 days late) | deliveries, delivery complaints |
| Defect batch | TMT-550D-16 batch B12 cracks in the bend test (19 of 36 returned) | returns, bendability complaints |
| Fake burst | 25 near-identical, unverified 5★ reviews on PVC-PIPE-110 in 3 days | raw rating 4.7 vs published |
Tip: on the Sellers page S03 still shows 83% on time. The average hides the October drop; finding it is a good exercise.
Setup¶
Install steps for all topics are in ../INSTALL.md. From the ai-learning folder:
source .venv/bin/activate # the one venv at ai-learning/ (see ../INSTALL.md section 4)
uv pip install -r requirements.lock # all topics, the tested versions
ollama pull nomic-embed-text # embeddings for optional lab 14
cd rnr && pytest -q
python 00_generate_data.py # builds data/rnr.db in about a second (templates)
uvicorn api.main:app --reload # open http://127.0.0.1:8000
python -m worker.run --backlog 50 # in a second terminal: moderate the 50 oldest reviews
Run everything from this folder. Settings:
| Setting | Default | What it does |
|---|---|---|
RNR_DB |
data/rnr.db |
Database file; --llm data goes to another one, e.g. data/rnr_llm.db |
LLM_MODEL |
ollama/qwen3:8b |
The model for every call (repo-wide, set in ../.env; see providers) |
EMBED_MODEL |
ollama/nomic-embed-text |
Embeddings for Ask the reviews; each model gets its own Chroma folder |
RNR_CACHE |
1 |
The worker reuses stored answers for identical requests |
RNR_ESCALATE |
1 |
A thinking second pass only for held or ABUSIVE answers |
RNR_TRACE_CONTENT |
1 |
Keep masked prompts and answers in spans (0 drops them) |
RNR_ASK_MAX_DISTANCE |
0.40 |
The "anything relevant?" gate for Ask the reviews |
Optional: python 00_generate_data.py --llm lets qwen3:8b write the genuine reviews (10 to 40 minutes the first time,
under a minute after: the text is cached in data/cache/). The worker also enriches approved reviews and writes summaries:
python -m worker.run --enrich 0 --once and --summarize 0 --once catch up on older reviews. Lab 11's --litellm
needs uv pip install -e '.[hosted]' from the ai-learning folder.
Key files¶
| File | What it holds | Read? |
|---|---|---|
ai/llm.py |
generate() and embed(): the product's door to the model, on top of the repo's door; logs every call, cache, thinking budget |
Skim |
ai/guardrails.py |
PII redaction, spam and injection rules, wrap_untrusted(), near-duplicate similarity |
Read |
ai/moderation.py, ai/mod_prompts.py |
The cascade (rules_check(), llm_check(), moderate()), escalation, safety nets; the prompt versions |
Read |
ai/aspects.py, ai/scoring.py |
Aspect extraction with quote checks; Bayesian score and Wilson ranking (no model) | Optional labs |
ai/cost.py, ai/rate_card.json, ai/gateway.py |
The meter, the prices (dated assumptions), budgets and fallbacks | Read |
ai/judge.py |
The LLM judge (lab 13) | Read |
ai/summary.py (+ summary_facts, summary_prompts, summary_checks), ai/ask.py |
"What buyers say", "Ask the reviews" | Optional labs |
evals/ |
One module per eval (moderation_eval, aspect_eval, summary_eval, judge_eval, cost_eval), the cost matrix (costs.py), hard cases, a stand-in model (fakes.py) |
Skim |
obs/tracing.py, obs/report.py |
Hand-rolled, OpenTelemetry-shaped spans; reading traces back | Read |
worker/ |
The job queue in a table and the handlers: moderate, enrich, summarize | Skim |
api/, ui/ |
JSON API under /api, HTMX pages (Products, SKU, Moderation, Sellers, Ops, traces); docs at /docs |
Skip |
data/, db/ |
The synthetic world, review specs and text, the schema | Skip |
tests/ |
Model-free tests (pytest -q) |
Skip |
Each lab's docstring names the functions to Read first and, in the main path, what to Skip.
Key decisions¶
- Data: synthetic, generated from specs with three planted stories, so every eval has a known answer. Templates by default;
--llmwrites natural genuine reviews. - Stack: FastAPI + HTMX + SQLite (a jobs table, no message broker) and one door to the model; Chroma for "Ask the reviews".
- Moderation: rules only for spam, known injection phrases and fake bursts; PII masked before the model; unsure, invalid or failed answers are HELD. Contact-only "spam" and the model's ABUSIVE calls are held for a human (safety nets), and evals report the model's own score next to the product's.
mod-v3is active. - Aspects and score: a fixed aspect list per category plus "other"; a Bayesian score toward the category mean; bars ranked by the Wilson lower bound and hidden under 3 mentions.
- Cost: one model, smarter routing: rules, cache, a quick pass, then a thinking pass only for held or ABUSIVE answers (about 6% of reviews). Prices are dated assumptions in
ai/rate_card.json. - Summary, judge and Q&A: facts from code, words from the model. Code checks every number, count pair and citation in
sum-v3and guarantees the top complaint;judge-v2judges only what code can't. Counting questions go to SQL, open ones to cited RAG over one SKU (distance gate 0.40).
Not built, on purpose: supplier insights (a seller scorecard and a "why did this rating drop?" agent) and complaint triage with seller reply drafts. Agents and multi-agent workflows have their own topics, so both became exercises in PRACTICE.md; the late-seller story (S03 in October) is planted and waiting.
Rules of thumb¶
- Decide the label before you write the data. Plant problems on purpose: an eval without a known answer measures nothing.
- Answer the user fast, do the AI work in the background: store, queue, reply 202, then moderate.
- One door to the model. If calls bypass it, you lose cost, latency and prompt-version tracking.
- Rules for patterns, the model for meaning. A keyword list for abuse rejects honest angry buyers.
- Mask PII before the model sees it. User text is data: fence it in tags and say so.
- The schema checks the shape; your code checks the meaning. Fail closed: unsure, invalid or broken means HELD.
- A clear business rule goes in code, not only in the prompt.
- Score before and after every prompt change, on the same reviews. Put "honest rejected" next to "bad published".
- Price the mistakes. The best policy is the cheapest under costs the business agreed, not the most accurate one.
- A safety net hides the model's mistakes from the headline: report the model's own score next to the product's.
- Grow a hard-case set from every failure, and never copy those cases into the prompt.
- One trace per unit of work, one span per step, and carry the trace id across every hop.
- Spans hold what the model saw (masked), never raw PII. Tracing must never fail the work.
- The LLM extracts, code calculates. Every extracted fact carries a quote that code checks.
- Meter at the one door; find the big meter first; put ₹ per 1,000 next to the eval score.
- Think only when it changes the answer: a cheap pass for everyone, a reasoning pass for the few.
- Cache only deterministic calls, and never in evals.
- Facts from code, words from the model. Check numbers, ids and quotes in code; judge only what code can't.
- Calibrate the judge before you trust it, and report kappa.
- Route counting questions to code; filter by SKU in the index, not the prompt; refuse before and after the model.
- Faithful is not complete: what must be in the output, code guarantees.
Tests¶
pytest -q (about 170 tests, no model needed) builds a small database per test and checks the planted stories and
labels, the job queue and worker, the API and every page, the guardrails and the cascade with a fake model, failing
closed, the eval tools, tracing across the queue with no raw PII in spans, aspect checks and scoring math, the cost
meter, cache, escalation and gateway, and the summary checks, judge, router, index and refusals. How qwen3:8b
behaves is measured by the labs.