Evaluation against demos: graders, sets and regressions
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Implement an eval runner that applies deterministic graders over a case set and reports counts, not just a rate.
- Write graders that encode grounding and abstention contracts, and detect a grader that passes everything.
- Explain model-judge biases and why small targeted eval sets still earn their place in CI.
Overview
#A demo is an anecdote; an evaluation is a measurement
The most expensive sentence in AI engineering is "it worked when I tried it." A demo exercises one input on one day with one model state. An evaluation applies a fixed set of inputs with defined expectations and produces a number you can compare across time, prompts, models and prompt-injection defenses. Everything else in this course, mocks, grounding, budgets, boundaries, becomes trustworthy only when something measures it.
Anatomy of an eval set
Each case has three parts: an input, an expectation, and a grader. Graders come in two families:
- Deterministic graders: exact string match, schema validation, required citation pattern, exact abstention sentinel. Cheap, stable, perfect for CI.
- Model-graded: a second model scores a rubric (tone, helpfulness, faithfulness). Useful for qualities code cannot check, but the judge itself has biases: position bias (favoring an answer by where it appears), verbosity bias (favoring longer answers), and self-preference (favoring its own style). Use rubrics, swap judge models, and spot-check judgments by hand.
const GRADERS = {
exact: (output, c) => output === c.expected,
citesSource: (output) => /\[\d\]/.test(output),
abstains: (output) => output === "NOT_IN_SOURCES"
};
The citesSource grader encodes lesson 9's grounding contract; abstains encodes its honesty contract. Neither needs a model to run, which is exactly what makes them regression-proof.
Running the set
function runEvalSet(cases, task) {
const results = cases.map((c) => ({
id: c.id,
passed: GRADERS[c.grader](task(c.input), c)
}));
const passed = results.filter((r) => r.passed).length;
return {
passed,
failed: results.length - passed,
rate: passed / results.length,
results
};
}
With a five-case set where one answer lost its citation, the result is { passed: 4, failed: 1, rate: 0.8 }. Report the counts alongside the rate: four out of five carries very different uncertainty than four thousand out of five thousand, and a rate alone hides that. Small targeted sets are still valuable; a twenty-case set that covers your known failure modes catches more real regressions than a vague thousand-case set nobody maintains.
What belongs in the set
- Happy paths: the cases your demo already shows.
- Edge contracts: unanswerable questions that must produce
NOT_IN_SOURCES, outputs that must parse and validate (lesson 5), truncated generations. - Historical failures: every production bug becomes a permanent case.
- Red-team cases: injection payloads through retrieved chunks and tool results (lesson 12), with expected refusal behavior.
- Format and safety checks: citation presence, no canary strings in output, no PII leakage.
Evaluation is a pipeline stage, not a milestone
Run the suite on every prompt change, model upgrade, retrieval tweak and parameter change, in CI, with failures blocking merge the way unit test failures do. When a case fails, the transcript (lesson 11) tells you where it broke: retrieval miss, misread, validation failure or grader bug. Grader bugs are real; when a grader is wrong, fix the grader and add a case that would have caught the bug.
Two honest limitations to keep in view. First, an eval set measures what it contains; a feature can pass every case and still fail on inputs you never imagined, so coverage grows from production traffic review. Second, models and usage drift: a passing score last quarter is not a passing score today, which is why the suite runs continuously rather than once.
Continue with ai-engineering-uncertainty-and-calibration to measure how confident your system should be allowed to sound.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement runEvalSet(cases, task): for each case, call task(c.input), apply GRADERS[c.grader], and collect { id, passed }. Return { passed, failed, rate, results } where rate is passed divided by total.
starter.javascriptconst GRADERS = { exact: (output, c) => output === c.expected, citesSource: (output) => /\[\d\]/.test(output), abstains: (output) => output === "NOT_IN_SOURCES" }; const EVAL_SET = [ { id: "e1", input: "How do I reset my password?", grader: "citesSource" }, { id: "e2", input: "How do I reset my password?", grader: "citesSource" }, { id: "e3", input: "What is the refund policy?", grader: "abstains" }, { id: "e4", input: "What is the refund policy?", grader: "abstains" }, { id: "e5", input: "How do I reset my password?", grader: "citesSource" } ]; function mockRagTask(input) { // Scripted: cited answers normally, exact abstention for refunds, // and a regression on the fifth call: an uncited answer. mockRagTask.n = (mockRagTask.n || 0) + 1; if (input.includes("refund")) return "NOT_IN_SOURCES"; if (mockRagTask.n === 5) return "Open Settings and choose Security."; return "Open Settings, choose Security, then Reset password. [1]"; } function runEvalSet(cases, task) { // For each case: output = task(c.input); passed = GRADERS[c.grader](output, c). // Return { passed, failed, rate, results }. } const run = runEvalSet(EVAL_SET, mockRagTask); console.log(JSON.stringify({ passed: run.passed, failed: run.failed, rate: run.rate }));Reveal the reference answer
reference.javascriptconst GRADERS = { exact: (output, c) => output === c.expected, citesSource: (output) => /\[\d\]/.test(output), abstains: (output) => output === "NOT_IN_SOURCES" }; const EVAL_SET = [ { id: "e1", input: "How do I reset my password?", grader: "citesSource" }, { id: "e2", input: "How do I reset my password?", grader: "citesSource" }, { id: "e3", input: "What is the refund policy?", grader: "abstains" }, { id: "e4", input: "What is the refund policy?", grader: "abstains" }, { id: "e5", input: "How do I reset my password?", grader: "citesSource" } ]; function mockRagTask(input) { mockRagTask.n = (mockRagTask.n || 0) + 1; if (input.includes("refund")) return "NOT_IN_SOURCES"; if (mockRagTask.n === 5) return "Open Settings and choose Security."; return "Open Settings, choose Security, then Reset password. [1]"; } function runEvalSet(cases, task) { const results = cases.map((c) => ({ id: c.id, passed: GRADERS[c.grader](task(c.input), c) })); const passed = results.filter((r) => r.passed).length; return { passed, failed: results.length - passed, rate: passed / results.length, results }; } const run = runEvalSet(EVAL_SET, mockRagTask); console.log(JSON.stringify({ passed: run.passed, failed: run.failed, rate: run.rate }));Authored expected output: {"passed":4,"failed":1,"rate":0.8}
The scripted task answers with citations on cases 1, 2 and 5's input, abstains on the refund cases, but its fifth call returns an uncited answer, so exactly one case fails. Counts and rate are both reported because 4 of 5 and 4000 of 5000 are different evidence.
Exercise 2Test
Write four assertions for the graders: citesSource passes an answer containing [1] and fails one without; abstains passes exactly NOT_IN_SOURCES and fails the lowercase phrase not in sources.
starter.javascriptfunction check(label, condition) { console.log(condition ? "PASS" : "FAIL"); } // Write four assertions: // 1. citesSource("Open Settings, choose Security, then Reset password. [1]") is true. // 2. citesSource("Open Settings, choose Security, then Reset password.") is false. // 3. abstains("NOT_IN_SOURCES") is true. // 4. abstains("not in sources") is false.Reveal the reference answer
reference.javascriptfunction check(label, condition) { console.log(condition ? "PASS" : "FAIL"); } check("citation present passes", /\[\d\]/.test("Open Settings, choose Security, then Reset password. [1]")); check("citation missing fails", !/\[\d\]/.test("Open Settings, choose Security, then Reset password.")); check("exact sentinel passes", "NOT_IN_SOURCES" === "NOT_IN_SOURCES"); check("near-miss abstention fails", "not in sources" !== "NOT_IN_SOURCES");Authored expected output: PASS PASS PASS PASS
The abstention grader is deliberately exact-string: near-miss phrases must fail so the sentinel stays machine-checkable. These assertions pin the contracts that lesson 9 promised.
Exercise 3Debug
weakGrade passes any non-empty output, so a fabricated answer passes alongside a good one. Predict the two logged lines for the weak grader, then implement fixedGrade(output, unanswerable) that requires a citation for answerable cases and the exact sentinel for unanswerable ones, and predict its three logged lines.
starter.javascriptfunction weakGrade(output) { return output.length > 0; } const hallucinated = "Our refund policy allows 90-day returns."; const good = "Open Settings, choose Security, then Reset password. [1]"; console.log(String(weakGrade(hallucinated))); console.log(String(weakGrade(good))); function fixedGrade(output, unanswerable) { // Answerable cases require a [number] citation. // Unanswerable cases require exactly NOT_IN_SOURCES. } console.log(String(fixedGrade(hallucinated, false))); console.log(String(fixedGrade(good, false))); console.log(String(fixedGrade("NOT_IN_SOURCES", true)));Reveal the reference answer
reference.javascriptfunction weakGrade(output) { return output.length > 0; } const hallucinated = "Our refund policy allows 90-day returns."; const good = "Open Settings, choose Security, then Reset password. [1]"; console.log(String(weakGrade(hallucinated))); console.log(String(weakGrade(good))); function fixedGrade(output, unanswerable) { if (unanswerable) return output === "NOT_IN_SOURCES"; return /\[\d\]/.test(output); } console.log(String(fixedGrade(hallucinated, false))); console.log(String(fixedGrade(good, false))); console.log(String(fixedGrade("NOT_IN_SOURCES", true)));Authored expected output: true true false true true
The weak grader returns true for both the fabricated and the grounded answer, which is how eval suites come to pass everything. The fixed grader rejects the uncited fabrication (false), accepts the cited answer (true), and accepts the exact sentinel for the unanswerable case (true). A grader that cannot fail is not a measurement.
Exercise 4Interview
Interview question: your team built a RAG assistant over internal docs. Design the evaluation you would require before rollout and the one you would keep running after.
Reveal the reference answer
reference.textA strong answer covers: (1) Set construction: happy-path questions with known source chunks, unanswerable questions that must return NOT_IN_SOURCES, historical support tickets that became bugs, and a red-team set of injection payloads hidden in documents. (2) Graders: deterministic first, citation required for answerable cases, exact sentinel for abstention, schema validation for any structured fields; model-graded rubrics only for tone and completeness, with judge-bias mitigations and hand spot-checks. (3) Retrieval metrics alongside answer metrics: recall over which chunk should be retrieved, so retrieval misses are distinguishable from generation misreads. (4) Process: the suite runs in CI on every prompt, model and retrieval change; failures block merge; each production incident becomes a permanent case. (5) Honesty: report counts with rates, keep coverage limitations explicit, and never present a demo as evaluation. Weak answers rely on vibes, a single demo, or an unexamined LLM judge.Authored expected output: A structured evaluation plan with case construction, deterministic-first graders, retrieval metrics, CI gating and honest reporting
The question tests whether the candidate separates anecdotes from measurements and can encode product contracts as graders.
Exercise 5Explain
Knowledge check: which statement about LLM-as-judge evaluation is true?
starter.text// Choose the correct option.Reveal the reference answer
reference.textModel judges are useful for rubric-based qualities but carry measurable biases: position bias, verbosity bias and self-preference. Mitigate with explicit rubrics, judge rotation and hand spot-checks, and keep deterministic graders as the backbone of the suite.Authored expected output: Judges are useful but biased; rubrics, rotation and spot-checks are required
Judging with a model imports a second source of nondeterminism and bias into your measurement; treat it as an instrument that itself needs calibration.
Common misconceptions
#- Myth: a good demo means the feature works. Fact: a demo is one input on one day; only a fixed case set with graders produces a comparable measurement.
- Myth: LLM judges are objective. Fact: judges show position, verbosity and self-preference biases; use rubrics, rotate judges and spot-check by hand.
- Myth: evals are useless until they are huge. Fact: a small set that covers known failure modes and historical bugs catches most real regressions; grow it from production traffic.
Follow-up practice
#- ai-engineering-uncertainty-and-calibration
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.