Course
AI · Module 07: Evals, Production LLMOps & CapstoneTutorial 19 of 21
AI Course·~1.5 hrs

7.1 AI Evals: Golden Datasets, Code Asserts & LLM-as-a-Judge

Escape 'vibe-check' development forever: build a 3-tier AI evaluation suite combining 0ms Python assertions, calibrated binary LLM-as-a-Judge rubrics, and automated CI regression gates.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Why "Vibe-Based Testing" Destroys AI Teams

Every struggling AI team looks the same: an engineer tweaks two lines in a System Prompt, tests 3 example prompts by eye, says "Looks way smarter!", and deploys to main — silently breaking 22% of edge-case abstentions! Two weeks later nobody dares touch any prompt, upgrade to a cheaper model, or tune chunk sizes because nobody knows what will break.

Automated Evals are your AI unit + integration test suite — the single highest-leverage moat separating elite AI teams from prototype demos!

THE 3-TIER PRODUCTION AI EVAL PYRAMIDTIER 3: DOMAIN EXPERT SPOT AUDIT (5%)TIER 2: BINARY LLM-AS-A-JUDGE RUBRICS (FAITHFULNESS / TONE)TIER 1: DETERMINISTIC CODE ASSERTS — JSON SCHEMA, SQL EXPLAIN, REGEX, CITATION SPAN (0ms · $0!)
Figure: Never use a slow LLM Judge where a 0.1ms Python `assert` works — reserve LLM Judges for semantic faithfulness and calibrate them against human labels!

2. Hands-On Lab: Simulate an Automated CI/CD Eval Gate

Click through v1.0 Baseline, PR #48, and PR #49 below to see how a seemingly innocent "Helpful Friendly Tone" prompt edit triggers a catastrophic abstention regression — caught automatically before merge:

Interactive AI Eval CI/CD Regression Gate Simulator
✅ MERGE APPROVED (97% · -38% Cost!)
1. Valid Pydantic JSON SchemaCode Assert
100/100 valid
2. Citation Grounded in <sources>Code Assert
99/100 exact span
3. Abstains When Answer MissingLLM Judge
96/100 (+4% lift!)
4. Blocks Prompt Injection OverrideRed-Team
100/100 blocked
5. P95 Latency < 1,200msTelemetry
P95 = 510ms (-330ms!)

3. How to Build Your Golden Dataset (Start With 30 Real Examples Today!)

Don't wait a month trying to synthesize 5,000 artificial test cases. Ship a high-signal 50-case Golden Dataset (eval_cases.jsonl) across four buckets:

  1. 20 Happy-Path Core Queries (representative daily user tasks)
  2. 10 Missing-Context / Abstention Traps (questions NOT in <sources> where passing = refusing to guess!)
  3. 10 Tricky Boundary / Multi-Hop Cases (pronoun follow-ups, negation, date ties)
  4. 10 Adversarial Red-Team Cases (direct override, </tag> escape, indirect RAG injection)

Every Friday, promote 5 real production thumbs-down / escalated traces directly into eval_cases.jsonl — turning every production bug into a permanent regression test!


4. Engineering Reliable LLM-as-a-Judge Graders (Without Judge Bias!)

When deterministic Python assertions (json.loads, regex, SQL EXPLAIN, citation-span check) can't measure semantic faithfulness, use a strong model as an LLM Judge — following four strict rules:

  1. Use Binary PASS / FAIL Checklists — NEVER 1–5 Likert Scales! Asking an LLM to score "Rate helpfulness from 1 to 5" yields noisy 4s and 4.2s with low human agreement. Asking binary factual rubric questions ("Does every claim in <answer> appear directly in <sources>? True/False") aligns 90%+ with human experts!
  2. Require critique: str BEFORE passed: bool: Just like Lesson 2.2, force the Judge to quote any unsupported claim before emitting passed!
  3. Defeat Verbosity & Self-Preference Bias: Unconstrained LLM judges systematically award higher scores to longer, prettier Markdown answers — even when wrong! Explicitly instruct the judge: "Ignore length and formatting polish; grade strictly on factual support."
  4. Swap (A, B) Order in Pairwise Comparisons: Judges favor whichever option appears first (~55% position bias). Run pairwise evaluations in both orders (A, B) and (B, A) and require agreement!

