Module 07: Projects

Retrieval3 projects0 of 3 complete

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:

bash
uv init docs-qa --bare --python 3.13 && cd docs-qa
uv add openai anthropic google-genai pydantic python-dotenv

These 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

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:

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:

  1. Create the package skeleton. mkdir docs_qa && touch docs_qa/__init__.py. Copy types.py, llm.py and rag.py from 07.1, 3.2 and 4.4, and budget.py/oracle.py if you want the cost calculator and oracle test (07.1, 5.2, 7.2). Copy smoke.py from 07.1, 3.3 to the project root.
  2. 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 (the tenant="acme" filter hid the initech contracts). Write down the failure each row maps to.
  3. Add retrieval configs. Copy docs_qa/retrieval.py from 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 with PRESETS["hybrid"] and {"dense": ..., "lexical": Bm25Retriever(CHUNKS)} — and compare their top-5 hits on five smoke questions. Note that Hit.score is not comparable across retrievers; compare which chunks come back, not the numbers.
  4. Add query understanding. Copy docs_qa/query.py from 07.3, Part 11. It needs docs_qa.llm's LLM/Message/FakeLLM, which you already have. Run its ScriptedLLM demo (uv run python -m docs_qa.query) and inspect a QueryPlan: original, cleaned, intent, route, rewrites, filters, techniques, degraded. Then call plan_query("and for contractors?", llm) — the fragment retrieves badly alone; that is the lesson's whole point.
  5. Wire the plan into retrieval. In your ask.py (below), turn the plan into search calls: plan.retrieval_queries gives the query strings, filters_for_search(plan.filters) gives the safe filter dict (07.3), and plan.route tells you whether to retrieve, clarify or skip. Merge filters_for_search output under any mandatory filters — never post-filter.
  6. Add grounded generation. Copy docs_qa/generate.py from 07.4, Part 10. Its llm parameter is LLMFn = Callable[[list[dict[str,str]]], str] — the same shape as docs_qa.llm.LLM, so your FakeLLM or provider adapter plugs straight in. Call generate_answer(plan.original, hits, llm, budget_tokens=3000); read GenerationResult: answer (GroundedAnswer with status, answer, evidence, missing), abstain_reason, sufficiency, model_calls. Check that an out-of-corpus question now sets status="abstained" — the naive pipeline only produced the string.
  7. 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 with cited_answer_from_grounded(gen.answer, passage_ids) — pass the GroundedAnswer inside the GenerationResult, not the result itself — where passage_ids is the ordered list of passage ids you sent (the chunk ids, in context order), then run verify_citations(cited, chunks={h.id: h.text for h in hits}, known_chunk_ids={h.id for h in hits}, n_sources=len(hits)) and citation_precision(checks) / claim_coverage(cited). Build sources (chunk_id -> SourceRef) from the hits' metadata and render with render_markdown(cited, sources). A marker pointing outside 1..n_sources, or a quote not found in its chunk, must fail loudly — that is the point of the verifier.
  8. Compose ask.py. Write the CLI that ties it together:
python
# 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):

python
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 out

filters_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:

bash
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):

text
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:

