Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

How to test LLM applications as a QA engineer

Contract tests on a scripted model, a golden set with pass-rate floors, a calibrated LLM judge and a regression gate.

By Intermediate1 h hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

To test an LLM application, split the tests by what they can promise. Test the code around the model with ordinary deterministic tests and a scripted fake model. Test the model’s behaviour with a golden set of real cases, scored by checks on properties rather than exact strings, and fail only when a pass rate falls below a floor. Use an LLM judge for the one or two qualities code cannot check, and only after you have measured it against your own labels. Then gate every change on “no worse than the last accepted run”.

This tutorial builds that suite in pytest for a small feature: a bug-report triager that returns a severity, a component and a one-line title. You will write contract tests, a golden set, a judge and a regression gate, and run all of it without an API key. It uses pytest 9.2.0 and the Anthropic Python SDK 2.12.0, checked on 21 November 2026. If you want the theory of evals first, read start evals with error analysis.

What to assert when the output changes every run

A QA engineer’s instinct is to pin the expected output and compare. With an LLM that fails twice: the same input gives different wording on each run, and with current Claude models you cannot set the temperature to make it stop. The fix is to choose, for each thing you care about, the strongest assertion that still holds when the wording moves.

What you check Assertion Example in this tutorial Runs
The code around the model Exact, deterministic The report reaches the model unchanged; bad JSON is retried once Every commit, no key
Structure of the output Exact on fields Severity is one of blocker, major, minor Every reply, in production too
Facts in the output Property The title mentions the coupon code or the postcode Golden set
Qualities without a rule Judged The title invents no cause Golden set, live
Behaviour over many cases Pass rate against a floor and a baseline Severity right on at least 85% of cases CI gate

Two ideas carry the rest of the page. One LLM test case on its own proves little, so you assert on rates across a set. And the scripted model is there to test how your code handles whatever the model says, including the replies you hope never to see.

1. Set up the project and the feature under test

Create a folder and a virtual environment, and pin the two packages:

mkdir triage-tests && cd triage-tests
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install anthropic==2.12.0 pytest==9.2.0

Save the feature as triage.py. It asks for JSON that matches a schema, then validates the reply in code before anything else sees it:

# triage.py: the LLM feature under test. Turns a bug report into severity, component and title.
import json
from dataclasses import dataclass

SEVERITIES = ["blocker", "major", "minor"]
COMPONENTS = ["checkout", "login", "search", "other"]
MAX_TITLE = 80

SYSTEM = (
    "You triage bug reports for an online shop. Return JSON with three fields. "
    "severity: blocker if customers cannot pay or sign in at all; major if a feature is broken "
    "for some customers or has a workaround; minor for cosmetic problems and typos. "
    "component: checkout, login, search or other. "
    "title: one line under 80 characters that states the symptom, using only facts in the report."
)

SCHEMA = {
    "type": "object",
    "properties": {
        "severity": {"type": "string", "enum": SEVERITIES},
        "component": {"type": "string", "enum": COMPONENTS},
        "title": {"type": "string"},
    },
    "required": ["severity", "component", "title"],
    "additionalProperties": False,
}


class InvalidOutput(ValueError):
    """The model replied, but not with something the app can use."""


@dataclass(frozen=True)
class Triage:
    severity: str
    component: str
    title: str


def parse_triage(text: str) -> Triage:
    try:
        data = json.loads(text)
    except json.JSONDecodeError as err:
        raise InvalidOutput(f"not JSON: {text[:60]!r}") from err
    if data.get("severity") not in SEVERITIES:
        raise InvalidOutput(f"unknown severity {data.get('severity')!r}")
    if data.get("component") not in COMPONENTS:
        raise InvalidOutput(f"unknown component {data.get('component')!r}")
    title = str(data.get("title", "")).strip()
    if not title or len(title) > MAX_TITLE:
        raise InvalidOutput(f"title must be 1-{MAX_TITLE} characters, got {len(title)}")
    return Triage(data["severity"], data["component"], title)


