AI Eval
Mostly digested from Hamel Husain & Shreya Shankar's AI Evals FAQ. These are strong practical opinions rather than universal truths, and the numbers below (30, 100, 100–200, ...) are starting points, not statistical guarantees.
Mental Model
AI eval is a systematic way to measure whether your AI product does what you want it to do. It isn't just about the model, it covers the prompt, retrieval, tools, workflow, application code and the end-user experience as a whole.
- Model benchmark: compares general model capabilities (MMLU, GPQA, SWE-bench). Useful for picking a model, but says nothing about whether your product works.
- Product eval: targets your own workflows and failure modes, e.g. does the order-cancelling agent pick the right order, and does it only reply "done" after the tool call actually succeeded.
The most important idea is to look at real outputs and find failures first, then decide what to measure. Don't start with generic metrics such as "helpfulness" or "hallucination".
Collect traces → Manual error analysis → Failure taxonomy → Build evaluators → Improve system
↑ │
└──────────────────────────────────────────────────────────────────────────────┘
Eval is a continuous improvement loop, not a static leaderboard.
Terminology
| Term | Meaning | Example |
|---|---|---|
| Eval case | A scenario to test along with its required data | "Should explicitly refuse when no data is found" |
| Evaluator / Grader | Function or process that decides Pass/Fail for a case | JSON Schema, code assertion, LLM judge |
| Eval set | A repeatable collection of cases | 100 core flows, past bugs, edge cases |
| Trace | Full record from user request to result | messages, retrieved docs, tool calls, latency |
| Rubric | Clear judging rules for humans or a judge | "Every key number in the answer must have a source" |
Traces
A trace is the raw material of evals. It is more than the final answer, it should be able to reconstruct the entire path of a request, especially for multi-turn conversations and agents.
{
"trace_id": "tr_20260922_001",
"input": {"user_query": "Show me the maintenance history of P-101"},
"messages": [...],
"retrieval": [{"doc_id": "m-88", "score": 0.81}],
"tool_calls": [{"name": "search_asset", "args": {"tag": "P-101"}, "ok": true}],
"output": "The last maintenance of P-101 was on ...",
"metadata": {"prompt_version": "v17", "model": "...", "latency_ms": 2840},
"feedback": null
}
The minimum to record:
- Input, final output, system and prompt version
- Retrieval results (doc IDs, ranking, scores)
- Tool name, arguments, return value, exceptions and retries
- Model, tokens, latency, cost and timestamp
- Session / trace ID and the order of each step
- User feedback, human labels and evaluator results
Define retention, access control, masking and deletion policies first. Sensitive content can go through PII redaction, field-level access control, or be evaluated inside a secure environment. Don't keep raw conversations indefinitely just for the sake of evals.
Error Analysis
Find the problems first, then build the ruler. Spending 30 minutes manually reading 20–50 outputs early on is worth more than building a big platform. A more complete round would prepare ~100 diverse traces, with a domain expert personally annotating at least the first 30 in an open-ended way.
- Sampling: keep a random sample, then add targeted samples such as failure flags, negative feedback, long conversations, retries, abnormal latency and clustering.
- Open coding: write free-form notes on "what's bad from the user's point of view". Don't let an existing rubric constrain you, and note down the first upstream failure.
- Axial coding: group similar notes into a failure taxonomy, and count frequency and impact.
- Iterate: find similar cases, accept or reject AI suggestions, until new traces no longer produce new categories (theoretical saturation).
Example failure taxonomy of an enterprise knowledge assistant:
| Failure mode | Definition | Severity | Suitable evaluator |
|---|---|---|---|
| Ungrounded key facts | Answer contains numbers or status not supported by the docs | High | LLM judge + citation assertion |
| Wrong asset | Asked about P-101 but used P-110's data | High | Code check on tool args / IDs |
| Missing source | Has an answer but no doc ID / URL | Medium | Structure or regex check |
| Overly verbose | Exceeds the product's length limit and hurts usability | Low | Length rule, judge if needed |
Lean exploratory at first (random + clustering), then lean targeted once you understand the problems (classifier + feedback + known signals). Always keep some random samples in each batch so you're not only looking at the "known unknowns".
Designing Evals
Turn failure modes into evals, starting with the cheapest and most reliable method.
| Priority | Method | When to use | Example |
|---|---|---|---|
| 1 | Code assertion | Objective and deterministically computable | JSON parses, tool args correct, DB written exactly once |
| 2 | Reference-based | Known answer or executable result exists | SQL execution result, unit tests, expected document set |
| 3 | Human review | Exploring new errors, building gold labels | Domain correctness, communication quality |
| 4 | LLM judge / classifier | Needs judgement and must scale human effort | Faithful to context, handoff reasonable |
| 5 | Online experiment | Validating real product impact | A/B: completion rate, adoption, retention |
Prefer binary Pass/Fail outputs. A 1–5 score leads to "what's the difference between a 3 and a 4?". If quality has multiple dimensions, split it into multiple binary checks, which are far easier to debug than a single fuzzy score.
An actionable rubric looks like:
Evaluator: grounded_key_facts
PASS: Every "key fact" in the answer is directly supported by the provided context.
FAIL: At least one key fact conflicts with the context, or has no support in it.
Out of scope: tone, length, missing non-critical details.
Key fact: dates, numbers, status, identity or action conclusions that would change the user's decision.
Output: {"label": "PASS|FAIL", "evidence": [...], "reason": "..."}
Composing an Eval Set
- Core: the most common, highest business value workflows.
- Regression: real bugs, added after being fixed to prevent recurrence.
- Edge: boundary and adversarial cases, e.g. empty data, ambiguity, tool timeout, malicious input.
- Slice: important segments such as language, persona, tenant, document type, length.
Purpose-built eval sets often grow to 100+ cases, but the point is to cover important flows and known failures while staying cheap enough to run frequently. More cases isn't always better.
LLM-as-a-Judge
An LLM judge is essentially a classifier, so don't trust it just because its output looks reasonable. Prepare trustworthy human labels for each failure mode, then measure how well it catches errors versus raising false alarms.
Human-labeled (100–200 per failure mode) → Train 10–20% → Dev 40–45% → Test 40–45%
These ratios are a starting suggestion from the source, not a hard rule. Acknowledge the uncertainty when data is scarce.
| Split | Purpose | Don't |
|---|---|---|
| Train | Few-shot examples, teaching the judge the rules | Use it to claim generalization performance |
| Dev | Iterate on prompt, choose model, inspect disagreements | Forget it gets overfitted after many rounds |
| Test | Final, independent validation | Tweak the prompt while looking at its results |
Confusion Matrix
What you actually need to look at:
| Human: has error | Human: no error | |
|---|---|---|
| Judge: Fail | True Positive (caught) | False Positive (false alarm) |
| Judge: Pass | False Negative (missed) | True Negative (correctly passed) |
- TPR / Recall =
TP / (TP + FN): how many real errors are caught. Prioritize when missing an error is costly. - TNR / Specificity =
TN / (TN + FP): how many good answers are correctly passed. Important when human review is expensive. - Precision =
TP / (TP + FP): when errors are rare in production, false positives can still overwhelm the team even with a high TNR, so evaluate against the real base rate.
Judge Prompt Principles
- Judge one clearly defined failure mode at a time.
- Provide the context needed to judge, but don't stuff in irrelevant trace data. Use ablation to test removing pieces one by one.
- Require structured output, cited evidence and a short reason.
- Treat human labels as ground truth and inspect disagreements case by case, rather than chasing an overall score.
- Align with a strong model first, then test the accuracy / cost / latency trade-off of smaller models.
Minimal Implementation
JSONL + Python is enough to start. Don't wait for a full platform.
eval_cases.jsonl
{"id":"e1","input":"Return the asset status","expected":{"asset_id":"P-101"}}
{"id":"e2","input":"What about an unknown asset?","expected":{"must_refuse":true}}
Python runner (replace run_system with your agent entry point)
import json
from dataclasses import dataclass, asdict
@dataclass
class Result:
case_id: str
passed: bool
checks: dict
output: str
def run_system(user_input: str) -> dict:
"""Return output, tool_calls, retrieved_docs, etc."""
raise NotImplementedError
def evaluate(case: dict, run: dict) -> Result:
expected = case["expected"]
checks = {}
if "asset_id" in expected:
used_ids = [c["args"].get("asset_id") for c in run.get("tool_calls", [])]
checks["correct_asset"] = expected["asset_id"] in used_ids
if expected.get("must_refuse"):
checks["refused"] = run.get("decision") == "REFUSE"
# Empty checks is a misconfiguration, not an automatic pass
passed = bool(checks) and all(checks.values())
return Result(case["id"], passed, checks, run["output"])
results = []
with open("eval_cases.jsonl", encoding="utf-8") as f:
for line in f:
case = json.loads(line)
results.append(evaluate(case, run_system(case["input"])))
pass_all_rate = sum(r.passed for r in results) / len(results)
print(json.dumps({"pass_all_rate": pass_all_rate,
"results": [asdict(r) for r in results]}, ensure_ascii=False, indent=2))
Reports must be able to drill down. A single pass-all rate works as a release gate (a case only passes when all required checks pass), but the report should also show pass rates per evaluator, failure category and slice, otherwise the overall score can't tell you what to fix.
Overall pass-all: 82%
├─ correct_asset_id: 98%
├─ grounded_key_facts: 84%
├─ tool_success_before_claim: 91%
└─ zh-TW slice: 71% <-- the segment that actually needs investigating
CI/CD vs. Production Monitoring
| CI eval | Production monitoring | |
|---|---|---|
| Purpose | Prevent known regressions before deploying | Discover new failures, estimate occurrence and drift |
| Data | Small and curated, often 100+, fixed and versioned | Continuously sampled real traces |
| Method | Mostly deterministic, cheap, fast | Can run more expensive, reference-free judges asynchronously |
| Threshold | Critical checks block, non-critical only warn | Trends, confidence intervals, slices and alerts |
| Output | Release allowed or not + regression details | New failure taxonomy, incidents and new CI cases |
Git / Prompt / Model change → CI eval gate → Deploy → Online sampling & monitoring
↑ │
└── new failures added to CI ──┘
Production discovers new problems, CI makes sure the same problem doesn't come back.
Guardrail ≠ Evaluator
| Guardrail | Evaluator |
|---|---|
| Synchronous, in the request path | Usually asynchronous or batch |
| Millisecond-level, simple, explainable | Can use heavier LLM judges |
| Blocks PII, SQL injection, malformed output | Measures correctness, completeness, handoff quality |
| False positives are user-visible product bugs | Results feed dashboards, improvements and the regression loop |
Don't casually put a slow, non-deterministic LLM judge in a synchronous guardrail. Calculate latency and cost first, and compare the cost of "blocking good answers" against "letting bad answers through".
RAG, Conversations and Agents
RAG
Evaluate retrieval first, then generation.
- Retrieval
- Recall@k: how many relevant docs make it into the top-k.
- Precision@k: how many of the top-k are actually relevant.
- MRR: how high the first relevant result is ranked.
- Generation
- C|Q: is the context relevant to the question.
- A|C: is the answer faithful to the context.
- A|Q: does the answer address the question.
Debug in that order: confirm the right docs were found, then confirm the model used them correctly. Merging both into a single "RAG score" obscures the root cause.
Agents
Start end-to-end, then add step-level diagnostics.
- End-to-end task success: treat the agent as a black box, did it achieve the user's goal.
- Tool choice: did it pick the right tool.
- Parameter extraction: are the arguments complete and valid.
- Error handling: are empty results, timeouts and API failures handled properly.
- Context retention: does it keep earlier constraints.
- Efficiency: steps, seconds, tokens and cost.
- Goal checkpoints: are key milestones of long flows completed.
See also the planning failure metrics in Agent.
Multi-turn Conversations
First judge whether the whole conversation achieved the user's goal, and mark the first upstream failure. When it fails, reduce it to the simplest single-turn case. If the single-turn case still fails, the root cause is most likely not conversation memory. To generate test cases, use a user simulator, or take the first N−1 turns of a real conversation and predict the next step.
Human Handoff
Traces should extend until the request is actually resolved, not stop when the AI hands off. Record the handoff reason, timing, the context passed over, wait time, how the human handled it and the final result, and look at both handoff quality and handoff rate.
30-Day Rollout Plan
| Week | Goal | Deliverables |
|---|---|---|
| 1 | Observable and manually reviewable | Trace schema, sampling script, minimal annotation UI / notebook; manually review 30 traces |
| 2 | First version of the failure taxonomy | ~100 diverse traces, failure categories, frequency, severity, 3–5 priority problems |
| 3 | Build the cheapest evaluators | Structure checks, tool assertions, reference tests; start labeling judge data if needed |
| 4 | Plug into dev and production loops | Versioned eval set, CI report, online sampling, weekly review cadence with an owner |
Definition of done:
- Every evaluator maps to a real failure mode.
- Every case is reproducible, with app / prompt / model / dataset versions recorded.
- Deterministic evals cover Pass, Fail and important edge cases.
- Judges have an independent test set, TPR/TNR and an acceptable threshold.
- CI failures can drill down to the case and check.
- New production failures have a process to flow back into the regression set.
- A fixed owner regularly retires stale or signal-less evals.
Common Pitfalls
| Pitfall | Why it's a problem | Fix |
|---|---|---|
| Picking a vendor / metric first | The tool ends up defining which problems you can see | Do manual error analysis first, then choose tools |
| Chasing 100% pass | May mean tests are too easy or outdated | Keep challenging cases, add real failures |
| An LLM judge for every error | High cost in labeling and maintenance | Fix prompt / code first; prefer assertions |
| A single weighted overall score | Score improves but you don't know what improved for users | Pass-all + per check + per category / slice |
| Using dev as test | Repeated tuning causes overfitting | Keep an untouched final test set |
| Only sampling negative feedback | Users don't always report, known signals are biased | Keep random sampling in every batch |
| A gold set that never changes | Product and usage drift over time | Redo error analysis after major changes and every 2–4 weeks |
| Finding the root cause before noting the issue | Slows down review and leads to premature conclusions | Note the user-visible issue first, then prioritize and investigate |
Good AI eval isn't "scoring the model". It's turning the product team's judgement of quality into an observable, repeatable improvement system that guides the next engineering decision.
References
- AI Evals: Everything You Need to Know -- Hamel Husain & Shreya Shankar
- CI/CD vs. Production Monitoring -- Hamel Husain & Shreya Shankar