text
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.retrieval and ask.py all run with no key and no network.
  • ask.py answers 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.py passes, 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 inside docs_qa/; run scripts from the project root (uv run python ask.py), not from inside the package.
  • ImportError inside docs_qa files — the lessons import Hit from retrievers (top-level), LLM/Message/FakeLLM from docs_qa.llm, and QueryPlan types from docs_qa.query. Check each file's own import block; the appendix's naming note applies.
  • FakeLLM returns "" 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_query returns degraded=True — a FakeLLM reply the classifier can't parse. Check plan.techniques and the fake's responses; the deterministic fallback still produces a usable plan, which is the designed behaviour.
  • Citations all fail quote_found — evidence_from_hit deliberately leaves quote empty so verification fails closed; fill quotes from the model's structured evidence or 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

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:

  1. Split the corpus into indexes. Group CHUNKS by doc_id into four lists (handbook, help-centre, tickets, contracts) and build one HybridRetriever per 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>}. Write routes.json-style RouteSpecs in code: name, description, retriever keys, implied filters (e.g. {"kind": "policy"} for handbook), and heuristic keywords.
  2. Route queries. Build Router(routes, indexes) with complete=None first — the heuristic fallback must carry the demo. Wrap it in RoutedRetriever(router, rrf_k=60). Ask the ten smoke questions plus "why was I charged twice for VPN seats?" (should route to tickets) and "what are the net-30 payment terms?" (should route to contracts or fall back to default). Log router.last_decision per query; deliberately misroute one and confirm the default route's insurance behaviour described in 07.2, 3.3.
  3. Add the orders table. Write orders.py with an InMemoryTable("orders", rows) of ~15 realistic rows (id, customer, sku, qty, total, status, ordered_at) — invent the data; no real customer data needed. Wrap it in TableRetriever(table) and fuse it with the document retriever via rrf_fuse or a build_retriever config whose first_stage includes "table". Ask "what did Globex order in October?" and check source_mix(hits) shows sql:orders contributions (07.2, 4.3).
  4. 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 a complete= classifier (the KeywordLLM fake 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 apply GuardedRetriever (or per-request mandatory_filters) so tenant="acme" questions can never see initech/globex chunks, and write the tenant-isolation test from 07.2, 6.2: same query, two tenants, disjoint result sets.
  5. Wire plan_query in front. In ask.py, call plan = plan_query(question, llm) first; use plan.retrieval_queries (fan out and fuse with rrf_fuse for RETRIEVE_MULTI, per-sub-question for DECOMPOSE), filters_for_search(plan.filters) merged under the mandatory filters, and honour CLARIFY/SKIP_RETRIEVAL before touching the retriever. Keep plan.original as the question generate_answer sees — the rewrites are for search, not for what the answer addresses (07.4).
  6. Add conversation. Copy docs_qa/conversation.py from 07.6, Part 7 and its tests. Use JsonFileSessionStore("sessions/"). Call handle_turn(store, session_id, user_text, retriever=..., llm=..., planner=..., generate=...) where planner adapts your plan_query output via plan_result_from_query_plan (07.6) and generate wraps generate_answer into a GenerationRequest -> str callable — grounded_generator(generate_answer, llm_messages) in conversation.py already does that wrapping. Mind the two llm shapes: handle_turn's own llm= takes a prompt string and returns text (str -> str), while grounded_generator and the other docs_qa modules take the message-list LLM from docs_qa/llm.py, so adapt once, for example lambda 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.
  7. Build the eval set. Write eval_cases.jsonl with 18–24 cases in the EvalCase schema (07.9, 3.1): ~10 answerable factoids with gold_chunk_ids and reference_answer, 3 expect_abstain unanswerable cases (office wifi password; a question only the initech contract answers, with filters={"tenant":"acme"}), 2 multi-turn cases using turns, 2 comparison/multi-hop (qtype), 1 chit-chat, 1 adversarial (a question containing an instruction-like phrase). Split dev/test — tune on dev only.
  8. 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 (your answer_fn wrapper, gate.py) inside docs_qa/eval/, as 07.9's smoke test does (then sys.path.append("../..") in the script so docs_qa, corpus and retrievers resolve from the project root after the eval folder, whose metrics.py must win), or put that folder first on sys.path; and mind that the project root also holds 06.10's metrics.py and harness.py (which has its own run_eval), so never let the wrong metrics/run_eval win the import. Write answer_fn(case) -> RagResult that runs your pipeline and maps Answer/Trace fields onto RagResult (the RagResult docstring in judges.py gives the field mapping). First run with FakeJudge to validate plumbing, then LLMJudge with your FakeLLM (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.
  9. Add the regression gate. Run run_eval on the dev set for config A (PRESETS["hybrid"], no routing) and config B (RoutedRetriever + shaped hybrid). Use compare_runs(before, after, metric="faithfulness") (call it again with metric="abstention_correct" for the second gate; the booleans subtract as 0/1) and bootstrap_ci (07.9, 6.2) and write gate.py that 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.
  10. Measure retrieval separately. Run the 06.10 harness (run_eval/evaluate_query/summarise from harness.py, run from the project root as a separate script from the 07.9 eval — it is a different run_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:

bash
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 detected

Illustrative shapes (your numbers will differ — the fakes are deterministic but your FakeLLM replies are yours):

text
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]) -> PASS

Done 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 default on ambiguity; source_mix shows sql: hits for the orders questions.
  • eval_cases.jsonl covers answerable, unanswerable, multi-turn, ACL and chit-chat cases; run_eval produces a markdown report; gate.py passes 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 confidence is telemetry, not a control; keep a broad default route and log last_decision (07.2, 3.3).
  • filters_for_search only emits kind/lang predicates — party, dates and topic_hint stay plan-side by design; don't "fix" it by post-filtering.
  • TableRetriever rows leak across tenants — caller filters merge over plan.filters for 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 test untouched until the end (07.9, 3.4).
  • Carried-forward chunks double the prompt — check TurnRecord.hits vs fresh counts and the token-cost section before raising carry_max (07.6, 4.2).

Stretch (optional)

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, PRINCIPALS auth, 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 RequestCost ledger, prompt caching with stable prefixes, scoped ResponseCache, 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:

bash
uv add openai anthropic google-genai pydantic \
       python-dotenv fastapi uvicorn httpx \
       tenacity pytest

Steps:

  1. Assemble the package. Reconcile names per the appendix: Principal, Question, Answer, Citation, Hit re-exported from docs_qa/__init__.py; AskPipeline.ask/ask_stream/ping per the contract in 07.11, 1.5. Wire runtime.py's build_pipeline() and build_stores() (the service imports both) with FakeLLM, the toy retrievers and a list-backed feedback store first — the service must boot with zero keys.
  2. Boot the service. uv run uvicorn service.app:app --port 8000. Hit /healthz and /readyz, then POST /ask with a bearer token from the PRINCIPALS map and a question; then POST /ask/stream and watch the SSE events (meta, degraded, delta, citations, usage, done, and error when something fails). The demo PRINCIPALS map in 07.11 has only two principals and both are in the acme tenant, 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).
  3. Capture feedback. POST /feedback with {"request_id": ..., "rating": "down", "reason": "missing_source", "comment": "..."}; reason must be one of wrong, outdated, missing_source or other (anything else is a 422), and request_id is the request_id from the meta event of a stream. Find the stored FeedbackRecord. This is the input to the feedback loop in 07.11, 6.1.
  4. Read the cost ledger. After ~10 /ask calls, dump RequestCost records: 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). Write cost_report.py that replays the ledger JSONL into a per-stage table.
  5. Prove cache scoping. Ask the same question as two tenants; show response_cache_key/scope_key differ and neither tenant's cached answer serves the other (07.11, 4.3). Then call ResponseCache.invalidate_doc("handbook") and show the next answer re-retrieves.
  6. Run the trace drill. Copy traces.py, trace_view.py, demo.py, probe.py from 07.10, Part 2. python demo.py renders the seeded failure (gold chunk at rank 6, k=5); then plant your own faults — one retrieval-side (k too small), one generation-side (a FakeLLM reply that answers from priors), one silent (a GuardedRetriever whose mandatory filter matches nothing). For each: capture a PipelineTrace, render it with trace_view.py, run probe.py's oracle_test and k_sweep, and write the diagnosis using the triage table (07.10, 1.3).
  7. Test the failure paths. pytest: /ask with a bad token → 401; a pipeline that raises → 502 from /ask and an error event from /ask/stream, a pipeline slower than the edge deadline → 504, and a fake ping that raises → /readyz returns 503; a retriever that raises inside the pipeline should instead give a degraded answer per the pipeline's policy (07.11, 4.7); /ask/stream disconnect mid-stream closes the upstream (check logs). Use the fakes.py seam — no keys.
  8. Write the ops one-pager. From 07.11, 8.4: which checklist items your service meets, which it fakes (the PRINCIPALS map is a stand-in for your IdP), and the three you would fix first.

Verify it, and what you should see:

bash
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 list

Illustrative SSE shape (your text differs — FakeLLM is canned):

text
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 /ask and /ask/stream for 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.sse vs an SSE library — FastAPI 0.162.0 has native EventSourceResponse/ServerSentEvent; don't add sse-starlette (07.11).
  • PRINCIPALS is a demo map, not auth — it stands in for your IdP/session store; never ship it as-is (07.11, 1.4).
  • PipelineTrace ≠ production Trace — the viewer's format keeps hit text and the rendered prompt for debugging; the always-on Trace keeps 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.degraded and the stream's degraded event, or users can't tell a thin answer from a broken one (07.11, 4.7).
Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close