def triage_bug(report: str, model, attempts: int = 2) -> Triage:
    """Ask the model, validate the reply, and retry once if it is unusable."""
    error = None
    for _ in range(attempts):
        try:
            return parse_triage(model.complete(SYSTEM, report, schema=SCHEMA))
        except InvalidOutput as err:
            error = err
    raise error

Why validate in code when the schema already constrains the reply? The schema guarantees shape, not your rules. Claude’s structured outputs do not support maxLength, so the 80-character limit can only live in parse_triage. Validation is also what makes the feature testable: it turns “the model said something odd” into a typed error your tests can expect.

2. Put the model behind a seam

Save models.py. Both classes have the same complete() method, so the feature never knows which one it is talking to:

# models.py: one real client and one scripted stand-in with the same complete() method.
class ClaudeModel:
    """Calls the Claude API. Needs ANTHROPIC_API_KEY in the environment."""

    def __init__(self, model: str = "claude-haiku-5-5", effort: str = "low"):
        import anthropic

        self.client = anthropic.Anthropic()
        self.model = model
        self.effort = effort

    def complete(self, system: str, user: str, schema: dict | None = None) -> str:
        output_config = {"effort": self.effort}
        if schema:
            output_config["format"] = {"type": "json_schema", "schema": schema}
        response = self.client.messages.create(
            model=self.model,
            max_tokens=4000,
            system=system,
            messages=[{"role": "user", "content": user}],
            output_config=output_config,
        )
        if response.stop_reason == "refusal":
            raise RuntimeError("the model declined this input")
        return next(block.text for block in response.content if block.type == "text")


class ScriptedModel:
    """Returns canned replies in order and records every prompt it was sent."""

    def __init__(self, *replies: str):
        self.replies = list(replies)
        self.calls: list[tuple[str, str]] = []

    def complete(self, system: str, user: str, schema: dict | None = None) -> str:
        self.calls.append((system, user))
        return self.replies.pop(0)

ClaudeModel defaults to claude-haiku-5-5, which Anthropic’s models page describes as the model for classification and extraction, at low effort. It is the only code in this tutorial that needs a key. ScriptedModel is the test double: it plays back replies you choose and records what it was sent, so a test can check the prompt as well as the handling of the answer.

3. Write contract tests for the code around the model

These are the tests a QA engineer already knows how to write. They pin the behaviour of your code for every kind of reply, good and bad. Save test_contract.py:

# test_contract.py: deterministic tests of the code around the model. No API key, no flakiness.
import json

import pytest

from models import ScriptedModel
from triage import InvalidOutput, SYSTEM, Triage, parse_triage, triage_bug

GOOD = json.dumps({"severity": "major", "component": "search", "title": "Price sort orders £100 before £20"})


def test_report_reaches_the_model_unchanged():
    model = ScriptedModel(GOOD)
    triage_bug("Sorting by price is wrong.", model)
    system, user = model.calls[0]
    assert system == SYSTEM
    assert user == "Sorting by price is wrong."


def test_valid_reply_becomes_a_triage():
    assert parse_triage(GOOD) == Triage("major", "search", "Price sort orders £100 before £20")


@pytest.mark.parametrize("reply", [
    "Sure! Here is the triage: major",                                         # prose, not JSON
    json.dumps({"severity": "critical", "component": "search", "title": "x"}),  # not in the enum
    json.dumps({"severity": "minor", "component": "search", "title": "x" * 81}),  # too long
    json.dumps({"severity": "minor", "component": "search", "title": "   "}),     # empty title
])
def test_unusable_replies_are_rejected(reply):
    with pytest.raises(InvalidOutput):
        parse_triage(reply)


def test_one_bad_reply_is_retried():
    model = ScriptedModel("not json", GOOD)
    assert triage_bug("report", model).component == "search"
    assert len(model.calls) == 2


