Module 10A: Projects

Production3 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 (10A.P1) and two stretches (10A.P2 and 10A.P3; the agent harness is optional, and it carries clearly marked optional extensions for memory, multi-agent and simulator-validation evals). The framework lessons of Module 10B add no numbered project: they add clearly marked optional extensions to the projects that fit best, namely a port of the RAG suite to DeepEval and Inspect with the numbers reconciled (starter), a judge-validation stretch idea for the two frameworks' judges (calibrated judge), and an Inspect agent eval and a DeepEval traced-agent eval in CI (agent harness). DeepEval is the required part of Module 10B, so the DeepEval extensions (the DeepEval half of the port, the DeepEval judge check and the traced-agent eval in CI) are the recommended core extensions, and the Inspect ones (the Inspect half of the port, the Inspect judge check and the Inspect agent eval) are optional, for readers who took the optional Inspect lessons 10B.8 to 10B.17. Every project runs keylessly. The module's running package evalkit is pure standard library except dataset.py (Pydantic), and every model call sits behind an injectable seam (call_model, judge, pipeline, produce), so scripted fakes and recorded outputs prove all the plumbing while a hosted provider proves the judgement. Provider keys are the stretch goal for each project once you have them.

First time? Create the evalkit package once (uv init evalkit --bare --python 3.13 && cd evalkit && mkdir evalkit) or reuse the project you built while doing the lessons, starting from the minimal harness in 03.13; each lesson's Setup says which files it adds, and 10A.10's appendix is the consolidated map. The projects below say exactly which files to copy and where.

Two honesty notes that apply everywhere. First, all pure-local output in the lessons was produced for real, so you can reproduce it exactly; model-dependent output is labelled illustrative because no keys were used when the lessons were written. Second, an eval number is only as honest as its dataset and its judge: a pass rate computed on leaked, contaminated or too-small data, or graded by an unvalidated judge, is worse than no number at all. Each project makes you confront that deliberately.


Starter

Starter: RAG eval suite#

Goal: Turn the Module 07 docs_qa Q&A bot into a measured system: a labelled RAG eval set built from the Module 05 synthetic dataset plus hand-written cases, scored by evalkit/rag_eval.py — retrieval and generation measured separately, failures attributed to stages with oracle experiments, per-type slices, a markdown scorecard, and a paired comparison between two pipeline configurations.

This is the module's core workflow end to end: dataset (10A.2) → deterministic metrics (10A.3) → harness anatomy (10A.1) → RAG methodology (10A.6). The keyless path is real here, not a compromise: retrieval, generation plumbing, deterministic metrics, abstention cells, citation checks, oracle isolation and statistics are all pure Python. The only steps that need a model are the answers themselves (your FakeLLM or a provider) and judge verdicts (a ScriptedJudge or a real judge).

What you'll practise:

  • The eval anatomy — dataset + task + scorers + aggregation + report — as a real pipeline rather than a demo (lesson 10A.1, Part 6)
  • Case design and dataset hygiene: question types, expect_abstain, nuggets, gold chunk IDs, splits, deduplication and provenance (lesson 10A.2, Parts 3 and 6, 6)
  • Deterministic graders first: token-F1, exact match, citation precision/recall, nugget recall, abstention accuracy — the metrics that need no judge (lesson 10A.3, Part 1)
  • The RAG evaluation matrix and stage-isolating oracle experiments (query / retrieval / assembly) that attribute failures instead of guessing (lesson 10A.6, Parts 1–2, 2)
  • Generation metrics: faithfulness, answer relevance, correctness, citation checks, abstention as a 2×2, context diffs (lesson 10A.6, Part 3)
  • The evalkit/rag_eval.py harness: RagCase, StageRun, the RAGPipeline protocol, run_rag_eval, aggregate, bound_analysis, compare_runs, report_markdown (lesson 10A.6, Part 5)
  • Paired comparison with bootstrap confidence intervals and per-slice reporting (lesson 10A.6, Part 8, lesson 10A.5, 7.4)

