Evaluating and monitoring AI systems

An AI feature that cannot be measured cannot be improved safely. This guide explains how to build an evaluation set, which metrics to use for retrieval, generation, and agents, how to use a model as a judge without fooling yourself, and what to monitor in production.

Evaluation in 60 seconds

  • Start with an evaluation set: realistic inputs with known good answers or clear scoring rules. Without it, every change is a guess.
  • Measure the parts separately: retrieval, generation, and tool use fail in different ways.
  • LLM-as-judge is useful and biased. Calibrate it against human labels and keep a human-reviewed sample.
  • Agents need task-level scores such as success, steps, tool-call validity, and cost.
  • Monitor in production: record traces, track quality signals and cost, and feed real failures back into the evaluation set.

Why evaluation is the center of AI engineering

A prompt change that fixes one failing example can quietly break ten others. A model upgrade can improve average quality and ruin a case your biggest customer cares about. Without a way to measure, teams rely on a few memorable examples, and quality moves in whichever direction the latest complaint pushed it. An evaluation set turns that guesswork into a number you can track before every release.

Building the evaluation set

The set is a list of cases. Each case has an input, often some context, and a way to judge the result: a reference answer, a list of facts the answer must contain, a rule it must satisfy, or a rubric a reviewer will apply. Quality here matters more than quantity: fifty well-chosen cases beat a thousand copied ones.

  • Use real inputs. Sample from production logs, support tickets, or user research, and remove personal data.
  • Cover the range. Include common cases, hard cases, edge cases, and cases where the right answer is 'I do not know' or a refusal.
  • Include known failures. Every bug report becomes a case, so a fixed problem stays fixed.
  • Have experts write or review the expected answers. A weak reference answer makes the score meaningless.
  • Split the set. Keep a part hidden from the people tuning prompts, so you do not overfit to what you can see.
  • Version the set and keep the scores from each run.
One evaluation case with several ways to judge it (illustrative) (json)
{
  "id": "refund-014",
  "input": "I bought a course last week and want my money back. Is that possible?",
  "context_docs": ["policy/refunds-v7"],
  "expected_facts": ["refund window is 14 days", "digital products are refundable if less than 30% was viewed"],
  "must_not": ["promise a refund without checking viewing progress"],
  "tags": ["refunds", "policy", "multi-condition"]
}

What to measure

Different parts of an AI system fail in different ways, so each gets its own measures. A single overall score hides where the problem is.

PartMetricWhat it tells youHow to compute it
RetrievalRecall at kWas the right passage retrieved at all?Label the relevant passages; check the top k
RetrievalMean reciprocal rankHow high did the right passage rank?Average of 1 divided by the rank of the first right hit
GenerationFaithfulness (groundedness)Is every claim supported by the sources?Split into claims; check each against the retrieved text
GenerationAnswer correctnessDoes it match the expected facts?Check required facts; compare with a reference
GenerationRefusal accuracyDoes it decline when it should, and only then?Cases labelled 'should answer' and 'should refuse'
AgentsTask successDid the run reach the goal?A final-state check or a rubric
AgentsTool-call validity and stepsDid it use tools correctly and efficiently?Count invalid calls and steps per task
SystemLatency and cost per taskIs the quality worth the price?Record time and token cost for each case
Recall at k and reciprocal rank for retrieval (illustrative) (python)
# Illustrative: score the retriever alone, before any answer is generated.

def retrieval_scores(cases, retriever, k=5):
    recalls, rr = [], []
    for case in cases:
        retrieved = [r.id for r in retriever(case['question'], top_k=k)]
        relevant = set(case['relevant_ids'])
        recalls.append(1.0 if relevant & set(retrieved) else 0.0)  # any relevant passage found?
        rank = next((i + 1 for i, rid in enumerate(retrieved) if rid in relevant), None)
        rr.append(1.0 / rank if rank else 0.0)
    n = len(cases)
    return {'recall_at_k': sum(recalls) / n, 'mrr': sum(rr) / n}

Using a model as a judge

Many qualities, such as helpfulness, tone, or whether an answer is faithful to its sources, are hard to score with rules. A common solution is to use a language model as the judge: give it the question, the answer, any sources, and a rubric, and ask for a score with a short reason. It scales far better than human review, and it can be useful. It also has known weaknesses that you should design around.

  • Position bias: when comparing two answers, judges often favour the first or the second. Swap the order and average.
  • Length bias: longer answers often score higher. Include length in the rubric or compare answers of similar length.
  • Self-preference: a model may favour answers written in its own style. Use a different model as judge when you can.
  • Vague rubrics: 'rate the quality from 1 to 10' gives noisy scores. Use specific yes-or-no criteria and short scales.
  • Unchecked trust: a judge is a model with an error rate. Measure it.

Calibrate the judge against people. Have humans label a sample of a hundred or so cases, run the judge on the same cases, and compare. If they agree most of the time on the criteria you care about, you can rely on the judge for broad coverage and keep a smaller human review for spot checks. If not, fix the rubric before scaling.