def test_two_bad_replies_raise_instead_of_guessing():
    with pytest.raises(InvalidOutput):
        triage_bug("report", ScriptedModel("not json", "still not json"))

Run them:

pytest -q test_contract.py
........                                                                 [100%]
8 passed in 0.01s

The parametrised cases are replies a real model rarely gives with a schema switched on, which is exactly why they need a test: you will not see them in a demo, and you will see them in production after a model or SDK change. The last test records a decision: when the model fails twice, the feature raises instead of filling in a default severity, so a bad triage cannot pass silently into your tracker.

4. Build a golden set and score it with pass-rate floors

A golden set is a fixed list of inputs with the answer you expect, taken from real reports where you can. Save these eight cases as golden.jsonl, one JSON object per line:

{"id": "coupon-rejected", "report": "Applying the code SPRING10 at checkout shows 'invalid code' although the email says it is valid until Friday. Same in Chrome and Firefox. I could still pay full price.", "severity": "major", "component": "checkout", "mentions": ["code", "coupon", "discount"]}
{"id": "pay-button-dead", "report": "The Pay now button does nothing on the last checkout step. No error, no spinner. Every caller to the support line today reports the same. We are not taking any orders.", "severity": "blocker", "component": "checkout", "mentions": ["pay"]}
{"id": "reset-email-late", "report": "Password reset emails arrive about 40 minutes late. Customers can still sign in with Google instead.", "severity": "major", "component": "login", "mentions": ["reset"]}
{"id": "login-down", "report": "Nobody can sign in since the 14:00 deploy: the login form returns 'Something went wrong' for every account we tried.", "severity": "blocker", "component": "login", "mentions": ["sign in", "sign-in", "login", "log in"]}
{"id": "results-typo", "report": "On the search results page the heading says 'Resluts for shoes'.", "severity": "minor", "component": "search", "mentions": ["typo", "resluts", "misspel", "spelling"]}
{"id": "price-sort", "report": "Sorting search results by price puts the 100 pound items before the 20 pound items. Looks like it sorts the numbers as text.", "severity": "major", "component": "search", "mentions": ["sort"]}
{"id": "careers-404", "report": "The Careers link in the footer goes to a 404 page.", "severity": "minor", "component": "other", "mentions": ["careers"]}
{"id": "postcode-space", "report": "Customers whose postcode contains a space cannot get past the address step at checkout. Removing the space works.", "severity": "major", "component": "checkout", "mentions": ["postcode"]}

mentions is a property check: the title must contain at least one of these words, so “Valid code SPRING10 rejected” and “Discount code refused” both pass. That is the core move for non-deterministic text. Decide which fact must survive, and accept any wording that keeps it.

To run the golden set offline, the suite replays stored outputs instead of calling the model. Save these as sample_outputs.json. They are hand-written for this tutorial, not model output, and two of them are wrong on purpose:

{
  "coupon-rejected": "{\"severity\": \"major\", \"component\": \"checkout\", \"title\": \"Valid code SPRING10 rejected as invalid at checkout\"}",
  "pay-button-dead": "{\"severity\": \"blocker\", \"component\": \"checkout\", \"title\": \"Pay now button does nothing on final checkout step\"}",
  "reset-email-late": "{\"severity\": \"major\", \"component\": \"login\", \"title\": \"Password reset emails arrive about 40 minutes late\"}",
  "login-down": "{\"severity\": \"blocker\", \"component\": \"login\", \"title\": \"Sign in fails for every account since 14:00 deploy\"}",
  "results-typo": "{\"severity\": \"minor\", \"component\": \"search\", \"title\": \"Typo in search results heading: 'Resluts'\"}",
  "price-sort": "{\"severity\": \"major\", \"component\": \"search\", \"title\": \"Price sort broken by a missing database index\"}",
  "careers-404": "{\"severity\": \"minor\", \"component\": \"other\", \"title\": \"Footer Careers link returns 404\"}",
  "postcode-space": "{\"severity\": \"blocker\", \"component\": \"checkout\", \"title\": \"Postcodes with a space block the checkout address step\"}"
}

