Module 10A: 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 (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: 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.pyharness:RagCase,StageRun, theRAGPipelineprotocol,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:
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 projectCopy 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:
- Verify the bot still answers. Run the Module 07 starter's
ask.py(orsmoke.py) on two questions — one answerable, one out-of-corpus — and confirm the abstention flag and citation check counts print. Everything downstream assumesdocs_qa'sgenerate_answer,Retriever.searchandFakeLLMwork. - Produce the question set. Write
export_chunks.pythat readscorpus.CHUNKSand emits the five-field shapesynth_eval.pyexpects (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 itseval_questions.jsonl; otherwise copysynth_eval.pyandquestion_model.py/gen_questions_prompt.txtfrom 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 iseval_questions.jsonlwithid,question,question_type,reference_answer,answerable,cited_chunk_ids,evidence_span,persona,language,generator,prompt_version. - Convert to
rag_cases.jsonl. Writemake_rag_cases.pythat maps each item to theRagCaseschema (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, andpersona/language/generator→source/notes. Deriveexpected_factsornuggetswhere the reference answer has separable claims (a refund policy answer might need "30 days" and "manager approval" as two nuggets). Assignsplit— roughly 80%dev, 20%test, stratified byquestion_typeso both splits cover every type, and by document, not by row: all questions generated from the samedoc_id(or chunk) go to the same split, otherwise tuning ondevleaks intotest(10A.2, 6.7); tune only ondev. - Hand-write the cases synthetic data can't give you. Append ~8 cases by hand to
rag_cases.jsonlcovering what the generator won't produce: 2expect_abstainunanswerable questions (office wifi password; something only another tenant's contract answers, withfilters={"tenant": "acme"}), 1 adversarial case whose "document" text contains an instruction-like phrase, 1 multi-hop case withnuggetsspanning two chunks, 1 ACL-leak case, 1 chit-chat case, and 1partial_okcase. This is the representativeness-vs-coverage lesson from 10A.2, 2.8 applied. - Build the chunks map. Write
chunks_map.json(or build it in code) mapping everychunk_idto{"chunk_id", "text", "metadata"}—rag_eval.py'sChunkneeds the text for quote verification and the metadata for judge context and ACL fields. Load it once and passchunks=torun_rag_eval. - Write the pipeline adapter. Create
docsqa_pipeline.pyimplementing theRAGPipelineprotocol —run(case, oracle="none") -> StageRun— following 10A.6, 5.4 but with realdocs_qaimports:retriever= the hybrid retriever overCHUNKS(fromretrievers.py+docs_qa.retrieval.PRESETS, as in the 07 starter),llm= yourFakeLLM, generation viadocs_qa.generate.generate_answer. Implement the fouroraclemodes:"none"(raw question → retrieve → generate),"query"(same — the docs_qa planner already rewrites; note the difference honestly),"retrieval"(skip retrieval, feedgold_chunk_idschunks to the generator),"assembly"(real retrieved set with a hugebudget_tokens). MapGenerationResultfields ontoStageRunexactly as the lesson's adapter does —retrieved_idsbefore oracle substitution,context_idsfromctx.kept + ctx.truncated,cited_ids/cited_quotesparallel fromga.evidence,abstainedfromstatus in {"abstained", "needs_clarification"},answer_partialfromstatus == "partial",sufficiencyfromcoverage_score, latency and token counts filled in. - Run end to end, deterministically first. Write
run_rag_eval.pythat loads cases + chunks, buildsDocsQaPipeline, callsrun_rag_eval(cases, pipeline, judge=ScriptedJudge(...), chunks=chunks_map, out_path="rag_results.jsonl", run_meta={...}), then printsreport_markdown(results, title=..., bound=bound_analysis(e2e, oracle_retrieval)). Start withScriptedJudge— its canned scores prove the plumbing; the deterministic columns (token-F1, citation F1, abstention accuracy, flags) are the real signal. - Run the oracle experiments. Re-run with
oracle="retrieval"andoracle="assembly"on the same cases, thenbound_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). - Add a judge — carefully. Swap
ScriptedJudgeforLLMJudgewrapping an injectablellmcallable: keylessly that's yourFakeLLMorevalkit.judges.FakeCallModel(plumbing check only — a fake judge's scores mean nothing about quality); with keys, use a provider call throughevalkit.judges.rubric_judgewith a different model family than the generator, per 10A.4, 5.2. Recordjudge_versioninrun_meta. - Compare two configurations. Change one thing — retriever preset (
densevshybrid), contextk(4 vs 8), or the grounding prompt — run both, and callcompare_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). - Grow the set honestly. Feed the worst slice from your report back into
rag_cases.jsonlas new cases — the flywheel from 10A.2, Part 7. Re-rundedupefromdataset.pyif you addedevalkit/dataset.py, and confirm no case leaked into a prompt's few-shot examples.
Verify it, and what you should see:
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 tableThe 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.
## 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.625What 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.jsonlloads throughload_rag_caseswith a dataset SHA, covers every question type you generated plus your hand-written edge cases, andsplitassignments keeptestuntouched until the end.run_rag_evalproducesrag_results.jsonland 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(orcompare_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
ScriptedJudgefor a realLLMJudgeviaevalkit.judges.rubric_judgewith 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
turnsand 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_curveoutput and re-run — watch the 2×2 move (10A.6, 3.5). - Run
nonfunctional.py'sperturbation_suiteover your questions and measure the pass-rate delta per perturbation type (10A.10, 6.3). - Render the report through
evalkit/report.py'srender_reportfor 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.jsonlrows (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
stderrversusevalkit'srag_eval.pyaggregates), 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_idsdon't match the corpus. The synthetic set was generated over a different chunk file —citation_prfandcontext_diffssilently score zero. Check that everygold_chunk_idsvalue exists in yourchunks_map; regenerate or drop cases whose chunks aren't indocs_qa.- Everything abstains or nothing does.
expect_abstainmaps fromanswerable == false— check your converter didn't invert it, and thatgenerate_answer's sufficiency gate is actually wired (min_coverageset, 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_idson the oracle run to confirm gold chunks actually entered the prompt. - Judge scores look great but mean nothing.
FakeCallModel/ScriptedJudgereturn canned verdicts — they prove plumbing, not quality. Only trust judge columns after validating against human labels (the stretch project below). - The report's
split:testrow is empty or tiny. Stratify byquestion_typewhen assigning splits — a random 80/20 on a skewed synthetic set can leave a whole type in dev only. retrieved_not_contextflags everywhere. Your adapter recordsretrieved_idsbefore oracle substitution butcontext_idsafter assembly — if the context budget trims aggressively, retrieval "succeeded" while the model never saw the chunk. That's a real finding, not a bug; checkbudget_tokensingenerate_answer.
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:
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-dotenvCopy 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:
- 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 intooutputs.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.1triage_eval.pyFakeTriageModeloutputs plus hand-varied ones; the point is a fixed, versioned set of outputs to grade. - Write the labelling sheet. Create
labels_template.csvwith columnsexample_id,input,output,human_label,notesand aLABEL_GUIDE.mdwith 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. - Convert labels to
Judgementrecords. Writemake_judgements.pythat emitsJudgement(example_id=..., human=..., judge=..., slice_=...)objects — start withjudge=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. - Build the judge. Write
judge_setup.pyconstructing aRubricwith anchoredRubricCriterions (10A.4, 3.2) and acall_model:FakeCallModelfirst 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 pinjudge_version= prompt version + model ID. - Run the judge and measure agreement. Write
validate_judge.pythat runsrubric_judgeover the dev+calibration cases, maps verdicts toJudgement.judge, then printsraw_agreement,cohens_kappa,tpr_tnr,fail_detection,disagreement_reportandagreement_ciper slice. Expect κ in the 0.4–0.7 range on a first rubric — that is normal; the iteration loop is the work. - 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). - Compute the corrected pass rate. Using calibration
tpr_tnr, runadjusted_pass_rateandcorrected_rate_cion 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. - Build the judge test set. Freeze ~20 cases with known verdicts as
judge_test_setcanaries (10A.5, 6.1); wire them to run whenever the judge prompt or model changes. - Wire the CI gate. Write
gate_eval.pythat runsrun_suite(10A.8, 4.2) over your eval cases with the judge as a scorer, stores results viasave_run, and callsevaluate_gatewithGateThresholds— an absolute floor on the judge pass rate plus a relative non-regressionmax_dropwith tolerance, and per-slice floors if a slice matters (10A.8, 1.3, 10A.8, 10.1). Wrap it inevalkit/cli.py'sgatecommand shape so CI calls one command (the CLI's own flags arerun --cases/--task/--scorer/--cost-of/--max-calls/--max-cost-usdandgate --run/--baseline/--metric/--min-overall/--max-drop/--min-cases/--slice-dim/--slice-floor; the metric name is the scorer function's__name__). Pass aBudget(max_calls=..., max_cost_usd=..., cost_of=...)torun_suiteso a bad run cannot overspend (10A.8, 3.5): it is thread-safe, and itscallscount includes calls that raised. - 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_cifor the A-vs-B comparison (10A.5, 7.4, 10A.8, 2.3). - 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. - 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:
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 subsetThe 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):
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.33and the gate:
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: PASSWhat 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.pyprints 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_versionis stamped on every verdict. gate_eval.pypasses 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_judgevariant for comparing prompt A vs B directly, with order-swapping (swap=True) andswapped_agreeconsistency checks (10A.4, 2.2, 4.1). - Try
jury_judgewith 3call_models and inspectspreadon 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/CallCacheso 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
FakeCallModelfor 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
GEvalmetric (the recommended core extension) and, optionally, through Inspect'smodel_graded_qa(), wrapped so thatvalidate_judge.pycan 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_reportper 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 checkinfra_errorvstask_errorclassification (10A.8, 2.5). - Judge scores drifted and nobody changed anything. Provider model updates under the same ID — that's why
judge_versionand the canary test set exist (10A.5, 6.3). adjusted_pass_ratereturnsNoneor 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): 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/AgentFnseams (10A.7, 2.2–2.3, 2.4) - Outcome graders:
state_is,state_check,answer_is,claims_supportedand partial credit viaweighted/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+:
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:
- Run the lesson's demo. Copy
agent_eval.pyandagent_eval_demo.pyintoevalkit/, runpython3 evalkit/agent_eval_demo.pyfrom the project root (its flatfrom agent_eval import ...resolves because Python puts the script's own folder onsys.path;python -m evalkit.agent_eval_demowould fail withNo module named 'agent_eval'). Read theSuiteReport: 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. - Read the world before extending it. Study
SupportWorld(10A.7, 2.5): its tools,allowed()denials,state(),call_log, andreset(). Your extensions must preserve the resettable-state invariant — trial N+1 must not see trial N's mutations. - Add tasks. Write 2–3 new
Tasks to the suite: e.g. "look up order ORD-1003 status then email the customer" (testsorders_get+send_emailordering viarequired_order; the world's policy hook deniessend_emailunless the call carriesapproved=true, so decide whether your task expects that denial or the approved call), "refund a damaged item" (testsrefunds_issueargs viatool_call_prf). The world's tool names areorders_get,orders_list,tickets_create,refunds_issue,docs_search,send_emailandget_time(seeSupportWorld.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 eachbudgetsand the right grader set. - 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 inmake_agent_factory's menu. - Run k trials and read reliability. Run
run_agent_suite(tasks, agent_for_trial, trials=8, seed=0)and comparepass@kvspass^kper task — the gap between them is your flakiness (10A.7, 5.1). Widentrialsto 16 and watch the Wilson intervals shrink. - Sensitivity analysis. Re-run with a different
AGENT_MIXor a tweaked task description; check whether pass^k moves more than the CI — that's prompt/tool-description sensitivity (10A.7, 5.3). - Wire the live adapter (optional, needs keys). Follow 10A.7, 10.2: wrap your production agent loop so tool calls route through
world.call_tooland each step lands in theTrajectory. Run one task live and compare its trajectory metrics to the scripted equivalent. - Build the online sampler. Copy
online.pyand runpython -m evalkit.online— 200 fixture traces, stratified sample,FakeJudge, score summary, PSI vs baseline. Then modifymake_fixture_tracesto reflect your agent's trace shape (route names, fields) and implement a realTraceJudge.__call__behind the same seam when you have keys. - Close the loop. Take the worst task's failing
TrialRecord.trajectory, classify the failure (wrong tool? bad args? loop? policy violation?), write aTaskregression case or a new grader for it, and re-run — the flywheel from 10A.9, 6.1 applied offline. - 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:
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):
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: stableYour 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_suiteruns your extended task suite withtrials ≥ 8and reports pass@k, pass^k and Wilson intervals per task.- At least one trajectory metric (
tool_call_prf,loop_detected,recovery_rateorstep_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.pysamples, judges withFakeJudge, 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.pychecks on agent outputs —wer/cerif the agent produces transcripts,timestamp_ioufor event claims (10A.7, 9.10). - Add a simulated user (
AgentFnthat 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 plottool_call_prf'sname_f1vsf1gap (10A.7, 7.5). - Hosted, needs keys: wire
live_agentto 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.pyandmemory_eval_demo.pycopied 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.pyat 08B.2'sMemoryStore(8.5) with the fake-clock fix from 7.3, and gate it withtest_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.pyandmas_eval_demo.pyfrom 2.4 onward (assembled per 9.3), and the 08D.3 event log converted withtrace_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.pyandsim_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
Conversationobjects, 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 onmockllm/modelwith 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).
epochswith thepass_at_kandpass_k_kreducers and a hand check of both formulas (10B.10, Part 7, 10B.16, Part 4), reconciled with the Wilson intervals yourrun_agent_suitealready reports.- Trajectory read from log events, not messages (10B.16, Part 2), and a tuned
react()baseline beside any multi-agent ordeepagent()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
@observeandupdate_current_span/update_current_trace(10B.5, Part 2, Part 3), evaluated end to end and at component level withevals_iterator(10B.5, 5.1) using deterministic tool metrics first (10B.5, Part 10) and the scriptedFakeJudgefor any judged metric. - A pytest suite with traced
assert_test(golden=...)run bydeepeval 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
evalkittrajectory 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 callworld.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. Checkreset()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_unusedtrajectory graders (10A.7, 1.2). - PSI fires on a tiny sample.
distribution_drifton 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_samplerecords judge failures asn_judge_errorsrather than aborting — that's by design; check the count, don't treat it as a quality signal.