Part 08›
✎

05. Testing Generative and LLM Components#

Level: Practitioner · Reading time: 30 min · Exercise: 120 min Prerequisites: Testing Without Oracles

In one sentence: After this chapter you can turn "the output should be good" into a rubric of yes-or-no questions and run it as an automated test suite, with a calibrated LLM judge, inside CI and on a budget.

Why this matters#

Your team ships a feature that summarizes each support conversation for the next agent. A reviewer reads five summaries and says they look fine.

Two weeks later someone rewrites the prompt. Summaries start to promise refunds that no agent offered. The unit tests pass, because none of them looks at the text. The problem surfaces when a customer quotes a promise the company never made.

You know how to test a function. You do not yet know how to test prose.

The core idea#

A rubric is a short list of criteria, each written as a question with a yes-or-no answer. It converts one vague request, "write a good summary", into several small ones. Each question is a separate oracle.

A judge is whatever answers those questions. Three kinds exist, and you should use them in this order:

  1. Code. Cheap, exact, and fast. Use it for everything checkable: valid JSON, required strings, length, a language, a date format.
  2. An LLM judge. Using a model to grade another model's output is called LLM-as-a-judge. Use it for meaning: Is every fact in the summary present in the conversation?
  3. A person. Slow and expensive. Use people to calibrate the judge, meaning to measure how often it agrees with people, and to settle the cases the judge gets wrong.

The analogy is a linter (a tool that flags style problems and simple mistakes in code), a junior reviewer, and a senior reviewer. A linter never tires and never understands intent. A junior reviewer with a checklist catches most violations and makes mistakes of their own. A senior reviewer audits the junior. The analogy breaks on consistency: a human junior gives the same answer twice, while an LLM judge can grade the same output differently on two runs, so its results are a rate.

How it works, step by step#

1. Write the rubric#

Write six to eight criteria. Give each one three parts:

Bad criterion: "Is the summary good?". Good criterion: "Does the summary state how the conversation ended: resolved, pending, or no reply?".

2. Give each criterion the cheapest oracle#

Criterion Oracle
Output parses as JSON Code
States the refund amount that was offered Code, with the amount supplied per test case
At most three sentences Code
Every fact appears in the conversation LLM judge
No action is promised that nobody agreed to LLM judge
Tone is neutral LLM judge, then a person on a sample

3. Build the test set#

Collect 30 to 100 real inputs. Then add cases designed to tempt each failure: an empty conversation, a rude customer, a very long thread, two issues in one message, a thread with no reply, a language switch in the middle. For each case, write down what a correct output must contain.

Keep a held-out set that you never tune the prompt on. Measuring Model Quality explains why.

4. Design the judge call#

5. Calibrate the judge against people#

An uncalibrated judge is an opinion. Before it gates any merge:

  1. Have two people label the same 50 to 100 outputs against each criterion, with written guidelines.
  2. Measure how often the two people agree. That is the ceiling: a judge cannot be more reliable than the humans it imitates.
  3. Measure how often the judge agrees with the people, per criterion.
  4. Rewrite the criteria with low agreement. A low score usually means a vague question, not a bad judge.

Figure 1. One test case through the rubric pipeline: code checks what it can, the judge answers only what code cannot, and people calibrate the judge.

flowchart TD
    C["Test case: input plus what the output must contain"] --> M["Model under test"]
    M --> O["Output"]
    O --> K["Can code check the criterion?"]
    K -->|"yes"| P["Code check: free and exact"]
    K -->|"no"| J["LLM judge: one question, answer plus quoted evidence"]
    J --> E["Is the quoted evidence in the output?"]
    E -->|"no"| X["Error: the judge failed, not the model"]
    E -->|"yes"| V["Verdict: must asserted strictly, should counted in a rate"]
    V --> B["People label a sample to calibrate the judge"]

The judge is only trusted for the criteria on which it has been shown to agree with people; everything a program can check never reaches it.

6. Handle flakiness#

Both the model under test and the judge can vary between runs. Four habits keep the suite trustworthy:

7. Run it in tiers inside CI#

Tier What runs Cost and time
Every commit Code checks on saved outputs Free, under a second
Every pull request 20 to 50 fixed cases, musts and shoulds Cents, a few minutes
Nightly Full set, held-out set, repeated runs for variance Dollars

Put the LLM tests in a separate job from unit tests. Unit tests answer "is the code broken?". LLM tests answer "is the behavior still good?". A flaky model call must not block a typo fix.

8. Review what the judge says#

Log every verdict with its evidence. When a test fails, ask first whether the judge is wrong. Sample a few passing verdicts too. A judge that approves everything is worse than no judge.

Worked example#

A pytest-style suite for the summarizer. The ask function stands in for your provider's SDK. The whole listing is illustrative pseudocode: it was not checked against current API documentation and it is not meant to run as pasted.

# llm.py -- illustrative pseudocode for a chat-model call. Each call costs money.
import json

def ask(system: str, user: str) -> str:
    return client.chat(model=MODEL, temperature=0.0, messages=[
        {"role": "system", "content": system},
        {"role": "user", "content": user}]).text

SUMMARIZER = ('Summarize the support conversation for the next agent in at most '
              'three sentences. Reply with JSON only: {"summary": "..."}')

def summarize(thread: str) -> str:
    return json.loads(ask(SUMMARIZER, thread))["summary"]
# test_summarizer.py
import json
import pytest
from llm import ask, summarize

