Sub topic 15
Testing and Evaluating LLM Features
This chapter assumes you can write basic Python, read JSON, and have seen the earlier chapters on prompting, classification, and structured output. It covers how to tell whether an LLM feature works, how to catch regressions when you change a prompt or model, and the mistakes teams make most often when they test these systems.
Why LLM features need a different kind of testing
A normal function returns the same output for the same input, so a unit test can assert exact equality. An LLM feature breaks that habit in three ways:
- The output can vary between runs, even with the same prompt.
- Many tasks have more than one acceptable answer. Two different summaries can both be good.
- Quality is a matter of degree. An answer can be partly right, right but badly worded, or right for the wrong reason.
You still test. You change what you assert. Instead of "the output equals X," you ask "across many realistic inputs, how often does the output meet the standard we care about?" That question needs three things: a set of test cases, a way to score each result, and a habit of re-running both whenever something changes.
Build an evaluation set first
An evaluation set (often called an eval set) is a list of inputs paired with what you expect or want. It is the most valuable testing asset you will have.
Good sources for cases:
- Real inputs from users or logs, with private data removed.
- Cases that failed in the past. Every bug report becomes a permanent test.
- Edge cases you invent on purpose: empty input, very long input, another language, typos, and inputs that try to override your instructions.
- Cases where the correct answer is "I don't know" or "none of the above."
Start small. Thirty to fifty well-chosen cases tell you more than a thousand copied at random. Label them carefully, because a wrong label makes a correct system look broken. Keep a separate group of cases that you never use while tuning the prompt. If you tune against every case you have, your score will look better than real performance (this is called overfitting to the eval set).
Three ways to score an output
Pick the cheapest method that is reliable for the task.
| Method | How it works | Best for | Main risk |
|---|---|---|---|
| Exact or rule-based check | Compare to a label, or test a property such as valid JSON or a required field | Classification, extraction, structured output | Rejects correct answers that are phrased differently |
| Human review | A person reads outputs and rates them against a rubric | Tone, helpfulness, final sign-off | Slow, costly, and raters disagree |
| Model-as-judge | A second model call grades the output against criteria | Summaries, drafts, open-ended answers | The judge has its own biases and errors |
Most real systems combine all three. Rules run on every case, a judge model covers the fuzzy qualities, and humans spot-check a sample and audit the judge.
A runnable evaluation harness
For tasks with a single correct label, scoring is simple. The harness below runs a classifier over labeled cases and reports accuracy and the failures. It takes the classifier as an argument, so you can pass a stub in tests and the real model call in production.
LABELS = ["billing", "bug", "feature_request", "other"]
def classify(ticket: str, complete) -> str:
prompt = (
"Classify the support ticket into exactly one label from: "
+ ", ".join(LABELS)
+ ".\nReply with the label only.\n\nTicket: " + ticket
)
answer = complete(prompt).strip().lower()
return answer if answer in LABELS else "other"
def evaluate(cases, complete):
failures = []
correct = 0
for ticket, expected in cases:
got = classify(ticket, complete)
if got == expected:
correct += 1
else:
failures.append((ticket, expected, got))
return correct / len(cases), failures
def fake_complete(prompt: str) -> str:
# Stand-in for a real model call, so the example runs offline.
if "charged twice" in prompt:
return "Billing"
if "crash" in prompt:
return "bug"
return "banana"
CASES = [
("I was charged twice this month", "billing"),
("The app will crash when I upload a photo", "bug"),
("Please add dark mode", "feature_request"),
]
accuracy, failures = evaluate(CASES, fake_complete)
print(f"accuracy: {accuracy:.2f}")
for ticket, expected, got in failures:
print(f"FAIL expected={expected} got={got} :: {ticket}")Running it prints an accuracy of 0.67 and one failure, for the dark mode ticket, because the stub returns "banana" and the fallback turns that into "other". Notice that the fallback inside classify hides the problem. If you want to know how often the model replies with something that is not a label, count those cases separately instead of folding them into "other."
Look past a single accuracy number
One score can hide what matters. Check these as well:
- Per-class results. A model can reach 90% accuracy by always predicting the most common label. Report precision and recall for each class, or at least print a confusion table of expected versus predicted labels.
- Cost of each error type. Wrongly routing a legal threat to "other" is worse than the reverse. Weigh errors by their consequences.
- Format failures. Track how often output is unparseable, using the same validation you use in production, such as the
parse_invoicecheck from the structured output chapter. - Latency and cost per case. A prompt that gains two points of accuracy but triples cost may not be an improvement.
Handling nondeterminism
Because outputs vary, one run proves little. Use these habits:
- Lower the temperature setting for tasks with one right answer, which makes output more consistent but not perfectly repeatable.
- Run each case several times and report the pass rate. A case that passes 3 of 5 runs is unstable, and that instability is worth knowing about.
- Compare versions on the same cases, and treat small differences with caution. On 40 cases, a change of one or two is noise, not progress.
- Record the model name, version, prompt text, and settings alongside every result. Without them you cannot explain why a score changed.
Using a model as a judge
For open-ended output, a judge prompt scores the answer against a rubric. A good judge prompt is specific, asks for a short reason, and returns a parseable result.
import json
JUDGE_TEMPLATE = (
"You are grading a summary of a source text.\n"
"Score 1 to 5 for faithfulness: 5 means every claim is supported by the source,\n"
"1 means it contains claims the source does not support.\n"
'Reply with JSON only: {{"score": <int>, "reason": "<one sentence>"}}\n\n'
"Source:\n{source}\n\nSummary:\n{summary}"
)
def judge(source: str, summary: str, complete) -> dict:
raw = complete(JUDGE_TEMPLATE.format(source=source, summary=summary))
data = json.loads(raw)
if not isinstance(data.get("score"), int) or not 1 <= data["score"] <= 5:
raise ValueError("score must be an integer from 1 to 5")
return data
def fake_judge(prompt: str) -> str:
return '{"score": 4, "reason": "One detail is slightly overstated."}'
print(judge("The shop opens at 9.", "The shop opens early.", fake_judge))Judges have known weaknesses:
- They tend to favor longer answers and answers written in their own style.
- They can favor whichever answer appears first when comparing two.
- They may be too lenient, giving high scores to everything.
Reduce these problems by scoring one narrow criterion per prompt, randomizing the order when comparing two answers, and checking the judge against a set of outputs that humans have already graded. If the judge and the humans disagree often, fix the judge before trusting its numbers.
Evaluating retrieval and tool use
When a feature has several parts, test the parts separately as well as together.
- Retrieval. Before judging the final answer, check whether the right document appeared in the top results. For each question, mark which document holds the answer, then measure how often it lands in the top k. A wrong answer with the right document retrieved is a prompt problem. A wrong answer with the wrong document retrieved is a search problem.
- Tool use. Check that the model chose the correct tool and passed valid arguments. These checks need no judge, because tool name and arguments are structured data you can compare directly.
- Groundedness. For answers built from documents, check that each claim is supported by the retrieved text, and that the model declines when the documents lack the answer.
Regressions and monitoring after launch
A regression is a case that used to pass and now fails. Prompt edits that fix one problem often cause another, so run the whole eval set after every change, and block the change if previously passing cases fail. The same applies when your provider updates a model version, which can shift behavior even though your own code did not change. Pin a specific model version where the provider allows it, and re-run your evals before moving to a new one.
Evaluation does not end at launch. Real users send inputs you did not predict. Log inputs and outputs (respecting your privacy rules), collect thumbs-up and thumbs-down signals, sample outputs for human review, and feed new failures back into the eval set.
Common mistakes
- Testing only with a handful of examples that you wrote while building the prompt.
- Tuning on every case, then reporting that same score as expected quality.
- Letting a fallback value hide format failures.
- Trusting a judge model without ever comparing it to human ratings.
- Reading a one-point change on a small set as a real improvement.
- Skipping the "no answer" cases, so the system never learns to refuse.
Exercise
Your classifier scores 92% accuracy on an eval set where 90% of the tickets are labeled "other." What is the problem with reporting that number, and what two checks would you add?
Show answer
A system that always answers "other" would score about 90%, so 92% may show almost no real skill. Add per-class precision and recall (or a confusion table) to see how it performs on the rare labels, and add more cases for the rare classes so they are not drowned out.
Exercise
A summarization feature gets worse after you shorten the prompt, but your judge model reports a higher average score. Give two reasons this could happen and one step to find out which is true.
Show answer
The judge may favor shorter or differently styled outputs, or it may be too lenient to detect the new errors. Another possibility is that the change is noise on a small set. Have humans grade a sample of outputs from both versions and compare their ratings to the judge's scores. If they disagree, revise the judge prompt before trusting it.