Setup: You need the Module 07 docs_qa project — if you haven't built it, do the starter in 07's projects.md first (or at minimum corpus.py, retrievers.py and the docs_qa package through 07.5's generate.py/cite.py). Then, inside that same project folder:

bash
uv init docs-qa --bare --python 3.13 && cd docs-qa   # first time only; see lesson 03.1 for the full setup
uv add openai anthropic google-genai pydantic python-dotenv pytest
mkdir evalkit                                        # the module's package, inside your project

Copy these lesson files into evalkit/ (each is printed in full in its lesson): core.py (10A.1, Part 6), judges.py (10A.4, Part 9) and rag_eval.py (10A.6, 5.2). Optionally add scorers.py (10A.3, Part 8) for extra deterministic graders and dataset.py (10A.2, 8.2) for dataset stats and dedup — both run on the pydantic you already installed. No .env keys are needed: docs_qa's FakeLLM answers, ScriptedJudge grades, and every metric that matters here is deterministic.

Steps:

  1. Verify the bot still answers. Run the Module 07 starter's ask.py (or smoke.py) on two questions — one answerable, one out-of-corpus — and confirm the abstention flag and citation check counts print. Everything downstream assumes docs_qa's generate_answer, Retriever.search and FakeLLM work.
  2. Produce the question set. Write export_chunks.py that reads corpus.CHUNKS and emits the five-field shape synth_eval.py expects (chunk_id, doc_id, doc_type, source, text — the same conversion the Module 05 project describes). If you already ran that project over a matching corpus, reuse its eval_questions.jsonl; otherwise copy synth_eval.py and question_model.py/gen_questions_prompt.txt from 10A.2, Parts 2 and 11 into a scratch folder and run the stub (uv run python synth_eval.py chunks_for_eval.jsonl) or your hosted generator. The output is eval_questions.jsonl with id, question, question_type, reference_answer, answerable, cited_chunk_ids, evidence_span, persona, language, generator, prompt_version.
  3. Convert to rag_cases.jsonl. Write make_rag_cases.py that maps each item to the RagCase schema (10A.6, 4.1): id→case_id, question→question, question_type→type/qtype, reference_answer→reference_answer, cited_chunk_ids→gold_chunk_ids, answerable == false→expect_abstain: true, and persona/language/generator→source/notes. Derive expected_facts or nuggets where the reference answer has separable claims (a refund policy answer might need "30 days" and "manager approval" as two nuggets). Assign split — roughly 80% dev, 20% test, stratified by question_type so both splits cover every type, and by document, not by row: all questions generated from the same doc_id (or chunk) go to the same split, otherwise tuning on dev leaks into test (10A.2, 6.7); tune only on dev.
  4. Hand-write the cases synthetic data can't give you. Append ~8 cases by hand to rag_cases.jsonl covering what the generator won't produce: 2 expect_abstain unanswerable questions (office wifi password; something only another tenant's contract answers, with filters={"tenant": "acme"}), 1 adversarial case whose "document" text contains an instruction-like phrase, 1 multi-hop case with nuggets spanning two chunks, 1 ACL-leak case, 1 chit-chat case, and 1 partial_ok case. This is the representativeness-vs-coverage lesson from 10A.2, 2.8 applied.
  5. Build the chunks map. Write chunks_map.json (or build it in code) mapping every chunk_id to {"chunk_id", "text", "metadata"} — rag_eval.py's Chunk needs the text for quote verification and the metadata for judge context and ACL fields. Load it once and pass chunks= to run_rag_eval.
  6. Write the pipeline adapter. Create docsqa_pipeline.py implementing the RAGPipeline protocol — run(case, oracle="none") -> StageRun — following 10A.6, 5.4 but with real docs_qa imports: retriever = the hybrid retriever over CHUNKS (from retrievers.py + docs_qa.retrieval.PRESETS, as in the 07 starter), llm = your FakeLLM, generation via docs_qa.generate.generate_answer. Implement the four oracle modes: "none" (raw question → retrieve → generate), "query" (same — the docs_qa planner already rewrites; note the difference honestly), "retrieval" (skip retrieval, feed gold_chunk_ids chunks to the generator), "assembly" (real retrieved set with a huge budget_tokens). Map GenerationResult fields onto StageRun exactly as the lesson's adapter does — retrieved_ids before oracle substitution, context_ids from ctx.kept + ctx.truncated, cited_ids/cited_quotes parallel from ga.evidence, abstained from status in {"abstained", "needs_clarification"}, answer_partial from status == "partial", sufficiency from coverage_score, latency and token counts filled in.
  7. Run end to end, deterministically first. Write run_rag_eval.py that loads cases + chunks, builds DocsQaPipeline, calls run_rag_eval(cases, pipeline, judge=ScriptedJudge(...), chunks=chunks_map, out_path="rag_results.jsonl", run_meta={...}), then prints report_markdown(results, title=..., bound=bound_analysis(e2e, oracle_retrieval)). Start with ScriptedJudge — its canned scores prove the plumbing; the deterministic columns (token-F1, citation F1, abstention accuracy, flags) are the real signal.
  8. Run the oracle experiments. Re-run with oracle="retrieval" and oracle="assembly" on the same cases, then bound_analysis(e2e_results, oracle_results) — the bound ratio tells you what share of end-to-end failures retrieval/assembly owns versus generation. This is the single most decision-relevant number in RAG eval (10A.6, 2.4).
  9. Add a judge — carefully. Swap ScriptedJudge for LLMJudge wrapping an injectable llm callable: keylessly that's your FakeLLM or evalkit.judges.FakeCallModel (plumbing check only — a fake judge's scores mean nothing about quality); with keys, use a provider call through evalkit.judges.rubric_judge with a different model family than the generator, per 10A.4, 5.2. Record judge_version in run_meta.
  10. Compare two configurations. Change one thing — retriever preset (dense vs hybrid), context k (4 vs 8), or the grounding prompt — run both, and call compare_runs(before, after, "faithfulness") plus the deterministic metrics. Read the bootstrap CI: a +0.02 with CI [-0.01, +0.05] is noise, not progress (10A.6, 8.1).
  11. Grow the set honestly. Feed the worst slice from your report back into rag_cases.jsonl as new cases — the flywheel from 10A.2, Part 7. Re-run dedupe from dataset.py if you added evalkit/dataset.py, and confirm no case leaked into a prompt's few-shot examples.

Verify it, and what you should see:

bash
uv run python run_rag_eval.py                 # e2e run -> rag_results.jsonl + rag_report.md
uv run python run_rag_eval.py --oracle retrieval   # oracle run for the bound analysis
uv run python compare_configs.py              # dense vs hybrid (or k=4 vs k=8) -> comparison table

The report's shape is the lesson's own (10A.6, 5.3) — per-split and per-type rows, flags, oracle bound analysis, provenance line. On your set the numbers differ; the structure is what matters.

Example output · illustrative19 lines
## docs_qa RAG eval

| split/type | n | faith | relev | corr | nugget | cite-F1 | abst-acc | p50ms | p95ms |
|---|---|---|---|---|---|---|---|---|---|
| overall | 24 | 0.812 | 0.790 | 0.655 | 0.833 | 0.742 | 0.875 | 41.000 | 88.000 |
| split:dev | 19 | ... |
| split:test | 5 | ... |
| type:factoid | 12 | ... |
| type:unanswerable | 4 | — | — | — | — | — | 0.750 | ... | ... |

### Flags
- `overall`: 1 unanswerable case(s) answered
- `type:multi-hop`: 2 case(s) with gold not retrieved

### Oracle bound analysis
- paired cases: 22
- retrieval-bound failures: 5
- both-fail (generation/label): 3
- bound ratio: 0.625

What to notice: the — cells are honest "not measured" states (no judge scores on abstained cases, no citation labels without gold_chunk_ids); the flags tell you which cases to read; the bound ratio of 0.625 means most e2e failures would be rescued by oracle retrieval — your next fix is retrieval, not the prompt. Judge columns will be ScriptedJudge canned values or FakeCallModel noise — treat them as plumbing checks, exactly as 07.9, 4.5 warns.

Done when:

  • rag_cases.jsonl loads through load_rag_cases with a dataset SHA, covers every question type you generated plus your hand-written edge cases, and split assignments keep test untouched until the end.
  • run_rag_eval produces rag_results.jsonl and a markdown report with overall, per-split and per-type rows, the abstention 2×2 counts and the flag list.
  • The oracle runs produce a bound analysis you can interpret: you can say whether retrieval, assembly or generation owns most of your failures, with numbers.
  • compare_runs (or compare_configs.py) gives you a paired bootstrap CI for at least one config change, and you can state whether the difference is real or noise.
  • Your write-up names the worst slice, the failure class it maps to (10A.6, 9.2), and which pipeline stage owns the fix.

Stretch ideas:

  • Swap ScriptedJudge for a real LLMJudge via evalkit.judges.rubric_judge with a different-family provider model, and validate it against ~30 hand labels first (10A.5 — don't skip this; an unvalidated judge manufactures confidence).
  • Add multi-turn cases with turns and score them at conversation level (10A.6, Part 6).
  • Add an insufficient-context probe: withhold the gold chunk on a dev slice of answerable cases and report the answered-despite-insufficient-context rate (10A.6, 3.5).
  • Tune the abstention threshold from abstention_curve output and re-run — watch the 2×2 move (10A.6, 3.5).
  • Run nonfunctional.py's perturbation_suite over your questions and measure the pass-rate delta per perturbation type (10A.10, 6.3).
  • Render the report through evalkit/report.py's render_report for the stakeholder format (10A.10, 7.1).

Optional extension: port the suite to DeepEval and Inspect, and reconcile the numbers (10B.1 to 10B.17)#

This extension is additive and keyless: it is not a separate project, and it comes after the base suite works. The DeepEval half is the recommended core extension (DeepEval is the mandatory part of the track); every Inspect part is optional and needs the Inspect lessons 10B.8 to 10B.17, so a DeepEval-only port skips the Inspect scorer, model_graded_qa() and Inspect-log items below and reconciles DeepEval against evalkit alone. The point is not to replace evalkit but to learn what each package does to the same numbers. Work in the framework track's single project (10B.1, Part 5): uv add deepeval python-dotenv (and, only for the optional Inspect half, uv add inspect-ai), set DEEPEVAL_TELEMETRY_OPT_OUT=1, and use the track's scripted FakeJudge and mockllm/model so nothing calls a provider.

Deliverables:

  • A frozen fixture: the same rag_cases.jsonl rows (at least the five-case shape 10B.17, 3.2 uses, with an abstention case and the empty-input edge case kept in), a scripted pipeline and a scripted judge, so any difference is the harness and not the model (10B.17, 5.5).
  • The deterministic checks written once as plain functions, wrapped as a DeepEval BaseMetric (10B.3, Part 6) and as an Inspect scorer (10B.10, Part 5), loaded through each package's own dataset path (10B.6, Part 1, 10B.9, Part 3).
  • One judged metric on each side (a DeepEval RAG metric such as faithfulness from 10B.4, Part 2, and Inspect's model_graded_qa() from 10B.11), each run against the scripted judge, with the judge prompts printed so you can see that the two definitions differ.
  • A reconciliation table in your write-up: case counts, the set of failing case ids, per-case scores, then each headline named as in 10B.17, 10.1 (DeepEval's printed pass rate versus Inspect's mean accuracy and stderr versus evalkit's rag_eval.py aggregates), with every difference classified as definition, noise or bug (10B.17, 10.3).
  • Optionally, Inspect's per-sample results fed back into evalkit's paired bootstrap (10B.17, 4.4) so the between-run comparison uses one set of statistics.

Acceptance criteria: case counts match on both sides, or each missing case is explained (the empty-input loader behaviour is a known cause, 10B.17, 5.2); the deterministic per-case verdicts agree exactly before any aggregate is compared; no judged number is declared "right" without validating that judge against human labels (10A.5); the frozen fixture and reference numbers are kept as a permanent smoke test (10B.1, 12.5).

Pitfalls: comparing DeepEval's pass rate (every metric must pass) with Inspect's per-scorer accuracy as if they were one quantity; trusting an Inspect target that is an empty string, which makes text scorers pass anything (10B.9, Part 2); letting a metric silently skip cases that lack a field (10B.2, Part 3); reporting a framework's default threshold as if you had chosen it.

Common problems:

  • gold_chunk_ids don't match the corpus. The synthetic set was generated over a different chunk file — citation_prf and context_diffs silently score zero. Check that every gold_chunk_ids value exists in your chunks_map; regenerate or drop cases whose chunks aren't in docs_qa.
  • Everything abstains or nothing does. expect_abstain maps from answerable == false — check your converter didn't invert it, and that generate_answer's sufficiency gate is actually wired (min_coverage set, context non-empty).
  • The oracle "retrieval" run changes nothing. You fed gold chunks but the generator still abstains — that's a generation-bound failure, which is exactly what the bound analysis is for; check StageRun.context_ids on the oracle run to confirm gold chunks actually entered the prompt.
  • Judge scores look great but mean nothing. FakeCallModel/ScriptedJudge return canned verdicts — they prove plumbing, not quality. Only trust judge columns after validating against human labels (the stretch project below).
  • The report's split:test row is empty or tiny. Stratify by question_type when assigning splits — a random 80/20 on a skewed synthetic set can leave a whole type in dev only.
  • retrieved_not_context flags everywhere. Your adapter records retrieved_ids before oracle substitution but context_ids after assembly — if the context budget trims aggressively, retrieval "succeeded" while the model never saw the chunk. That's a real finding, not a bug; check budget_tokens in generate_answer.

Stretch

Stretch: Calibrated LLM-as-judge grader#

Goal: Build a judge for a real grading task — a support-answer quality rubric or the ticket-triage verdict — then prove it agrees with humans before trusting it: ~60 hand-labelled cases, agreement metrics (kappa, TPR/TNR), bias-corrected pass rates with intervals, a rubric iteration loop on the dev split, judge regression canaries, and finally a CI gate that runs the calibrated judge on every prompt change.

This is the module's hardest-won lesson turned into a system: 10A.4 builds the judge, 10A.5 calibrates it, 10A.8 gates on it. The keyless path covers everything except the judge's own verdicts — FakeCallModel proves the plumbing, and you can simulate judge behaviour on fixtures to practise the statistics before spending a cent on real judge calls.

What you'll practise:

  • Judge design and prompt anatomy: Rubric, RubricCriterion, rubric_judge, anchored criteria, output schemas, "cannot determine" paths, versioning (lesson 10A.4, Parts 2–3 and 9, 9)
  • The validation loop: label → judge → measure agreement → analyse disagreements → fix → re-measure, with dev/calibration/test splits for the judge (lesson 10A.5, Parts 1–2, 2)
  • Agreement metrics from scratch: cohens_kappa, weighted_kappa, krippendorff_alpha, spearman, kendall_tau_b, tpr_tnr, fail_detection, disagreement_report, agreement_ci (lesson 10A.5, Part 3)
  • Judge error structure and correction: adjusted_pass_rate, corrected_rate_ci, when correction is unsafe (lesson 10A.5, Part 4)
  • Judge regression tests and drift: judge_test_set, canary examples, re-validation triggers (lesson 10A.5, Part 6)
  • Statistical reporting under judge noise: paired_diff_ci, variance decomposition, the multiple-comparison trap (lesson 10A.5, Part 7)
  • The CI gate: run_suite, CallCache, the result store (save_run/load_run), evaluate_gate, GateThresholds, cli.py, pytest parametrisation, GitHub Actions (lesson 10A.8, Parts 4–6, 5, 6)
  • The change playbooks: prompt-change and model-upgrade procedures (lesson 10A.8, Part 8)

Setup:

bash
uv init evalkit --bare --python 3.13 && cd evalkit && mkdir evalkit
uv add pydantic pytest pytest-xdist
# provider judge only — pick the providers you have keys for:
uv add openai anthropic google-genai python-dotenv

Copy judges.py (10A.4, Part 9), judge_validation.py (10A.5, Part 10), runner.py, compare.py and cli.py (10A.8, Parts 4 and 6, 6.1) into evalkit/. core.py (10A.1) and scorers.py (10A.3) help for the harness side. No keys needed for the statistics; the judge itself needs a call_model — FakeCallModel keylessly, a provider SDK with keys.

Steps:

  1. Pick the task and produce the outputs. Choose something you can label: the 10A.1 ticket-triage task, a support-answer quality rubric, or your own. Produce ~60 (input, output) pairs into outputs.jsonl — e.g. run two prompt variants of your system over a fixed input set so you have paired outputs to compare later. If you don't have a system, use the 10A.1 triage_eval.py FakeTriageModel outputs plus hand-varied ones; the point is a fixed, versioned set of outputs to grade.
  2. Write the labelling sheet. Create labels_template.csv with columns example_id,input,output,human_label,notes and a LABEL_GUIDE.md with your rubric's anchored definitions (what "pass" means, borderline examples, what to ignore). Label all ~60 yourself — stratify deliberately: mostly obvious cases plus ~15 borderline ones, because agreement on borderline cases is what discriminates judges (10A.5, 2.4). If you can, have a second person label a 15-case subset for a human–human κ baseline.
  3. Convert labels to Judgement records. Write make_judgements.py that emits Judgement(example_id=..., human=..., judge=..., slice_=...) objects — start with judge= placeholder, fill it in step 5. Split the set dev/calibration/test per 10A.5, 1.4: dev for rubric iteration, calibration for the reported agreement, test frozen for the gate.
  4. Build the judge. Write judge_setup.py constructing a Rubric with anchored RubricCriterions (10A.4, 3.2) and a call_model: FakeCallModel first to prove plumbing, then a provider adapter — for OpenAI the Responses API with structured output, for Anthropic Messages with its schema subset, per 10A.4, 5.3. Use a different model family than whatever generated the outputs, and pin judge_version = prompt version + model ID.
  5. Run the judge and measure agreement. Write validate_judge.py that runs rubric_judge over the dev+calibration cases, maps verdicts to Judgement.judge, then prints raw_agreement, cohens_kappa, tpr_tnr, fail_detection, disagreement_report and agreement_ci per slice. Expect κ in the 0.4–0.7 range on a first rubric — that is normal; the iteration loop is the work.
  6. Iterate the rubric on dev only. Read disagreement_report's worst slice, classify each disagreement (judge too lenient? rubric ambiguous? label wrong?), apply one fix at a time — anchor a criterion, split a vague one, add an "ignore" clause, switch binary↔ordinal — and re-measure on dev. When dev κ plateaus, measure once on calibration and stop touching the rubric; the calibration number is your honest agreement estimate (10A.5, 5.2, 5.6).
  7. Compute the corrected pass rate. Using calibration tpr_tnr, run adjusted_pass_rate and corrected_rate_ci on your observed judge pass rate — this is the Rogan–Gladen correction from 10A.5, 4.2. If TPR+TNR ≤ 1 or the CI is enormous, the judge isn't good enough to correct — report that honestly.
  8. Build the judge test set. Freeze ~20 cases with known verdicts as judge_test_set canaries (10A.5, 6.1); wire them to run whenever the judge prompt or model changes.
  9. Wire the CI gate. Write gate_eval.py that runs run_suite (10A.8, 4.2) over your eval cases with the judge as a scorer, stores results via save_run, and calls evaluate_gate with GateThresholds — an absolute floor on the judge pass rate plus a relative non-regression max_drop with tolerance, and per-slice floors if a slice matters (10A.8, 1.3, 10A.8, 10.1). Wrap it in evalkit/cli.py's gate command shape so CI calls one command (the CLI's own flags are run --cases/--task/--scorer/--cost-of/--max-calls/--max-cost-usd and gate --run/--baseline/--metric/--min-overall/--max-drop/--min-cases/--slice-dim/--slice-floor; the metric name is the scorer function's __name__). Pass a Budget(max_calls=..., max_cost_usd=..., cost_of=...) to run_suite so a bad run cannot overspend (10A.8, 3.5): it is thread-safe, and its calls count includes calls that raised.
  10. Prove the gate catches a real regression. Run the gate on prompt variant A (pass), then variant B with a deliberately degraded prompt (fail) — and confirm it fails for the right reason (paired diff beyond tolerance), not infra noise. Use paired_diff_ci/paired_bootstrap_ci for the A-vs-B comparison (10A.5, 7.4, 10A.8, 2.3).
  11. Add the CI plumbing. Adapt the lesson's tests/conftest.py + test_eval_smoke.py (10A.8, 5.1) to run a ~10-case smoke subset on every commit, and keep the full suite for PR/nightly tiers. Reference the GitHub Actions YAML from 10A.8, 6.2 — do not run it, just adapt it.
  12. Write the judge changelog. Record judge_version, rubric version, measured κ/TPR/TNR and date for every judge change — the artefact 10A.5, 5.4 requires so score changes stay attributable.

Verify it, and what you should see:

bash
python validate_judge.py            # agreement report on calibration split
python gate_eval.py                 # CI gate on the current prompt variant
python gate_eval.py --variant degraded   # same suite, worse prompt -> gate fails
pytest -q -m eval_smoke             # parametrised smoke subset

The agreement report's shape (your numbers will differ; the figures below are internally consistent, built from 17 true passes, 3 false fails, 4 false passes and 16 true fails, and the lesson's judge_validation.py functions reproduce them from such a table):

Example output · illustrative6 lines
calibration split: n=40
  raw agreement:   0.825
  cohen's kappa:   0.650   CI95 [0.37, 0.85]
  judge TPR/TNR:   0.850 / 0.800
  adjusted pass rate: 0.500 (observed 0.525)  CI95 [0.18, 0.77]
  worst slice:     refunds  n=12  kappa=0.33

and the gate:

Example output · illustrative5 lines
run stored: runs/2026-11-06T…/  cases=60 repeats=1 workers=4
metric 'judge_pass' current=0.683 baseline=0.700
paired diff: -0.017 CI95 [-0.08, +0.05] -> within tolerance
slice floor 'refunds': 0.61 >= 0.55 -> ok
gate: PASS

What to notice: 0.825 raw agreement sounds strong, but kappa is 0.65 with a wide interval at n=40; TPR/TNR show the direction of the errors (the false-pass rate of 0.20 is higher than the false-fail rate of 0.15, so the adjusted pass rate is slightly lower than the observed one) and the corrected rate's interval is wide because 40 labels cannot pin it down; the worst slice is where the rubric needs work; and the gate's CI straddling zero means "within tolerance", not "proven equal".

Done when:

  • validate_judge.py prints agreement metrics per slice on the calibration split, and your rubric changelog records every change with its measured effect on dev.
  • You can state the judge's TPR/TNR, the corrected pass rate with its CI, and whether correction is safe — or honestly report that it isn't.
  • The judge test set runs and judge_version is stamped on every verdict.
  • gate_eval.py passes on the good prompt variant and fails on the degraded one for a statistical reason (paired diff beyond tolerance or a slice floor breach), with infra errors excluded.
  • The pytest smoke subset runs keylessly in CI configuration, and your notes explain which parts still need keys.

Stretch ideas:

  • Add a pairwise_judge variant for comparing prompt A vs B directly, with order-swapping (swap=True) and swapped_agree consistency checks (10A.4, 2.2, 4.1).
  • Try jury_judge with 3 call_models and inspect spread on borderline cases (10A.4, 2.7).
  • Compare the Rogan–Gladen corrected pass rate with a prediction-powered estimate (10A.5, 4.6): label a small random sample of the judged outputs, run both, and explain why the intervals differ.
  • Wire memoize/CallCache so re-runs are free, then deliberately bust the cache once to see what a warm-cache gate hides (10A.8, 3.2).
  • Hosted, needs keys: swap FakeCallModel for real provider calls, run the full 60-case calibration, and compare κ across two judge model families — the different-family rule in action (10A.4, 5.2).
  • Framework judges (optional, after 10B.1 to 10B.7; the Inspect half needs 10B.8 to 10B.17 and is optional): run your calibration split through a DeepEval GEval metric (the recommended core extension) and, optionally, through Inspect's model_graded_qa(), wrapped so that validate_judge.py can read their verdicts, and report each one's TPR, TNR and κ against the same human labels (10B.3, Part 10, 10B.11, Part 10). Keyless, the scripted judge only proves the wrapper; the agreement numbers need a real judge.

Common problems:

  • High raw agreement, useless judge. Predicting the majority class scores ~85% raw agreement on imbalanced labels. Check κ and TNR — if TNR is near zero the judge never says "fail" (10A.5, 3.2).
  • κ looks fine but slices hide failure. A global κ of 0.6 can be 0.8 on easy cases and 0.3 on the slice users hit. Always read disagreement_report per slice (10A.5, 7.7 for the reverse trap too).
  • You tuned the rubric on the calibration set. That's training accuracy, not test accuracy — the reported κ is inflated. Keep calibration frozen; iterate on dev only (10A.5, 5.6).
  • The gate flakes. Small eval set + judge variance + no repeats = coin flips. Add repeats, use CI-based gating, and check infra_error vs task_error classification (10A.8, 2.5).
  • Judge scores drifted and nobody changed anything. Provider model updates under the same ID — that's why judge_version and the canary test set exist (10A.5, 6.3).
  • adjusted_pass_rate returns None or a wild number. TPR+TNR ≤ 1 means the judge is worse than chance on your labels — fix the judge before correcting anything (10A.5, 4.5).

Stretch (optional)

Stretch (optional): Agent eval harness with an online sampler#

Goal: Evaluate an agent — the Module 08A support/refund agent or the lesson's scripted personalities — as a trajectory through a world, not a text answer: outcome and trajectory graders, k trials per task, pass@k vs pass^k with intervals, cost per success; then close the loop with evalkit/online.py, a production-trace sampler with a fake judge and PSI drift alerts.

This pairs the module's two hardest eval targets: 10A.7 for agents and 10A.9 for what happens after release. Fully keyless: agent_eval.py runs scripted agents against the SupportWorld fake backend, and online.py runs on fixture traces with FakeJudge.

What you'll practise:

  • The four levels of agent grading — outcome, trajectory/process, step-level, safety/side-effects (lesson 10A.7, 1.2)
  • Simulated environments: deterministic fixtures, real tool surfaces, resettable state, the World/AgentFn seams (10A.7, 2.2–2.3, 2.4)
  • Outcome graders: state_is, state_check, answer_is, claims_supported and partial credit via weighted/all_of (10A.7, 3)
  • Trajectory metrics: tool_call_prf, redundant_calls, loop_detected, recovery_rate, step_efficiency, trajectory_align, required_order, no_denied_calls, within_budget (10A.7, 4)
  • Reliability: pass_at_k, pass_hat_k, wilson_interval, variance across seeds, cost per success (10A.7, 5)
  • The demo world: SupportWorld, scripted agent personalities, run_agent_suite, SuiteReport (10A.7, 2.5 and 10, 10)
  • Online evaluation: Trace, TraceJudge, sample_stratified, run_sample, summarize, distribution_drift, FakeJudge (lesson 10A.9, Part 7)
  • Drift detection with PSI and the feedback loop from production failure to regression case (10A.9, Parts 5–6, 6)

Setup: stdlib only — no packages beyond Python 3.11+:

bash
uv init evalkit --bare --python 3.13 && cd evalkit && mkdir evalkit
# copy evalkit/agent_eval.py, evalkit/agent_eval_demo.py (10.7) and evalkit/online.py (10.9)
# optional: evalkit/mm_metrics.py (10.7, 9.10), evalkit/trace_adapter.py + trace_demo.py (10.7, 10.4)
#   and grader_selftest.py (10.7, 5.5) — run each as `python3 evalkit/<file>.py`

Steps:

  1. Run the lesson's demo. Copy agent_eval.py and agent_eval_demo.py into evalkit/, run python3 evalkit/agent_eval_demo.py from the project root (its flat from agent_eval import ... resolves because Python puts the script's own folder on sys.path; python -m evalkit.agent_eval_demo would fail with No module named 'agent_eval'). Read the SuiteReport: per-task pass rates, pass@k vs pass^k, Wilson intervals, trajectory metrics, cost per success. Predict which scripted personality wins before reading the output.
  2. Read the world before extending it. Study SupportWorld (10A.7, 2.5): its tools, allowed() denials, state(), call_log, and reset(). Your extensions must preserve the resettable-state invariant — trial N+1 must not see trial N's mutations.
  3. Add tasks. Write 2–3 new Tasks to the suite: e.g. "look up order ORD-1003 status then email the customer" (tests orders_get + send_email ordering via required_order; the world's policy hook denies send_email unless the call carries approved=true, so decide whether your task expects that denial or the approved call), "refund a damaged item" (tests refunds_issue args via tool_call_prf). The world's tool names are orders_get, orders_list, tickets_create, refunds_issue, docs_search, send_email and get_time (see SupportWorld.tools() in 10A.7, 2.5), so a task that names any other tool fails with an unknown-tool error, and a task the lazy agent fails but the good one passes. Give each budgets and the right grader set.
  4. Add an agent personality. Write a new AgentFn — e.g. a "careful" agent that verifies state before acting, or a "tool-happy" one that calls redundant reads — following the scripted-agent pattern (_traj, _call, deterministic per seed). Register it in make_agent_factory's menu.
  5. Run k trials and read reliability. Run run_agent_suite(tasks, agent_for_trial, trials=8, seed=0) and compare pass@k vs pass^k per task — the gap between them is your flakiness (10A.7, 5.1). Widen trials to 16 and watch the Wilson intervals shrink.
  6. Sensitivity analysis. Re-run with a different AGENT_MIX or a tweaked task description; check whether pass^k moves more than the CI — that's prompt/tool-description sensitivity (10A.7, 5.3).
  7. Wire the live adapter (optional, needs keys). Follow 10A.7, 10.2: wrap your production agent loop so tool calls route through world.call_tool and each step lands in the Trajectory. Run one task live and compare its trajectory metrics to the scripted equivalent.
  8. Build the online sampler. Copy online.py and run python -m evalkit.online — 200 fixture traces, stratified sample, FakeJudge, score summary, PSI vs baseline. Then modify make_fixture_traces to reflect your agent's trace shape (route names, fields) and implement a real TraceJudge.__call__ behind the same seam when you have keys.
  9. Close the loop. Take the worst task's failing TrialRecord.trajectory, classify the failure (wrong tool? bad args? loop? policy violation?), write a Task regression case or a new grader for it, and re-run — the flywheel from 10A.9, 6.1 applied offline.
  10. Set the alert thresholds. Choose PSI bands for your score distribution (the lesson's 0.1/0.25 rule of thumb is a starting point, not a law — 10A.9, 5.2) and a pass-rate floor; document what action each band triggers.

Verify it, and what you should see:

bash
python3 evalkit/agent_eval_demo.py    # suite report, real output
python -m evalkit.online              # sampler + PSI, real output (online.py imports nothing from the package)

The online sampler's real output (from the lesson, abridged: the full run also prints median_score, label_counts and judge_versions):

text
production traces today: 200
sampled for judging:    21 ({'chat': 7, 'extract': 7, 'rag': 7})
== summary ==
  n_traces: 21
  n_judged: 20
  n_judge_errors: 1
  mean_score: 0.805
  pass_rate: 0.9
score-distribution PSI vs baseline: 0.081
rule of thumb: stable

Your agent suite report will differ but the fields are fixed: per-task TaskReport (pass rate, pass@k, pass^k, Wilson interval, mean steps/cost/tokens) and SuiteReport aggregates. The number that matters most is pass^k — pass@1 of 0.9 with pass^8 of 0.4 means most users hit a failure within 8 tries (10A.7, check-yourself).

Done when:

  • run_agent_suite runs your extended task suite with trials ≥ 8 and reports pass@k, pass^k and Wilson intervals per task.
  • At least one trajectory metric (tool_call_prf, loop_detected, recovery_rate or step_efficiency) produces a number you can interpret and act on.
  • You can name which scripted personality wins on which task and why (which grader fired), not just that it scored higher.
  • online.py samples, judges with FakeJudge, summarises and computes PSI — and you've documented your alert thresholds.
  • At least one production-style failure became a new eval case or grader (the loop closed once).

Stretch ideas:

  • Implement mm_metrics.py checks on agent outputs — wer/cer if the agent produces transcripts, timestamp_iou for event claims (10A.7, 9.10).
  • Add a simulated user (AgentFn that plays the customer) for a conversational task (10A.7, 6.1).
  • Sketch the tool-count scaling test: add distractor tools to SupportWorld.tools() at 10/50/200 and plot tool_call_prf's name_f1 vs f1 gap (10A.7, 7.5).
  • Hosted, needs keys: wire live_agent to a real provider and compare its trajectory metrics against the scripted agents on the same tasks — the honest "how close is the fake" check (10A.7, 10.2).

Optional extensions: memory, multi-agent systems, simulator validation and the framework track (10A.11 to 10B.17)#

These extend the same agent project and are optional, additive and keyless; extension E (DeepEval) is the recommended core extension of the framework track and extension D (Inspect) is optional (extensions D and E need only the track's fakes; the Docker-backed parts of D are flagged where they would need it). They are not separate projects: do one or more once the base harness works, and report them as extra sections of the same write-up. Each reuses agent_eval.py (plus compare.py and judge_validation.py from 10A.8 and 10A.5), so copy those beside the new files first.

Extension A: a multi-session memory suite (10A.11)

Deliverables:

  • memory_eval.py and memory_eval_demo.py copied from 8.1 and 8.2, and a run of the clean and buggy systems side by side (8.3).
  • Three scenarios of your own for your agent's domain, written with the write-policy case grid (3.3): at least one preference update, one TTL expiry and one injected-instruction case.
  • Write and read quality reports for them (fact-level F1, silent duplicates; recall, precision, staleness and an abstention probe), and a staleness probe that asks after the clock has advanced (4.2).
  • A canary leakage probe: per-subject canaries seeded for two users, a cross-user probe, and the zero-event upper bound reported with its leak-eligible denominator (5.3, 5.6).
  • A compaction probe set (verbatim IDs, one constraint, one decision) run through two strategies (6.9).
  • Optional: point memory_store_adapter.py at 08B.2's MemoryStore (8.5) with the fake-clock fix from 7.3, and gate it with test_memory_gates.py (8.6).

Acceptance criteria: the self-test (8.4) lights up the expected signal for every bug you plant; the leak report states n_eligible and the bound rather than "0 leaks"; every compaction number is paired against the uncompressed run.

Pitfalls: a probe that passes under the no-memory condition does not test memory; reading the wall clock inside the system under test makes TTL tests meaningless; counting probes that could never leak inflates the zero-leak claim.

Extension B: a multi-agent extension (10A.12)

Deliverables:

  • mas_eval.py and mas_eval_demo.py from 2.4 onward (assembled per 9.3), and the 08D.3 event log converted with trace_from_events (2.5).
  • Handoff grading on at least eight gold tasks: the routing confusion matrix including "no handoff" and "human", context-transfer completeness graded on what the receiver saw, and ping-pong, cycle and return-path checks (Part 3).
  • Counterfactual attribution for failed runs with at least one trivial baseline (last-step) beside it, and an attributor-accuracy number (4.4, 4.7).
  • An equal-budget single-agent baseline compared with paired statistics, plus the overhead distributions (token multiplier, effective parallelism, latency speed-up, cost per successful task) (6.2, 5.2).

Acceptance criteria: the baseline gets the same token budget as the multi-agent system (equal_budget_check passes); results are reported as p50/p95 and paired intervals, not means; at least one failure is attributed by replay and the attribution is compared with a human label.

Pitfalls: comparing a multi-agent run to a single agent with a smaller budget; reading blame from the last step of the trace; averaging latency when one straggler dominates the tail.

Extension C: validate your user simulator (10A.12, Part 7)

Deliverables:

  • sim_validation.py and sim_validation_demo.py (7.10, 7.15, 7.16).
  • A small set of real or hand-written human conversations for your agent's domain, converted to Conversation objects, and a realism report against a real-versus-real noise floor (7.5).
  • Leakage with the unhelpful-user and no-user controls (7.8) and a termination report (7.9).
  • Predictive validity: do three agent variants rank the same under the simulator as under your human conversations (7.12)? Finish with the validity card.

Acceptance criteria: the card reports a rank correlation with its bootstrap interval and says PASS, PROVISIONAL or WARN accordingly; you state how many human conversations you used and what 7.13 says that supports.

Pitfalls: validating realism on turn statistics alone while ranking is wrong; a simulator that volunteers the goal before it is asked; treating a point estimate above the threshold as a pass when the lower interval bound is below it.

Extension D (optional, Inspect): an Inspect agent eval with a sandbox, limits and pass@k (10B.14, 10B.15, 10B.16)

Deliverables:

  • The support desk as Inspect tools and a react() agent (10B.14, 1.5, 6.2), run on mockllm/model with scripted tool calls, and unit tests for each tool before the agent exists (2.10).
  • A sandbox (one per sample) holding the world state, a final-state scorer that checks the outcome there instead of the agent's prose (10B.15, 6.2, 6.5). Docker is only needed to run it for real: the keyless path is the scorer's unit tests and the tool tests, and you must say in the write-up which parts did not run.
  • Limits set on purpose (10B.15, 7.1, 7.11) and stop reasons separated before any accuracy is read (11.3).
  • epochs with the pass_at_k and pass_k_k reducers and a hand check of both formulas (10B.10, Part 7, 10B.16, Part 4), reconciled with the Wilson intervals your run_agent_suite already reports.
  • Trajectory read from log events, not messages (10B.16, Part 2), and a tuned react() baseline beside any multi-agent or deepagent() variant (10B.14, 6.5).

Acceptance criteria: every reported number states its limits and epochs; samples that hit a limit or errored are counted separately from wrong answers; the sample standard error is reported with what it does and does not cover (10B.10, Part 8); the CI gate checks the log status as well as the exit code (10B.12, Part 13).

Pitfalls: retries inside react() are not epochs; the call that crosses a token or turn limit is made and discarded; a scorer that reads the final message passes an agent that only said it finished; inspect eval exits 0 when samples errored.

Extension E (recommended core extension, DeepEval): a DeepEval traced-agent eval in CI (10B.5, 10B.7, Part 2)

Deliverables:

  • The agent instrumented with @observe and update_current_span / update_current_trace (10B.5, Part 2, Part 3), evaluated end to end and at component level with evals_iterator (10B.5, 5.1) using deterministic tool metrics first (10B.5, Part 10) and the scripted FakeJudge for any judged metric.
  • A pytest suite with traced assert_test(golden=...) run by deepeval test run, and a check that catches span-only failures the console table hides (10B.7, 2.4, 10B.5, 5.5).
  • A GitHub Actions workflow that runs the keyless suite on every pull request and stores the run artifact (10B.7, 2.7), plus a regression diff against the artifact of the previous run, since DeepEval has no local baseline command (2.8).
  • A mapping of your DeepEval agent results onto the evalkit trajectory graders you already have, listing what DeepEval scores and what it cannot (handoffs, 10B.5, 13.2).

Acceptance criteria: the job fails when a span-level metric fails and when no test case was collected; with -n workers the case count in the summary is checked (10B.7, 2.5); no step needs a Confident AI key, and DEEPEVAL_TELEMETRY_OPT_OUT=1 is set; every agent-metric threshold you chose is justified against labelled cases (10B.5, 14.3).

Pitfalls: a trace-aware judge is not reference-aware (10B.5, 8.4); spans that cross an asyncio or thread boundary land in the wrong trace; a metric that passes when no plan is visible (10B.5, 9.4); reading a green CI run as proof when no case was collected.

Common problems:

  • pass^k looks terrible but the agent "works". pass^k is the probability all k trials succeed — with k=8 even a 90%-per-trial agent scores ~0.43. Report both, and check whether failures cluster on one task or spread evenly.
  • Trajectory metrics all zero. Your StepRecords aren't being recorded — the agent must call world.call_tool, not the raw tool functions, or the trajectory is empty and graders see nothing.
  • world.reset() doesn't restore side channels. Sent emails and audit logs persist across trials — pass rates become meaningless. Check reset() covers every mutation channel (10A.7, 2.2).
  • The "reckless" agent passes outcome graders. Outcome and trajectory are separate levels — a lucky-but-wrong path still reaches the right end-state. Add no_denied_calls/tool_unused trajectory graders (10A.7, 1.2).
  • PSI fires on a tiny sample. distribution_drift on 20 judged traces is noise — stratified sampling helps but small routes still produce few points; widen the sample or widen the bucket count before acting (10A.9, 5.2).
  • Judge errors crash the sampler. run_sample records judge failures as n_judge_errors rather than aborting — that's by design; check the count, don't treat it as a quality signal.

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