JUDGE = """You grade a summary of a support conversation.
Answer the question with "yes" or "no".
Copy the exact words from the summary that justify your answer.
Reply with JSON only: {{"answer": "yes or no", "evidence": "quoted words"}}

Conversation:
{thread}

Summary:
{summary}

Question: {question}"""

def judge(thread: str, summary: str, question: str) -> bool:
    """One paid call per question."""
    prompt = JUDGE.format(thread=thread, summary=summary, question=question)
    verdict = json.loads(ask("You are a careful grader.", prompt))
    if verdict["evidence"] not in summary:
        raise ValueError(f"judge invented its evidence: {verdict['evidence']!r}")
    return verdict["answer"] == "yes"

MUSTS = [  # hard requirements: every case must pass, every time
    "Does every fact in the summary appear in the conversation?",
    "Does the summary say how the conversation ended: resolved, pending, or no reply?",
    "Does the summary promise only actions that someone in the conversation agreed to?",
]
SHOULDS = [  # quality preferences: judged as a pass rate
    "Is the summary neutral, blaming no one?",
]
CASES = [
    pytest.param(
        "Customer: I was charged twice for order 42.\n"
        "Agent: Sorry about that. I refunded $42; it arrives within 3 days.",
        ["42"], id="double-charge"),
    pytest.param("Customer: Hello? Is anyone there?", [], id="no-reply"),
    pytest.param(
        "Customer: My app crashed while I was paying, and the invoice "
        "address is wrong.\nAgent: Let me check both and get back to you.",
        ["crash", "address"], id="two-issues-pending"),
]

_summaries = {}  # several tests need the same summary: pay for it once

def summary_of(thread: str) -> str:
    if thread not in _summaries:
        _summaries[thread] = summarize(thread)
    return _summaries[thread]

# 1. Free checks first. No judge needed.
@pytest.mark.parametrize("thread, required", CASES)
def test_hard_checks(thread, required):
    summary = summary_of(thread)
    for word in required:
        assert word in summary, f"{word!r} missing from: {summary}"
    assert len(summary.split()) <= 80, "summary is too long"

# 2. Hard requirements: strict, one test per case and criterion.
@pytest.mark.parametrize("thread, _", CASES)
@pytest.mark.parametrize("question", MUSTS)
def test_must_criteria(thread, _, question):
    summary = summary_of(thread)
    assert judge(thread, summary, question), f"FAILED: {question}\nSummary: {summary}"

# 3. Quality preferences: a rate, because judge and model both vary.
def test_should_criteria_pass_rate():
    checks = [judge(t, summary_of(t), q) for t, _ in CASES for q in SHOULDS]
    assert sum(checks) / len(checks) >= 0.8, f"{sum(checks)} of {len(checks)} passed"

What to observe:

What the practitioners say#

Kästner's chapter 15 is the book behind this chapter, and it has almost nothing on rubrics or on one model grading another: it predates most current judge practice. The steps above, the judge calibration, the handling of flakiness, the cost estimate and the CI tiers are engineering guidance built on its three strategies, not content from the book.

Pitfalls#

  1. One vague criterion. "Is it good?" cannot be calibrated. Fix: split it into specific yes-or-no questions.
  2. Asking the judge what code can check. Slower, costlier, and less reliable. Fix: code first, judge second.
  3. Gating merges on an uncalibrated judge. Fix: measure agreement with people per criterion before it can block a merge.
  4. Asserting exact text. Sampled output always differs in wording. Fix: parse fields, compare facts, use rates.
  5. Running every LLM test on every commit. The suite is slow, flaky, and resented. Fix: tiers, and a separate CI job.
  6. Blaming the model for every red test. Fix: read the evidence, and audit the judge before the component.
  7. Tuning the prompt on the test cases. Fix: keep a held-out set for the reported number.

Try it#

Take one LLM component you can call.

  1. Write a rubric of six criteria, each marked must or should, each with its cheapest oracle.
  2. Build 30 cases, including five designed to tempt a specific failure.
  3. Implement the suite in three parts, as in the example.
  4. Label the 30 outputs yourself against every criterion, then measure the judge's agreement with you, per criterion.

You are done when the suite runs from one command, reports failures with evidence, costs less than ten cents per run, and shows at least 80 percent agreement with your labels on every must-criterion. Rewrite any criterion below that mark until it reaches it. Stretch goal: have a second person label the same 30 outputs and compute how often the two of you agree.

Key takeaways#

Self-check#

  1. A reviewer says the summaries "look good". What is the first thing to ask for?
  2. Which oracle should check "the output is valid JSON", and why that one?
  3. Why compare a judge's verdicts with human labels one criterion at a time?
  4. A must-criterion test fails. The judge's evidence is a sentence that is not in the summary. What happened?
  5. Why are should-criteria asserted as a rate while musts are strict?
Show answers 1. The criteria behind the judgment. "Good" is not testable until it is split into specific yes-or-no questions. 2. Code. It is exact, free, and instant, and a judge would be slower, costlier, and less reliable for it. 3. Agreement is a property of the question, not only of the judge. A low score on one criterion points to a vague question to rewrite, which an overall agreement figure would hide. 4. The judge failed, not the component. The evidence check raised an error so that a grader's mistake is not reported as a product defect. 5. Hard requirements admit no exceptions, so each case must pass. Preferences are judged inconsistently by both the model and the judge, so only their frequency over many cases is stable.

Sources#

Next#

→ Data Quality, because a model can only be as good as the data that reaches it, and data bugs hide longer than code bugs.