Module 07: Projects
Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.
Three projects: one starter and two stretches (the production service is optional). All three build the same docs_qa package the eleven lessons grow — a Q&A system over the fictional Acme corpus (handbook, help centre, tickets, contracts) that Modules 05 and 06 prepared — and all three run keylessly on the module's fakes: FakeLLM in docs_qa/llm.py, the toy DenseRetriever/Bm25Retriever/HybridRetriever from lesson 06.10, and the deterministic FakeJudge in docs_qa/eval/. Hosted providers (OpenAI, Anthropic, Gemini, OpenRouter) are the stretch goal for each project once you have a key: the lessons' openai_llm()/anthropic_llm()/gemini_llm()/openrouter_llm() adapters drop into the same LLM seam, so the code doesn't change — only the wiring does.
What the fakes can and cannot tell you. FakeLLM returns canned replies keyed on prompt substrings, so it exercises your plumbing — retrieval, planning, context assembly, citation verification, sessions, eval scoring — but never its judgement. The toy embedder only "understands" the eval qids and text aliases in corpus.py; free-text questions get a seeded random vector, so the BM25 leg of a hybrid retriever does the real work (07.1, 3.1). Expected outputs below are the deterministic ones the lessons show; anything model-dependent is labelled illustrative.
First time? Do lesson 07.1's Setup once:
uv init docs-qa --bare --python 3.13 && cd docs-qa
uv add openai anthropic google-genai pydantic python-dotenvThese install the newest release of each package; the versions the samples were checked against (as of November 2026) are in 07.1's Setup, and tenacity, fastapi, uvicorn and httpx for the third project are in 07.11's Setup. Then copy corpus.py and retrievers.py — printed in full in lesson 06.10, Part 4 — into the project root. They are top-level modules, not package members: corpus.py defines Chunk, CHUNKS, BY_ID, QUERY_TOPICS and query_vector(); retrievers.py defines Hit, the Retriever protocol, DenseRetriever, Bm25Retriever, HybridRetriever, rrf() and the cosine helpers. Every docs_qa file imports them as from corpus import ... / from retrievers import ..., so keep them at the root. The .env file holds provider keys if you wire a real model; the fakes need none.
The package grows lesson by lesson; 07.11's appendix is the consolidated file listing. Where a name differs between two lessons' files (each lesson's code was written to run on its own), the appendix's interfaces are the contract — adapt imports, keep the semantics.
Starter: Docs Q&A bot with verified citations#
Goal: Assemble the docs_qa package end to end — naive pipeline, retrieval configs, query understanding, grounded generation with abstention, and verified citations — into a CLI that answers questions over the Acme corpus with sources a user can check.
Prerequisites: lessons 07.1 to 07.5 (read them alongside the steps; each step names the section to copy from) and the Module 05/06 corpus files. No key needed.
What you'll practise:
- The pipeline contracts and seams:
Question/Answer/Tracetypes, theRetrieverprotocol, theLLMcallable andwith_catalogprovenance (lesson 07.1, 3.2, 4.2, 4.4) - The naive pipeline and its ten-question smoke loop, including reading retrieval misses vs generation misses (07.1, 3.3, 3.4)
- Named retrieval configurations and evidence-based choice (lesson 07.2, 1.2, 1.4)
- The
QueryPlancontract andplan_querywith a fake model (lesson 07.3, 2.2, Part 11) - Grounded generation: context assembly, the grounding prompt, sufficiency gates and abstention (lesson 07.4, Part 2, Part 3, Part 4)
- Citation verification and rendering (lesson 07.5, Part 4,
cited_answer_from_grounded)
Setup: the project and packages above, plus corpus.py/retrievers.py at the project root. No keys needed. Add uv add pytest for step 7.
Steps:
- Create the package skeleton.
mkdir docs_qa && touch docs_qa/__init__.py. Copytypes.py,llm.pyandrag.pyfrom 07.1, 3.2 and 4.4, andbudget.py/oracle.pyif you want the cost calculator and oracle test (07.1, 5.2, 7.2). Copysmoke.pyfrom 07.1, 3.3 to the project root. - Run the naive pipeline.
uv run python smoke.py. Read the ten rows the way 07.1, 3.4 teaches: which rows are retrieval misses, which are generation misses, and why Q10's abstention is a success (thetenant="acme"filter hid the initech contracts). Write down the failure each row maps to. - Add retrieval configs. Copy
docs_qa/retrieval.pyfrom 07.2 (the complete file at the end of the lesson). Build two retrievers over the toy corpus —build_retriever(PRESETS["dense"], retrievers={"dense": DenseRetriever(CHUNKS)})and the same withPRESETS["hybrid"]and{"dense": ..., "lexical": Bm25Retriever(CHUNKS)}— and compare their top-5 hits on five smoke questions. Note thatHit.scoreis not comparable across retrievers; compare which chunks come back, not the numbers. - Add query understanding. Copy
docs_qa/query.pyfrom 07.3, Part 11. It needsdocs_qa.llm'sLLM/Message/FakeLLM, which you already have. Run itsScriptedLLMdemo (uv run python -m docs_qa.query) and inspect aQueryPlan:original,cleaned,intent,route,rewrites,filters,techniques,degraded. Then callplan_query("and for contractors?", llm)— the fragment retrieves badly alone; that is the lesson's whole point. - Wire the plan into retrieval. In your
ask.py(below), turn the plan into search calls:plan.retrieval_queriesgives the query strings,filters_for_search(plan.filters)gives the safe filter dict (07.3), andplan.routetells you whether to retrieve, clarify or skip. Mergefilters_for_searchoutput under any mandatory filters — never post-filter. - Add grounded generation. Copy
docs_qa/generate.pyfrom 07.4, Part 10. Itsllmparameter isLLMFn = Callable[[list[dict[str,str]]], str]— the same shape asdocs_qa.llm.LLM, so yourFakeLLMor provider adapter plugs straight in. Callgenerate_answer(plan.original, hits, llm, budget_tokens=3000); readGenerationResult:answer(GroundedAnswerwithstatus,answer,evidence,missing),abstain_reason,sufficiency,model_calls. Check that an out-of-corpus question now setsstatus="abstained"— the naive pipeline only produced the string. - Add verified citations. Copy
docs_qa/cite.py— the full file is printed at the end of 07.5, after the Part 4 excerpts. Convert the generated answer withcited_answer_from_grounded(gen.answer, passage_ids)— pass theGroundedAnswerinside theGenerationResult, not the result itself — wherepassage_idsis the ordered list of passage ids you sent (the chunk ids, in context order), then runverify_citations(cited, chunks={h.id: h.text for h in hits}, known_chunk_ids={h.id for h in hits}, n_sources=len(hits))andcitation_precision(checks)/claim_coverage(cited). Buildsources(chunk_id -> SourceRef) from the hits' metadata and render withrender_markdown(cited, sources). A marker pointing outside1..n_sources, or a quote not found in its chunk, must fail loudly — that is the point of the verifier. - Compose
ask.py. Write the CLI that ties it together:
# ask.py — the starter project's entry point. Run: uv run python ask.py "question"
import sys
from corpus import BY_ID, CHUNKS
from retrievers import Bm25Retriever, DenseRetriever, HybridRetriever
from docs_qa.llm import FakeLLM
from docs_qa.rag import with_catalog
from docs_qa.query import filters_for_search, plan_query
from docs_qa.retrieval import PRESETS, build_retriever
from docs_qa.generate import generate_answer
from docs_qa.cite import (SourceRef, cited_answer_from_grounded, render_markdown,
verify_citations)
TITLES = {"handbook": "Employee Handbook", "help-centre": "Help Centre",
"tickets": "Support Tickets", "contracts": "Contracts"}
llm = FakeLLM({ ... }) # reuse smoke.py's canned replies, keyed on question phrases
# with_catalog (07.1) adds doc_id/section to each hit so sources can show titles
retriever = with_catalog(
build_retriever(
PRESETS["hybrid"],
retrievers={"dense": DenseRetriever(CHUNKS), "lexical": Bm25Retriever(CHUNKS)}),
BY_ID, TITLES)
def ask(question: str) -> None:
plan = plan_query(question, llm)
if plan.route.name in ("CLARIFY", "SKIP_RETRIEVAL") or not plan.retrieval_queries:
print(plan.clarification or "(no retrieval needed)")
return
hits = retriever.search(plan.primary_query, k=6,
filters=filters_for_search(plan.filters))
gen = generate_answer(plan.original, hits, llm)
if gen.answer is None: # defensive: generate_answer always sets it
print("(no answer produced)")
return
if gen.answer.status == "abstained": # the gates said no: do not render an empty answer
print("I don't have that information in the available documents.")
print(f"[status=abstained missing={gen.answer.missing} "
f"reason={gen.abstain_reason or 'model'}]")
return
passage_ids = [h.id for h in gen.context.kept] if gen.context else [h.id for h in hits]
cited = cited_answer_from_grounded(gen.answer, passage_ids) # the GroundedAnswer, not the GenerationResult
chunks = {h.id: h.text for h in hits}
checks = verify_citations(cited, chunks, set(chunks), n_sources=len(passage_ids))
bad = [c for c in checks if not c.ok]
print(render_markdown(cited, sources_from_hits(hits, TITLES)))
print(f"[status={gen.answer.status} "
f"citation checks: {len(checks) - len(bad)}/{len(checks)} ok]")ask.py also needs the sources_from_hits helper, which maps each hit's metadata to a SourceRef (07.5, 2.3). Put it above ask() (SourceRef is already in the imports):
def sources_from_hits(hits, titles: dict[str, str]) -> dict[str, SourceRef]:
"""chunk_id -> SourceRef, built from each hit's metadata."""
out: dict[str, SourceRef] = {}
for h in hits:
m = h.metadata or {}
doc_id = m.get("doc_id", "")
section = m.get("section", "")
out[h.id] = SourceRef(
chunk_id=h.id,
doc_id=doc_id,
title=m.get("title") or titles.get(doc_id, doc_id or "Untitled"),
section_path=[p for p in section.split("/") if p],
snippet=h.text[:200],
)
return outfilters_for_search comes from docs_qa.query, as imported above.
9. Run the smoke set through ask.py. Ask the ten QUESTIONS from smoke.py plus two follow-ups ("and for contractors?", "what about sick leave?"). Compare with step 2: abstentions should now be flagged, citations verified, and the follow-up should retrieve something sensible once plan_query has run — or fail informatively if the fake's canned replies don't cover the rewritten query (that is a FakeLLM limitation, not a pipeline bug; note it in your write-up).
10. Test without a model. Write test_docs_qa.py with pytest: (a) plan_query on a greeting returns route == SKIP_RETRIEVAL with degraded == False; (b) verify_citations fails a CitedAnswer whose marker exceeds n_sources; (c) generate_answer on an empty hit list returns abstain_reason == "nothing_retrieved". All three run on fakes — no key, no network.
Verify it, and what you should see:
uv run python smoke.py # the 07.1 demo: 10 rows, deterministic retrieved ids
uv run python -m docs_qa.query # the 07.3 ScriptedLLM demo: QueryPlans, real output
uv run python -m docs_qa.retrieval # the 07.2 demo: configs, routing, triggers
uv run pytest -q test_docs_qa.py # 3 passed
uv run python ask.py "how much vacation do I get?"The ask.py output shape (the answer text comes from your FakeLLM replies; the structure is what the code prints):
Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year [2].
**Sources**
[2] Employee Handbook — leave / vacation
> Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.
[status=answered citation checks: 6/6 ok]The marker is the passage's position in the context you sent, so it is [2] here (the vacation chunk ranked second) and not always [1]; each citation runs six checks (marker in text, marker in range, claim span, marker inside claim, chunk known, quote found), which is why the count is a multiple of six. For an out-of-corpus question the sufficiency gate abstains and the abstained branch prints:
I don't have that information in the available documents.
[status=abstained missing=['the wifi password'] reason=insufficient_context]What to notice: status is now a real field (answered, partial, abstained) set by the sufficiency gate and the answer contract, not a string match; citations are verified — a marker the model invents fails marker_in_range or quote_found rather than displaying; and every stage you added is a seam the next project reuses unchanged.
Done when:
smoke.py,python -m docs_qa.query,python -m docs_qa.retrievalandask.pyall run with no key and no network.ask.pyanswers at least six of the ten smoke questions with verified citations, abstains (flagged, not just worded) on the out-of-corpus ones, and its citation check counts are printed per answer (six checks per citation).test_docs_qa.pypasses, proving the abstention and citation-verification paths without a model.- Your notes map each remaining smoke failure to a lesson: which stage owns the fix (query understanding? retrieval depth? grounding? citations?).
Stretch ideas: Swap FakeLLM for openai_llm()/anthropic_llm()/gemini_llm()/openrouter_llm() with keys in .env and re-run ask.py — same code, real answers (07.1, 4.3). Add streaming by wrapping the LLM call per 03.3 and 07.4, 8.3. Calibrate the abstain threshold on a labelled answerable/unanswerable set (07.4, 4.5). Run the 06.10 harness against each PRESETS config and keep the winner (07.2, 1.4). Try a provider-native citation feature (07.5, Part 3) and compare it against your verified [n] markers.
Common problems:
ModuleNotFoundError: corpus/retrievers— they are top-level files at the project root, not insidedocs_qa/; run scripts from the project root (uv run python ask.py), not from inside the package.ImportErrorinsidedocs_qafiles — the lessons importHitfromretrievers(top-level),LLM/Message/FakeLLMfromdocs_qa.llm, andQueryPlantypes fromdocs_qa.query. Check each file's own import block; the appendix's naming note applies.FakeLLMreturns""for everything — its canned keys must be substrings of the joined prompt, which now includes the assembled context. Use distinctive question phrases as keys (the smoke.py comment explains why short keys like "per diem" match the context, not the ask).plan_queryreturnsdegraded=True— aFakeLLMreply the classifier can't parse. Checkplan.techniquesand the fake's responses; the deterministic fallback still produces a usable plan, which is the designed behaviour.- Citations all fail
quote_found—evidence_from_hitdeliberately leavesquoteempty so verification fails closed; fill quotes from the model's structuredevidenceor your own extraction before trusting precision numbers (07.5). - Retrieval returns nothing for a follow-up — expected: the toy retriever embeds query text, and "and for contractors?" has no eval alias. This is what conversational rewriting in the stretch project fixes.
Stretch: Multi-source assistant with conversation memory and an eval gate#
Goal: Extend the starter into an assistant that routes questions across several indexes (the four Acme sources plus a small orders table), understands follow-ups across a conversation, and proves every change with a labelled eval suite and a regression gate.
Prerequisites: the starter project working, plus lessons 07.6 and 07.9. No key needed.
What you'll practise:
- Retrieval configs, adaptive k, dedup/MMR/merge/expansion and evidence-based ablation (lesson 07.2, Parts 1–2, Part 2)
- Multi-index routing with
RouteSpec/Router/RoutedRetriever, federated fusion and the wrong-route failure mode (07.2, Part 3) - Structured data as a retriever:
InMemoryTable/TableRetriever/TableQuery/source_mix(07.2, Part 4) - Retrieval triggers and ACL guards:
Trigger/TriggeredRetriever,GuardedRetriever, tenant-isolation tests (07.2, Parts 5–6, Part 6) - Query understanding end to end:
QueryPlan,plan_query,filters_for_search, multi-query fan-out, decomposition, clarification (lesson 07.3, Part 11, 7) - Conversational RAG: the condense step, per-turn routes, sticky filters, carried-forward chunks, session stores,
handle_turn(lesson 07.6, Parts 2–7, Part 7) - The eval harness:
EvalCase/load_cases,run_eval, deterministic metrics,LLMJudge/FakeJudge/CachedJudge,aggregate,compare_runs/bootstrap_ci,report_markdown(lesson 07.9, Part 5, 6)
Setup: everything the starter used, plus uv add pytest. You will also want the 06.10 harness files (harness.py and the evalset helpers printed in 06.10) for the retrieval-side numbers.
Steps:
- Split the corpus into indexes. Group
CHUNKSbydoc_idinto four lists (handbook,help-centre,tickets,contracts) and build oneHybridRetrieverper group — or, simpler and closer to the lesson, keep one chunk list per route and register them in a retriever registry{"handbook": ..., "help-centre": ..., "tickets": ..., "contracts": ..., "default": <all-chunks hybrid>}. Writeroutes.json-styleRouteSpecs in code: name, description, retriever keys, impliedfilters(e.g.{"kind": "policy"}for handbook), and heuristickeywords. - Route queries. Build
Router(routes, indexes)withcomplete=Nonefirst — the heuristic fallback must carry the demo. Wrap it inRoutedRetriever(router, rrf_k=60). Ask the ten smoke questions plus "why was I charged twice for VPN seats?" (should route totickets) and "what are the net-30 payment terms?" (should route tocontractsor fall back todefault). Logrouter.last_decisionper query; deliberately misroute one and confirm thedefaultroute's insurance behaviour described in 07.2, 3.3. - Add the orders table. Write
orders.pywith anInMemoryTable("orders", rows)of ~15 realistic rows (id,customer,sku,qty,total,status,ordered_at) — invent the data; no real customer data needed. Wrap it inTableRetriever(table)and fuse it with the document retriever viarrf_fuseor abuild_retrieverconfig whosefirst_stageincludes"table". Ask "what did Globex order in October?" and checksource_mix(hits)showssql:orderscontributions (07.2, 4.3). - Add triggers and guards. Wrap the fused retriever in
TriggeredRetriever(inner, Trigger())so "hi" skips retrieval through the built-in heuristic (07.2, Part 5). Then pass acomplete=classifier (theKeywordLLMfake from 07.2 works) and show that "what is 12% of 80?" is skipped only once the classifier is wired in — the bare heuristic deliberately lets it through (see the "what the heuristic deliberately misses" note in 07.2, 5.2). Then applyGuardedRetriever(or per-requestmandatory_filters) sotenant="acme"questions can never seeinitech/globexchunks, and write the tenant-isolation test from 07.2, 6.2: same query, two tenants, disjoint result sets. - Wire
plan_queryin front. Inask.py, callplan = plan_query(question, llm)first; useplan.retrieval_queries(fan out and fuse withrrf_fuseforRETRIEVE_MULTI, per-sub-question forDECOMPOSE),filters_for_search(plan.filters)merged under the mandatory filters, and honourCLARIFY/SKIP_RETRIEVALbefore touching the retriever. Keepplan.originalas the questiongenerate_answersees — the rewrites are for search, not for what the answer addresses (07.4). - Add conversation. Copy
docs_qa/conversation.pyfrom 07.6, Part 7 and its tests. UseJsonFileSessionStore("sessions/"). Callhandle_turn(store, session_id, user_text, retriever=..., llm=..., planner=..., generate=...)whereplanneradapts yourplan_queryoutput viaplan_result_from_query_plan(07.6) andgeneratewrapsgenerate_answerinto aGenerationRequest -> strcallable —grounded_generator(generate_answer, llm_messages)inconversation.pyalready does that wrapping. Mind the twollmshapes:handle_turn's ownllm=takes a prompt string and returns text (str -> str), whilegrounded_generatorand the otherdocs_qamodules take the message-listLLMfromdocs_qa/llm.py, so adapt once, for examplelambda prompt: llm_messages([{"role": "user", "content": prompt}]). Run a scripted three-turn session: "how much vacation do I get?" → "and for contractors?" → "what about sick leave?" — watch the condense step rewrite the follow-ups and the sticky filters/entities carry forward. - Build the eval set. Write
eval_cases.jsonlwith 18–24 cases in theEvalCaseschema (07.9, 3.1): ~10 answerable factoids withgold_chunk_idsandreference_answer, 3expect_abstainunanswerable cases (office wifi password; a question only the initech contract answers, withfilters={"tenant":"acme"}), 2 multi-turn cases usingturns, 2 comparison/multi-hop (qtype), 1 chit-chat, 1 adversarial (a question containing an instruction-like phrase). Splitdev/test— tune on dev only. - Run the harness. Create
docs_qa/eval/from 07.9, Part 5 (dataset.py,metrics.py,judges.py,runner.py,report.py). These modules import each other flat (from runner import aggregate), so keep the scripts that use them (youranswer_fnwrapper,gate.py) insidedocs_qa/eval/, as 07.9's smoke test does (thensys.path.append("../..")in the script sodocs_qa,corpusandretrieversresolve from the project root after the eval folder, whosemetrics.pymust win), or put that folder first onsys.path; and mind that the project root also holds 06.10'smetrics.pyandharness.py(which has its ownrun_eval), so never let the wrongmetrics/run_evalwin the import. Writeanswer_fn(case) -> RagResultthat runs your pipeline and mapsAnswer/Tracefields ontoRagResult(theRagResultdocstring injudges.pygives the field mapping). First run withFakeJudgeto validate plumbing, thenLLMJudgewith yourFakeLLM(deterministic but dumb) — note judge scores are only as good as the fake; the deterministic metrics (abstention, citation P/R, token-F1) are the real signal keylessly. - Add the regression gate. Run
run_evalon the dev set for config A (PRESETS["hybrid"], no routing) and config B (RoutedRetriever+ shaped hybrid). Usecompare_runs(before, after, metric="faithfulness")(call it again withmetric="abstention_correct"for the second gate; the booleans subtract as 0/1) andbootstrap_ci(07.9, 6.2) and writegate.pythat exits non-zero if faithfulness or abstention-correctness drops beyond the CI — the CI gate pattern from 07.9, 6.3. Then deliberately break something (drop the tenant filter) and confirm the gate catches it. - Measure retrieval separately. Run the 06.10 harness (
run_eval/evaluate_query/summarisefromharness.py, run from the project root as a separate script from the 07.9 eval — it is a differentrun_eval) over each retriever config on the q01–q16 evalset, so you can say which stage a quality change came from — the two-stage view from 07.9, Part 1.
Verify it, and what you should see:
uv run python -m docs_qa.query
uv run python chat_demo.py # your scripted 3-turn session
(cd docs_qa/eval && uv run python gate.py) # eval run + comparison; exits 0 on dev set
(cd docs_qa/eval && uv run python gate.py --break-acl) # exits 1: tenant leak detectedIllustrative shapes (your numbers will differ — the fakes are deterministic but your FakeLLM replies are yours):
route decisions: tickets->tickets(0.9) contracts->contracts(0.9) 'net-30'->default(heuristic)
session s1 turn2: standalone='What is the per diem policy for contractors?' route=retrieve carried=2
EvalCase eval-007: abstention=correct citation_f1=1.00 faithfulness=0.83
gate: faithfulness delta +0.02 (CI [-0.05,+0.09]) -> PASSDone when:
- One command runs a multi-turn conversation end to end: condense → route → retrieve (routed, filtered, fused) → plan → generate → cite → answer, with sessions persisted to
sessions/. - The router sends at least four question types to sensible indexes and falls back to
defaulton ambiguity;source_mixshowssql:hits for the orders questions. eval_cases.jsonlcovers answerable, unanswerable, multi-turn, ACL and chit-chat cases;run_evalproduces a markdown report;gate.pypasses on dev and fails when you break the ACL.- Your write-up names which metric moved for each change you tried (routing on/off, trigger on/off, k=4 vs k=8) and whether the CI says the difference is real.
Stretch ideas: Wire the Router's complete callable to a real provider for the LLM classifier and A/B it against the heuristic (07.2, 3.2). Add expand_parents/merge_adjacent shaping and measure on the eval set (07.2, 2.6). Try a managed retriever behind the same Retriever protocol and bake it off against yours (07.7, 2.8, Part 6). Add multi-turn eval cases scored at conversation level (07.6, Part 8).
Common problems:
- A misroute returns confidently empty results — the router's
confidenceis telemetry, not a control; keep a broaddefaultroute and loglast_decision(07.2, 3.3). filters_for_searchonly emitskind/langpredicates —party, dates andtopic_hintstay plan-side by design; don't "fix" it by post-filtering.TableRetrieverrows leak across tenants — callerfiltersmerge overplan.filtersfor exactly this reason; test it like chunks (07.2, 4.1).- Eval scores look great because the judge is your
FakeLLM— trust the deterministic metrics keylessly; treat LLM-judge numbers as plumbing checks until you run a real judge (07.9, 4.5). - You tuned on the test split — the dev/test discipline exists because re-chunking and re-prompting silently overfit; keep
testuntouched until the end (07.9, 3.4). - Carried-forward chunks double the prompt — check
TurnRecord.hitsvsfreshcounts and the token-cost section before raisingcarry_max(07.6, 4.2).
Stretch (optional): Production RAG service#
Goal: Wrap the docs_qa package in the FastAPI service from 07.11 — streaming answers, bearer auth, ACL-scoped retrieval, feedback capture, per-request cost accounting and traces — then run the seeded-fault debugging drill from 07.10 against it.
Prerequisites: the starter project (the stretch project helps), plus lessons 07.10 and 07.11. No key needed.
What you'll practise:
- The production architecture and the complete service:
/ask,/ask/stream,/feedback,/healthz,/readyz,PRINCIPALSauth, request IDs, budgets, concurrency limits, degradation events (lesson 07.11, 1.3–1.5, 1.4) - The RAG threat model and layered defences: injection scanning at ingest, ACL filters inside retrieval, cache keys carrying permission scope, PII handling, provider data policies (07.11, Part 2)
- Freshness operations: staleness SLAs, tombstones and delete verification, versioned indexes (07.11, Part 3)
- Cost engineering: the per-request
RequestCostledger, prompt caching with stable prefixes, scopedResponseCache, model tiering, degradation (07.11, Part 4) - Debugging in production:
PipelineTrace,trace_view.py,probe.py,demo.py, the oracle-context test and the master triage table (lesson 07.10, Parts 1–2, Part 2)
Setup: the full docs_qa package from the appendix (07.11) — if you did the two earlier projects you have most of it; add scan.py, scope.py, cache.py, costing.py, deletions.py, pipeline.py, runtime.py, fakes.py and service/app.py from 07.11. Dependencies:
uv add openai anthropic google-genai pydantic \
python-dotenv fastapi uvicorn httpx \
tenacity pytestSteps:
- Assemble the package. Reconcile names per the appendix:
Principal,Question,Answer,Citation,Hitre-exported fromdocs_qa/__init__.py;AskPipeline.ask/ask_stream/pingper the contract in 07.11, 1.5. Wireruntime.py'sbuild_pipeline()andbuild_stores()(the service imports both) withFakeLLM, the toy retrievers and a list-backed feedback store first — the service must boot with zero keys. - Boot the service.
uv run uvicorn service.app:app --port 8000. Hit/healthzand/readyz, thenPOST /askwith a bearer token from thePRINCIPALSmap and a question; thenPOST /ask/streamand watch the SSE events (meta,degraded,delta,citations,usage,done, anderrorwhen something fails). The demoPRINCIPALSmap in 07.11 has only two principals and both are in theacmetenant, so add a third, for example"demo-token-carol": Principal(user_id="carol", tenant_id="initech", groups=frozenset({"eng"})). Send one question as each of the two tenants and confirm the initech-only question abstains for the acme principal — the ACL filter is inside retrieval, never post-filtered (07.11, 2.3). - Capture feedback.
POST /feedbackwith{"request_id": ..., "rating": "down", "reason": "missing_source", "comment": "..."};reasonmust be one ofwrong,outdated,missing_sourceorother(anything else is a 422), andrequest_idis therequest_idfrom themetaevent of a stream. Find the storedFeedbackRecord. This is the input to the feedback loop in 07.11, 6.1. - Read the cost ledger. After ~10
/askcalls, dumpRequestCostrecords: per-stage tokens and USD,by_stage()totals, and confirm cached-prefix reuse shows up as reduced input cost on repeat questions (07.11, 4.1, 4.2). Writecost_report.pythat replays the ledger JSONL into a per-stage table. - Prove cache scoping. Ask the same question as two tenants; show
response_cache_key/scope_keydiffer and neither tenant's cached answer serves the other (07.11, 4.3). Then callResponseCache.invalidate_doc("handbook")and show the next answer re-retrieves. - Run the trace drill. Copy
traces.py,trace_view.py,demo.py,probe.pyfrom 07.10, Part 2.python demo.pyrenders the seeded failure (gold chunk at rank 6, k=5); then plant your own faults — one retrieval-side (k too small), one generation-side (aFakeLLMreply that answers from priors), one silent (aGuardedRetrieverwhose mandatory filter matches nothing). For each: capture aPipelineTrace, render it withtrace_view.py, runprobe.py'soracle_testandk_sweep, and write the diagnosis using the triage table (07.10, 1.3). - Test the failure paths. pytest:
/askwith a bad token → 401; a pipeline that raises →502from/askand anerrorevent from/ask/stream, a pipeline slower than the edge deadline →504, and a fakepingthat raises →/readyzreturns503; a retriever that raises inside the pipeline should instead give a degraded answer per the pipeline's policy (07.11, 4.7);/ask/streamdisconnect mid-stream closes the upstream (check logs). Use thefakes.pyseam — no keys. - Write the ops one-pager. From 07.11, 8.4: which checklist items your service meets, which it fakes (the
PRINCIPALSmap is a stand-in for your IdP), and the three you would fix first.
Verify it, and what you should see:
uv run pytest -q # service + pipeline tests pass, no keys
uv run uvicorn service.app:app --port 8000 &
curl -s localhost:8000/healthz # {"status":"ok",...}
curl -sN -X POST localhost:8000/ask/stream -H 'authorization: Bearer demo-token-alice' \
-H 'content-type: application/json' -d '{"question":"how much vacation?"}'
uv run python demo.py # the 07.10 seeded-fault trace report
uv run python trace_view.py fault-b.json # 07.10's seeded fault (exercise 9) or your own planted fault's trace: the suspects listIllustrative SSE shape (your text differs — FakeLLM is canned):
event: meta
data: {"request_id": "...", "trace_id": "..."}
id: 1
event: delta
data: {"text": "Full-time employees accrue"}
id: 2
...
event: citations
data: {"items": [{"id": 1, "doc_id": "handbook-2026", "chunk_id": "handbook-001", "title": "Employee Handbook", "page": 42, "quote": "..."}]}
event: usage
data: {"input_tokens": 3210, "output_tokens": 84, ...}
event: done
data: {"answer_id": "...", "abstained": false}Done when:
- The service boots keylessly, answers
/askand/ask/streamfor two tenants with correct ACL isolation, accepts feedback, and every request produces a trace and a cost record. - You have diagnosed three seeded faults with the trace viewer + probes and can name the pipeline stage each lived in.
- Cache keys provably include the permission scope; a doc invalidation forces re-retrieval.
- Your ops one-pager honestly separates "built", "faked for the demo" and "not built".
Stretch ideas: Point runtime.py at a real provider key and re-run the drill — watch real latency and cost land in the ledger (07.11, 4.1). Add FallbackRetriever so a dead primary degrades to BM25-only (07.11). Rehearse a blue/green index swap with shadow evaluation (07.11, 3.4). Add OpenTelemetry GenAI spans (07.11, 5.1; conventions in the lesson's resources). Stress the concurrency limits and watch the degradation events (07.11, 4.7).
Common problems:
fastapi.ssevs an SSE library — FastAPI 0.162.0 has nativeEventSourceResponse/ServerSentEvent; don't addsse-starlette(07.11).PRINCIPALSis a demo map, not auth — it stands in for your IdP/session store; never ship it as-is (07.11, 1.4).PipelineTrace≠ productionTrace— the viewer's format keeps hit text and the rendered prompt for debugging; the always-onTracekeeps ids/scores/hashes only. Reconcile via sampling, don't merge the schemas (07.10, 2.2).- Cached answers leaking across tenants — the cache key must carry
scope_key(principal)and the index version; a missing scope is a data leak, not a bug (07.11, 4.3). - Streaming citations — resolve markers at the end or buffer citation events; never emit a citation for a chunk that might be trimmed (07.5, 5.5).
- Degradation that isn't legible — a skipped rewriter/rerank must surface in
Answer.degradedand the stream'sdegradedevent, or users can't tell a thin answer from a broken one (07.11, 4.7).