Now the test. It scores every case, writes the rates and per-case failures to results.json, and fails only when a rate falls below its floor. Save test_golden.py:

# test_golden.py: score the feature on a fixed set of real-looking cases and enforce pass-rate floors.
import json
import os
from pathlib import Path

from judge import judge_title
from models import ClaudeModel, ScriptedModel
from triage import triage_bug

LIVE = os.environ.get("LLM_LIVE") == "1"
CASES = [json.loads(line) for line in Path("golden.jsonl").read_text().splitlines() if line.strip()]
FLOORS = {"severity": 0.85, "component": 1.0, "mentions_key_fact": 0.85, "faithful_title": 0.85}


def run_case(case: dict) -> dict:
    if LIVE:
        model = ClaudeModel()
    else:  # replay a stored output so the suite runs offline
        model = ScriptedModel(json.loads(Path("sample_outputs.json").read_text())[case["id"]])
    result = triage_bug(case["report"], model)
    checks = {
        "severity": result.severity == case["severity"],
        "component": result.component == case["component"],
        "mentions_key_fact": any(word in result.title.lower() for word in case["mentions"]),
    }
    if LIVE:  # the judge needs a real model; offline runs skip this check
        checks["faithful_title"] = judge_title(case["report"], result.title, ClaudeModel("claude-opus-5-5", "medium"))
    return checks


def test_golden_set_meets_floors():
    rows = {case["id"]: run_case(case) for case in CASES}
    checks = sorted({name for row in rows.values() for name in row})
    rates = {name: round(sum(row[name] for row in rows.values()) / len(rows), 3) for name in checks}
    failures = {cid: [n for n, ok in row.items() if not ok] for cid, row in rows.items() if not all(row.values())}
    Path("results.json").write_text(json.dumps({"rates": rates, "failures": failures}, indent=2) + "\n")

    below = {name: rate for name, rate in rates.items() if rate < FLOORS[name]}
    assert not below, f"below floor: {below}. Per-case failures are in results.json"

The file imports judge.py, which you write in step 5, so run it in step 6. One test per set, not one per case, is deliberate. A per-case test turns one borderline answer into a red build, and the team learns to rerun until green. A floor says what quality you will ship: here, component must always be right because it routes the bug to a team, and severity may miss one case in eight because a person reviews it.

5. Add a judge, and test the judge

The price-sort sample invents a cause (“a missing database index”) that the report never mentions. Every property check passes it, because the title does mention sorting. “Invents nothing” has no rule you can write in code, so it is a job for an LLM-as-a-judge. Save judge.py:

# judge.py: an LLM judge for the one property code cannot check, "the title invents nothing".
from triage import InvalidOutput

JUDGE_SYSTEM = (
    "You check one thing: whether a bug title states only facts that are in the bug report. "
    "Answer FAIL if the title adds a cause, a number, a place or any claim the report does not contain. "
    "Otherwise answer PASS. Reply with PASS or FAIL as the first word, then one sentence of reasoning."
)


def judge_title(report: str, title: str, model) -> bool:
    reply = model.complete(JUDGE_SYSTEM, f"<report>\n{report}\n</report>\n<title>{title}</title>")
    words = reply.strip().split()
    verdict = words[0].strip(".:").upper() if words else ""
    if verdict not in ("PASS", "FAIL"):
        raise InvalidOutput(f"judge gave no verdict: {reply[:60]!r}")
    return verdict == "PASS"

A judge is a measuring instrument, so it gets tests of its own. Write six labelled examples by hand in judge_labels.jsonl, half faithful and half not:

{"report": "Sorting search results by price puts the 100 pound items before the 20 pound items.", "title": "Price sort puts 100 pound items before 20 pound items", "label": true}
{"report": "Sorting search results by price puts the 100 pound items before the 20 pound items.", "title": "Price sort broken by a missing database index", "label": false}
{"report": "The Careers link in the footer goes to a 404 page.", "title": "Footer Careers link returns 404", "label": true}
{"report": "The Careers link in the footer goes to a 404 page.", "title": "Careers page deleted in last release", "label": false}
{"report": "Password reset emails arrive about 40 minutes late.", "title": "Password reset emails delayed by about 40 minutes", "label": true}
{"report": "Password reset emails arrive about 40 minutes late.", "title": "Reset emails late for all Gmail users", "label": false}

Then save test_judge.py. Its first two tests check the parsing offline; the third measures agreement with your labels and only runs live:

# test_judge.py: the judge is code too. Test its parsing offline, and its agreement with you live.
import json
import os
from pathlib import Path

import pytest

from judge import judge_title
from models import ClaudeModel, ScriptedModel
from triage import InvalidOutput

LIVE = os.environ.get("LLM_LIVE") == "1"


def test_verdicts_are_parsed():
    assert judge_title("r", "t", ScriptedModel("PASS. Every fact is in the report.")) is True
    assert judge_title("r", "t", ScriptedModel("FAIL: the cause is invented.")) is False


def test_a_reply_without_a_verdict_is_an_error():
    with pytest.raises(InvalidOutput):
        judge_title("r", "t", ScriptedModel("The title looks fine to me."))


@pytest.mark.skipif(not LIVE, reason="calls the Claude API; set LLM_LIVE=1")
def test_judge_agrees_with_human_labels():
    model = ClaudeModel("claude-opus-5-5", effort="medium")
    rows = [json.loads(line) for line in Path("judge_labels.jsonl").read_text().splitlines()]
    agree = sum(judge_title(r["report"], r["title"], model) == r["label"] for r in rows)
    assert agree / len(rows) >= 0.9, f"judge agreed on {agree}/{len(rows)} labels"

The judge uses Claude Opus 5.5 while the feature uses Haiku: grading is the harder task, and the judge sees far fewer calls than production does. The judge asks one narrow question with a fixed answer format, which is what makes its verdicts countable. Six labels is only a start; the LLM-as-a-judge tutorial covers how many you need and how to read the disagreements.

6. Run the whole suite

Offline first. -rs prints why a test was skipped:

pytest -q -rs
cat results.json
...........s                                                             [100%]
=========================== short test summary info ============================
SKIPPED [1] test_judge.py:25: calls the Claude API; set LLM_LIVE=1
11 passed, 1 skipped in 0.01s
{
  "rates": {
    "component": 1.0,
    "mentions_key_fact": 1.0,
    "severity": 0.875
  },
  "failures": {
    "postcode-space": [
      "severity"
    ]
  }
}

The suite passed with a known failure inside it, and that is the point: postcode-space was triaged as a blocker when the report says there is a workaround. Severity is at 0.875, above its 0.85 floor. results.json tells you which case to read, and reading it is where you decide whether the prompt or your label is wrong.

To run against the real model, set your key and the live flag:

export ANTHROPIC_API_KEY="sk-ant-..."
LLM_LIVE=1 pytest -q -rs

The live run replaces the stored outputs with Claude Haiku 5.5 replies, adds the faithful_title check and runs the judge calibration. Your rates will differ from the offline ones and may differ between live runs. Run it two or three times before you trust a rate, because one run of eight cases can move by a whole case either way.

7. Gate changes on the last accepted run

Floors catch disasters. They do not catch a slide from 1.0 to 0.875 that still clears the floor, which is how quality usually leaks after a prompt edit. Save gate.py:

# gate.py: fail CI when any pass rate drops more than TOLERANCE below the last accepted run.
import json
import sys
from pathlib import Path

TOLERANCE = 0.05

baseline = json.loads(Path("baseline.json").read_text())["rates"]
current = json.loads(Path("results.json").read_text())["rates"]

