Skip to main content

AI Eval

info

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​

TermMeaningExample
Eval caseA scenario to test along with its required data"Should explicitly refuse when no data is found"
Evaluator / GraderFunction or process that decides Pass/Fail for a caseJSON Schema, code assertion, LLM judge
Eval setA repeatable collection of cases100 core flows, past bugs, edge cases
TraceFull record from user request to resultmessages, retrieved docs, tool calls, latency
RubricClear 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
Privacy

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.

  1. Sampling: keep a random sample, then add targeted samples such as failure flags, negative feedback, long conversations, retries, abnormal latency and clustering.
  2. 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.
  3. Axial coding: group similar notes into a failure taxonomy, and count frequency and impact.
  4. 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 modeDefinitionSeveritySuitable evaluator
Ungrounded key factsAnswer contains numbers or status not supported by the docsHighLLM judge + citation assertion
Wrong assetAsked about P-101 but used P-110's dataHighCode check on tool args / IDs
Missing sourceHas an answer but no doc ID / URLMediumStructure or regex check
Overly verboseExceeds the product's length limit and hurts usabilityLowLength rule, judge if needed
Sampling strategy

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.

PriorityMethodWhen to useExample
1Code assertionObjective and deterministically computableJSON parses, tool args correct, DB written exactly once
2Reference-basedKnown answer or executable result existsSQL execution result, unit tests, expected document set
3Human reviewExploring new errors, building gold labelsDomain correctness, communication quality
4LLM judge / classifierNeeds judgement and must scale human effortFaithful to context, handoff reasonable
5Online experimentValidating real product impactA/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.

SplitPurposeDon't
TrainFew-shot examples, teaching the judge the rulesUse it to claim generalization performance
DevIterate on prompt, choose model, inspect disagreementsForget it gets overfitted after many rounds
TestFinal, independent validationTweak the prompt while looking at its results

Confusion Matrix​

What you actually need to look at:

Human: has errorHuman: no error
Judge: FailTrue Positive (caught)False Positive (false alarm)
Judge: PassFalse 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 evalProduction monitoring
PurposePrevent known regressions before deployingDiscover new failures, estimate occurrence and drift
DataSmall and curated, often 100+, fixed and versionedContinuously sampled real traces
MethodMostly deterministic, cheap, fastCan run more expensive, reference-free judges asynchronously
ThresholdCritical checks block, non-critical only warnTrends, confidence intervals, slices and alerts
OutputRelease allowed or not + regression detailsNew 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​

GuardrailEvaluator
Synchronous, in the request pathUsually asynchronous or batch
Millisecond-level, simple, explainableCan use heavier LLM judges
Blocks PII, SQL injection, malformed outputMeasures correctness, completeness, handoff quality
False positives are user-visible product bugsResults feed dashboards, improvements and the regression loop
warning

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.

  1. End-to-end task success: treat the agent as a black box, did it achieve the user's goal.
  2. Tool choice: did it pick the right tool.
  3. Parameter extraction: are the arguments complete and valid.
  4. Error handling: are empty results, timeouts and API failures handled properly.
  5. Context retention: does it keep earlier constraints.
  6. Efficiency: steps, seconds, tokens and cost.
  7. 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​

WeekGoalDeliverables
1Observable and manually reviewableTrace schema, sampling script, minimal annotation UI / notebook; manually review 30 traces
2First version of the failure taxonomy~100 diverse traces, failure categories, frequency, severity, 3–5 priority problems
3Build the cheapest evaluatorsStructure checks, tool assertions, reference tests; start labeling judge data if needed
4Plug into dev and production loopsVersioned 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​

PitfallWhy it's a problemFix
Picking a vendor / metric firstThe tool ends up defining which problems you can seeDo manual error analysis first, then choose tools
Chasing 100% passMay mean tests are too easy or outdatedKeep challenging cases, add real failures
An LLM judge for every errorHigh cost in labeling and maintenanceFix prompt / code first; prefer assertions
A single weighted overall scoreScore improves but you don't know what improved for usersPass-all + per check + per category / slice
Using dev as testRepeated tuning causes overfittingKeep an untouched final test set
Only sampling negative feedbackUsers don't always report, known signals are biasedKeep random sampling in every batch
A gold set that never changesProduct and usage drift over timeRedo error analysis after major changes and every 2–4 weeks
Finding the root cause before noting the issueSlows down review and leads to premature conclusionsNote the user-visible issue first, then prioritize and investigate
TL;DR

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​