Evaluating LLM Apps
"It looked good when I tried it" is not evidence. LLM output varies with wording, inputs and model versions, so you need a repeatable way to measure quality — an evaluation (often called evals). Evals tell you whether a prompt change helped, whether a cheaper model is good enough, and whether an update broke something.
Start with a test set
Collect realistic inputs with the expected result (or a description of what a good result must contain). Twenty well-chosen cases beat none; grow the set whenever you find a failure in production.
| Kind of check | Example | How to score |
|---|---|---|
| Exact answer | classification label, extracted ID | exact match |
| Short free text | an extracted name or date | normalised match, token F1 |
| Must contain / must not contain | "mentions the 30-day policy", "no competitor names" | rule-based checks |
| Format | valid JSON with required keys | parser + validator |
| Open-ended quality | helpfulness, tone, faithfulness to sources | rubric scored by a person or an LLM judge |
Automatic metrics
import re
from collections import Counter
def normalise(text):
text = re.sub(r"[^\w\s]", "", text.lower())
return " ".join(w for w in text.split() if w not in {"a", "an", "the"})
def exact_match(pred, gold):
return normalise(pred) == normalise(gold)
def token_f1(pred, gold):
p, g = normalise(pred).split(), normalise(gold).split()
common = sum((Counter(p) & Counter(g)).values())
if common == 0:
return 0.0
precision, recall = common / len(p), common / len(g)
return 2 * precision * recall / (precision + recall)
cases = [
("The Eiffel Tower", "Eiffel Tower"),
("in Paris, France", "Paris"),
("Berlin", "Paris"),
]
for pred, gold in cases:
print(f"{pred!r:20} vs {gold!r:15} EM={exact_match(pred, gold)!s:5} F1={token_f1(pred, gold):.2f}")'The Eiffel Tower' vs 'Eiffel Tower' EM=True F1=1.00
'in Paris, France' vs 'Paris' EM=False F1=0.50
'Berlin' vs 'Paris' EM=False F1=0.00
Exact match is strict; token F1 gives partial credit for overlapping words. Neither understands meaning ("Paris" vs "the French capital" scores 0), which is why open-ended outputs need rubrics.
A tiny eval harness
An eval harness runs every case through the system and reports a score per check. Here the "system" is a fake classifier standing in for a prompt + model; swap in a real call and the harness stays the same:
TEST_SET = [
{"input": "My card was charged twice", "expected": "billing"},
{"input": "Parcel still not here after a week", "expected": "delivery"},
{"input": "The lamp flickers when switched on", "expected": "product"},
{"input": "Refund for the double payment please", "expected": "billing"},
{"input": "Courier left the box in the rain", "expected": "delivery"},
{"input": "Do you sell gift cards?", "expected": "other"},
]
def system_v1(text):
t = text.lower()
if "charged" in t or "payment" in t:
return "billing"
if "parcel" in t:
return "delivery"
return "product"
def system_v2(text):
t = text.lower()
if any(w in t for w in ("charged", "payment", "refund")):
return "billing"
if any(w in t for w in ("parcel", "courier", "delivery")):
return "delivery"
if any(w in t for w in ("broken", "flickers", "faulty")):
return "product"
return "other"
def evaluate(system):
failures = [c for c in TEST_SET if system(c["input"]) != c["expected"]]
return 1 - len(failures) / len(TEST_SET), failures
for name, system in [("v1", system_v1), ("v2", system_v2)]:
accuracy, failures = evaluate(system)
print(f"{name}: accuracy {accuracy:.0%}")
for f in failures:
print(f" wrong: {f['input']!r} (expected {f['expected']}, got {system(f['input'])})")v1: accuracy 67%
wrong: 'Courier left the box in the rain' (expected delivery, got product)
wrong: 'Do you sell gift cards?' (expected other, got product)
v2: accuracy 100%
Looking at the failures, not just the score, is where you learn what to fix.
LLM-as-judge
For qualities that rules can't capture, a second model can grade outputs against a rubric. This is reference code:
JUDGE_PROMPT = """You are grading a customer-support answer.
<question>{question}</question>
<sources>{sources}</sources>
<answer>{answer}</answer>
Score each criterion 1-5 and reply as JSON:
{{"faithful": <only uses facts from sources>, "helpful": <answers the question>,
"tone": <polite and concise>, "reason": "<one sentence>"}}"""
result = client.messages.create(model="claude-opus-5-5", max_tokens=200,
messages=[{"role": "user", "content": JUDGE_PROMPT.format(...)}])Judges are useful but imperfect: they can prefer longer answers, favour their own style, or be swayed by confident wording. Make the rubric specific, ask for a short reason, check a sample of judgements by hand, and compare with human ratings before trusting the scores.
Comparing versions
Aggregate results into a table to compare prompt or model versions across categories:
import pandas as pd
results = pd.DataFrame({
"version": ["v1"] * 4 + ["v2"] * 4,
"category": ["billing", "delivery", "product", "other"] * 2,
"passed": [9, 6, 8, 2, 10, 9, 8, 6],
"total": [10, 10, 10, 8, 10, 10, 10, 8],
})
results["rate"] = (results["passed"] / results["total"]).round(2)
print(results.pivot(index="category", columns="version", values="rate"))
totals = results.groupby("version")[["passed", "total"]].sum()
print((totals["passed"] / totals["total"]).round(3).to_string())version v1 v2
category
billing 0.90 1.00
delivery 0.60 0.90
other 0.25 0.75
product 0.80 0.80
version
v1 0.658
v2 0.868
Good habits
- Separate retrieval and generation in RAG evals: was the right chunk retrieved? Did the answer use it faithfully?
- Run evals on every change — prompt, model, retrieval settings, temperature — like unit tests.
- Watch variance: with sampling, run each case a few times or use temperature 0 for evals.
- Monitor production: log inputs and outputs (respecting privacy), collect user feedback, and add real failures to the test set.
- Track cost and latency alongside quality — a 1% gain may not justify a much slower model.
Go further: Evaluating LLMs: Perplexity, Benchmarks and Judges covers benchmark scoring, pass@k and contamination.
Test yourself
Why is token F1 often used alongside exact match?
- It is faster
- It gives partial credit when the answer overlaps the reference
- It understands synonyms
- It checks JSON validity
What is a known weakness of LLM-as-judge?
- It can't read text
- It may prefer longer or more confident answers, so it should be validated against human ratings
- It always gives 5/5
- It requires no rubric
You found a failure in production. What should you do with it?
- Ignore it
- Add it to the test set so future versions are checked against it
- Delete the logs
- Increase the temperature