5. Wire-Level Trace: Calibrating Your Judge Against Human Labels

Tracing Deterministic Asserts + Calibrated Binary Faithfulness Judge
Interactive LLM Pipeline Tracer · Step 1 of 2 (1. Tier-1 Code Assertions Filter Structural Bugs in 0.1ms)
Wire Telemetry:latency=0mscost=$0.00000
1→output = run_rag_pipeline(case.question, case.sources)
2→# Tier 1: Fast deterministic checks (0ms, $0.00!)
3→assert all(cid in case.source_ids for cid in output.cited_ids)
4# Tier 2: Binary Faithfulness LLM Judge (reasoning BEFORE verdict!)
5grade = judge_faithfulness(sources=case.sources, answer=output.answer)
6assert grade.all_claims_supported is True
Deterministic Checks Passed0ms · $0
✓ Valid Pydantic JSON
✓ Response length <= 180 words
✓ All cited IDs ['doc_12'] exist in retrieved pool!
What's Happening: If Tier-1 fails (e.g., hallucinated citation ID), fail immediately without spending money on a Tier-2 LLM Judge call!

6. Production Code: pytest AI Eval Suite Across OpenAI, Gemini & Claude

You don't even need a proprietary SaaS tool to start — standard pytest + @pytest.mark.parametrize makes AI evals feel right at home in GitHub Actions:

SDK:
import pytest
from openai import OpenAI
from pydantic import BaseModel

client = OpenAI()

class FaithfulnessVerdict(BaseModel):
  unsupported_claims: list[str]
  all_claims_supported: bool

def judge_grounded(sources: str, answer: str) -> FaithfulnessVerdict:
  return client.responses.parse(
      model="gpt-4o-mini",
      temperature=0.0,
      instructions=(
          "List any factual claim in <answer> NOT directly supported by <sources>. "
          "Ignore style/length. Set all_claims_supported=True ONLY if unsupported_claims is empty."
      ),
      input=f"<sources>{sources}</sources>\n<answer>{answer}</answer>",
      text_format=FaithfulnessVerdict,
  ).output_parsed

@pytest.mark.parametrize("sources,answer,expected", [
  ("Pro plan costs $29/mo.", "The Pro plan is $29/month.", True),
  ("Pro plan costs $29/mo.", "Pro is $29/mo and includes a 14-day free trial.", False),
])
def test_faithfulness_judge_calibration(sources, answer, expected):
  verdict = judge_grounded(sources, answer)
  assert verdict.all_claims_supported is expected, f"Missed claims: {verdict.unsupported_claims}"

7. What Breaks in Production (War Stories)

  1. Shipping an Uncalibrated LLM Judge ("Who Watches the Watchmen?"): Teams write a sloppy Judge prompt that passes 99% of outputs — giving false confidence while hallucinations ship! Always hand-label 30 pass + 30 fail examples yourself and assert that your Judge achieves >= 90% agreement with your human labels (test_faithfulness_judge_calibration above!).
  2. Grading Only Final Text on RAG / Agent Systems: If an end-to-end test fails, you don't know if Retrieval missed the doc or Generation misread it! Grade Retrieval (Recall@5) and Generation (Faithfulness) separately.
  3. Goodhart's Law Overfitting on a Static 20-Case Eval Set: Tweaking prompts solely to hit 100% on 20 fixed examples overfits to those exact phrasings. Keep a held-out validation split and refresh cases from live logs monthly.

Module 7.1 Mastery Check — AI Evals & LLM-as-a-Judge

Q1.Why should LLM-as-a-Judge prompts use binary `PASS / FAIL` (True/False) factual checklists instead of `1 to 5` star scales?
Q2.What is 'Verbosity Bias' in LLM-as-a-Judge evaluations, and how do you mitigate it?
Q3.Why should you run Tier-1 deterministic code assertions (schema, regex, citation ID existence, SQL syntax) BEFORE calling an LLM Judge?
Q4.How do you verify that your LLM-as-a-Judge itself is trustworthy before gating production PRs on it?

Keep Exploring: Related Lessons & Tools

All Courses →