failed = False
for check, before in sorted(baseline.items()):
    now = current.get(check)
    if now is None:
        print(f"{check:18} missing from this run")
        failed = True
        continue
    dropped = now < before - TOLERANCE
    failed |= dropped
    print(f"{check:18} baseline {before:.2f}  now {now:.2f}  {'DROP' if dropped else 'ok'}")

sys.exit(1 if failed else 0)

Accept the current run as the baseline and check the gate passes:

cp results.json baseline.json
python gate.py
component          baseline 1.00  now 1.00  ok
mentions_key_fact  baseline 1.00  now 1.00  ok
severity           baseline 0.88  now 0.88  ok

Now simulate a regression. Edit the reset-email-late title in sample_outputs.json to “Emails to customers arrive about 40 minutes late”, which drops the word “reset”, and run both checks again:

pytest -q test_golden.py
python gate.py
.                                                                        [100%]
1 passed in 0.00s
component          baseline 1.00  now 1.00  ok
mentions_key_fact  baseline 1.00  now 0.88  DROP
severity           baseline 0.88  now 0.88  ok

pytest is happy, because 0.875 clears the floor. The gate exits 1, because the rate fell by more than the tolerance. Run gate.py after the golden test in CI and commit baseline.json; update it only in a pull request that says why the new numbers are acceptable. Put the edited title back before you go on.

Choosing floors and tolerance

Start each floor just below what your first honest live runs score, not at the number you would like. Set the tolerance to at least one case’s worth of the set (with eight cases, one case is 0.125), or the gate will fire on noise; the 0.05 here works only because the offline replay is deterministic. As the golden set grows towards 50 or 100 cases, one case is worth less, and you can tighten both. Grow the set from production: every bug the triager gets wrong becomes a new line in golden.jsonl with the answer a person gave.

Pitfalls

Asserting on exact strings. assert title == "Footer Careers link returns 404" fails on the next run with identical meaning. Assert on the fact that must survive ("careers" in title.lower()) and leave the wording free.

Treating one failing case as a failed build. Per-case tests teach the team to rerun until green. Score the set, keep the per-case failures in a report, and fail on the rate.

Trusting the schema to enforce your rules. Structured outputs guarantee the JSON shape and the enums. They do not enforce string length, and they say nothing about whether the title is true. Keep the validation in code and test it with bad replies.

Using a judge you never checked. An uncalibrated judge produces numbers that look like measurements. Label examples yourself, including the failure you care about, and keep the agreement test in the suite so a model change cannot quietly break it.

Calling the model in contract tests. Tests that hit the API are slow, cost money and fail for reasons that have nothing to do with your code. Anything that tests parsing, prompts or retries belongs on the scripted model.

Letting the baseline drift upwards on a lucky run. If you copy results.json to baseline.json after every green run, one lucky run sets a bar that ordinary runs then miss. Update the baseline deliberately, after several live runs agree.

Next steps

Covers

Check your understanding

Testing LLM applications quiz

Assertions for non-deterministic output, scripted models, golden sets with floors, calibrated judges and regression gates.

8 questions · pass mark 70%

Question 1 of 80 answered
  1. The triage title changes wording on every run. What should the golden-set test assert about it?
  • Write your first LLM eval

    Turn real outputs into a small test set, add code-based checks in promptfoo and run them in CI to catch regressions on every change.

    TutorialBeginner40 min

  • LLM-as-a-judge: grading outputs you can trust

    Write narrow grading criteria, check the judge's verdicts against your own labels and decide when its agreement is good enough.

    TutorialIntermediate45 min

  • AI for QA engineers: where it helps and where it doesn't

    Where it helps in test design, agent-written tests and self-healing, where it does not, and the testing skills worth building.

    Article

  • Golden dataset

    A curated set of inputs with expected outputs or grading notes, used as the fixed reference that your evals are scored against.

    Glossary

  • AI for test engineers

    An AI course for testers: apply generative AI to everyday test automation, from AI-assisted test design to generating, healing and reviewing Playwright tests.

    Learning pathBeginner9 h10 steps

Back to top