A judge with specific criteria and a structured verdict (illustrative) (python)
# Illustrative: ask for yes or no on each criterion, not a vague score.
import json

JUDGE_PROMPT = '''You are grading an answer. Use only the sources provided.
For each criterion answer true or false, and give a one-sentence reason.
Criteria:
1. supported: every claim in the answer is supported by the sources.
2. complete: the answer covers every required fact: {required_facts}
3. safe: the answer makes no promise that the policy does not allow.

Question: {question}
Sources: {sources}
Answer: {answer}

Return JSON: {{"supported": {{"value": bool, "reason": str}}, "complete": {{...}}, "safe": {{...}}}}'''

def judge(case, answer, sources):
    prompt = JUDGE_PROMPT.format(required_facts=case['expected_facts'],
                                 question=case['input'], sources=sources, answer=answer)
    return json.loads(call_judge_model(prompt, temperature=0))

Evaluating agents

An agent run is a sequence of decisions, so checking only the final answer hides problems. Score the outcome, and also score the path.

  • Outcome: did the task finish with the right result? Prefer checks on the final state (the record was created, the test passes) over reading the text.
  • Path: how many steps, how many tool calls were invalid, did it repeat itself, did it ask for confirmation when it should have?
  • Safety: did it stay within permissions, and did it refuse the actions it should refuse?
  • Cost and time: tokens and seconds per task, with a budget for each.
  • Repeatability: run each task several times, because a single success can be luck. Report the success rate.
A small agent evaluation harness (illustrative) (python)
# Illustrative: run every task several times and score outcome, path, and cost.

def evaluate_agent(tasks, run_agent, repeats=3):
    report = []
    for task in tasks:
        runs = [run_agent(task['goal']) for _ in range(repeats)]
        report.append({
            'task': task['id'],
            'success_rate': sum(task['check'](r.final_state) for r in runs) / repeats,
            'avg_steps': sum(r.steps for r in runs) / repeats,
            'invalid_tool_calls': sum(r.invalid_calls for r in runs),
            'avg_cost_usd': sum(r.cost for r in runs) / repeats,
        })
    return report

Make evaluation part of the release process

An evaluation that runs only when someone remembers is not much use. Run it automatically on every change to a prompt, a model version, a retrieval setting, or a tool, and set thresholds. A change that lowers a key score beyond a limit should fail the build, the same way a failing unit test would. Store the scores of each run so you can see trends and compare versions.

A release gate that blocks regressions (illustrative) (python)
# Illustrative: compare a candidate against the current baseline and block regressions.

THRESHOLDS = {'recall_at_k': -0.02, 'faithfulness': -0.01, 'task_success': -0.02}  # allowed drops

def gate(baseline, candidate):
    failures = []
    for metric, allowed_drop in THRESHOLDS.items():
        drop = candidate[metric] - baseline[metric]
        if drop < allowed_drop:
            failures.append(f'{metric} fell by {abs(drop):.3f} (limit {abs(allowed_drop):.3f})')
    if failures:
        raise SystemExit('Release blocked: ' + '; '.join(failures))
    print('Evaluation gate passed.')

Observability: seeing the system in production

Offline evaluation tells you how the system behaves on cases you chose. Production tells you what users actually do. Observability for AI adds a few items to the usual logs, metrics, and traces.

  • Traces for every request. Record the prompt version, the retrieved chunks and their scores, each tool call and result, the model and settings, token counts, latency of each step, and the final answer. A trace is the first thing you open when someone says 'it gave a wrong answer'.
  • Cost metrics. Tokens and money per request, per user, per feature, with alerts on spikes.
  • Quality signals. User feedback (thumbs, edits, retries), escalations to a human, refusal rate, and automated checks such as groundedness on a sample.
  • Drift. Compare the mix of questions and the scores over time, since new topics, new documents, and provider-side model changes can all shift quality without any change from you.
  • Privacy controls on logs. Redact personal data, restrict access, and set retention.

Prompt management

Prompts are code, and they should be treated as such: stored in version control, reviewed, tested, and released with a version number that appears in the traces. Keep each prompt as a template with named inputs, separate from application logic, so you can change it without redeploying everything. Some teams go further and describe the steps of a pipeline declaratively, then let an optimiser search for prompts that score best on the evaluation set, which puts the evaluation set at the centre of the workflow.

How to start

  • Write twenty to fifty real cases this week. Include failures you already know.
  • Score retrieval and generation separately if you use RAG.
  • Run it on every change, even by hand at first.
  • Add a judge model for qualities rules cannot check, and calibrate it against human labels.
  • Add tracing before launch, not after the first incident.
  • Feed real failures back into the set.

What this means for your role

Common mistakes

Further reading

Measure first, change second. A small, honest evaluation set will teach you more than a large collection of impressions.

Search topics

↑↓ to move · Enter to open · Esc to close