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.
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!
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:
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:
- 20 Happy-Path Core Queries (representative daily user tasks)
- 10 Missing-Context / Abstention Traps (questions NOT in
<sources>where passing = refusing to guess!) - 10 Tricky Boundary / Multi-Hop Cases (pronoun follow-ups, negation, date ties)
- 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:
- Use Binary
PASS / FAILChecklists — NEVER1–5Likert Scales! Asking an LLM to score "Rate helpfulness from 1 to 5" yields noisy4s and4.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! - Require
critique: strBEFOREpassed: bool: Just like Lesson 2.2, force the Judge to quote any unsupported claim before emittingpassed! - 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."
- 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
✓ Valid Pydantic JSON ✓ Response length <= 180 words ✓ All cited IDs ['doc_12'] exist in retrieved pool!
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:
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)
- 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 andassertthat your Judge achieves>= 90%agreement with your human labels (test_faithfulness_judge_calibrationabove!). - 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. - 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
Keep Exploring: Related Lessons & Tools
All Courses →Encode and decode UTF-8 strings, URLs, query parameters, Hex byte streams, and Base64 / Base64URL payloads without data corruption.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.