Evaluating LLMs and agents
How to tell whether a gen AI system is good enough and stays that way: building evaluation datasets, computation-based vs model-based (LLM-as-a-judge) metrics, judge biases and how to control them, pointwise vs pairwise and rubric-based evaluation, Agent Platform Evals, agent trajectory metrics, safety evaluation, online monitoring, and statistics for comparing versions. Includes a win-rate confidence calculator.
1. Why LLM evaluation is different
Classic models have one right label per input. Generative outputs are open-ended: many answers can be right, wording varies run to run, and quality has several dimensions (correct, grounded, safe, helpful, on-format). So evaluation combines several kinds of metric over a fixed, versioned dataset, and runs on every change.
| When | Purpose |
|---|---|
| Model or tier selection | Which model meets the quality bar at the lowest cost? |
| Prompt and RAG iteration | Did this change help or hurt? |
| Before every release (CI) | Regression gate: prompt, model version, retrieval or tool changes |
| After tuning | Tuned model vs base model with prompting, on held-out data |
| In production | Online monitoring of sampled traffic, user feedback, safety |
2. Building the evaluation dataset
- Representative: sample real user questions (after removing PII), covering intents, languages and difficulty.
- Edge and adversarial cases: out-of-scope questions, ambiguous requests, prompt-injection attempts, questions the documents don't answer.
- References where possible: expected answers, expected source documents (for RAG), expected tool calls (for agents).
- Size: dozens for quick iteration, hundreds for release decisions; more for small differences (see the win-rate calculator).
- Versioned and frozen: store in Cloud Storage or BigQuery; never tune prompts on the final test split.
- Add every production failure you find to the dataset (it becomes a regression test).
3. Computation-based vs model-based metrics
| Type | Examples | Strengths | Weaknesses |
|---|---|---|---|
| Computation-based | Exact match, BLEU, ROUGE, JSON schema validity, tool-call validity and parameter match, regex checks | Cheap, fast, deterministic | Need references; penalize valid paraphrases; miss meaning |
| Model-based (LLM-as-a-judge, autorater) | Fluency, coherence, groundedness, instruction following, safety, helpfulness, custom criteria | Judge meaning without references; scale | Biased, costs tokens, must be validated against humans |
| Human evaluation | Expert ratings, side-by-side preferences | The ground truth for subjective quality | Slow, expensive, inconsistent between raters |
| Metric | Good for |
|---|---|
| Exact match | Classification labels, short factual answers, extracted fields |
| BLEU | N-gram precision against references: translation |
| ROUGE (ROUGE-L and variants) | N-gram / longest-common-subsequence recall: summarization against references |
| Schema validity | Structured output |
| Groundedness | RAG: answer supported by context |
| Instruction following, fluency, coherence, safety | Open-ended generation |
4. Pointwise, pairwise and rubrics
| Mode | How | Use when |
|---|---|---|
| Pointwise | Judge scores one response on a scale (for example 1–5) against criteria | Absolute quality tracking, thresholds, monitoring |
| Pairwise | Judge picks the better of two responses (baseline vs candidate) for the same prompt; report win rate | Comparing two models, prompts or settings; more sensitive to small differences |
| Rubrics | A list of specific, checkable criteria ("mentions the 30-day limit", "doesn't promise refunds for shipping") | Making judgements consistent and explainable |
| Adaptive rubrics | Agent Platform Evals generates prompt-specific rubrics, then checks responses against them | Diverse prompts where one generic rubric is too vague |
5. LLM-as-a-judge: biases and how to control them
| Bias | What happens | Mitigation |
|---|---|---|
| Position bias | Pairwise judge prefers the first (or second) response | Evaluate both orders and average or count only consistent wins; randomize order |
| Verbosity bias | Longer answers win regardless of quality | Rubrics that reward concision; length-controlled comparisons; check length vs score correlation |
| Self-preference | A judge favours outputs from its own model family | Use a different (often stronger) judge model; validate with humans |
| Leniency / score compression | Everything gets 4/5 | Clear rubrics with anchored examples per score; prefer pairwise or binary checks |
| Inconsistency | Same input, different score | Low judge temperature, multiple samples, explanations before scores |
| Domain blind spots | Judge lacks domain knowledge (medical, legal) | Give references or context to the judge; expert human review |
Validating the judge
- Have humans label a sample (for example 100–200 items) with the same rubric.
- Measure agreement between judge and humans: accuracy, and Cohen's kappa (agreement corrected for chance), or correlation for scores.
- Iterate on the judge prompt and rubric until agreement is acceptable; recheck when the judge model changes.
Kappa interpretation (rough): below 0.4 weak, 0.4–0.6 moderate, 0.6–0.8 substantial, above 0.8 strong. Use the calculator below.
6. Agent Platform Evals
Agent Platform Evals (formerly the Gen AI evaluation service) runs evaluations of models, prompts, RAG systems and agents.
| Capability | What to know |
|---|---|
| Datasets | Prompts, responses (or generate them during the run), references, context, expected trajectories |
| Computation-based metrics | Exact match, BLEU, ROUGE, tool-call validity, tool name and parameter match |
| Model-based metrics | Prebuilt pointwise and pairwise templates (fluency, coherence, safety, groundedness, instruction following, summarization and question-answering quality) and custom criteria |
| Adaptive rubrics | Per-prompt rubrics generated and checked automatically |
| Agent metrics | Trajectory and tool-use metrics; multi-turn task success |
| Results | Per-row scores and explanations, summary tables; logged to Experiments for comparison over time |
| Production | Online evaluation monitors on sampled live traffic; user and environment simulators for agents |
# Sketch with the Agent Platform SDK; module and metric names vary by release.
import pandas as pd
import vertexai
from vertexai.evaluation import EvalTask, PointwiseMetric, MetricPromptTemplateExamples
vertexai.init(project="PROJECT_ID", location="us-central1")
data = pd.DataFrame({"prompt": prompts, "response": responses, "reference": references})
task = EvalTask(dataset=data,
metrics=["exact_match", "rouge_l_sum",
MetricPromptTemplateExamples.Pointwise.GROUNDEDNESS],
experiment="support-bot-eval")
result = task.evaluate()
print(result.summary_metrics)
7. Evaluating agents: trajectories and tool use
For agents, the final answer isn't enough: the trajectory (sequence of tool calls) shows whether the agent got there safely and efficiently.
| Metric | Passes when |
|---|---|
| Trajectory exact match | Tool calls exactly equal the reference sequence |
| In-order match | All reference calls appear in order; extra calls allowed |
| Any-order match | All reference calls appear, in any order |
| Trajectory precision | Share of predicted calls that are in the reference (penalizes unnecessary calls) |
| Trajectory recall | Share of reference calls that the agent made (penalizes missed steps) |
| Single tool use | A specific required tool was called |
| Tool-call validity and parameter match | Calls are well-formed with correct arguments |
| Final response quality | Model-based metrics on the answer |
| Multi-turn task success | The user's goal was achieved over a whole conversation (often with a simulated user) |
8. Safety evaluation and red-teaming
- Red-teaming: deliberately try jailbreaks, prompt injection (direct and through documents or tools), harmful requests, data exfiltration and PII leakage before launch.
- Safety metrics: model-based safety scores, policy-violation rates, refusal rates on harmful prompts, over-refusal rates on benign prompts.
- Track both under-blocking (harmful content gets through) and over-blocking (legitimate users refused).
- Fairness: compare quality and refusal rates across languages, dialects and user groups.
- Controls under test: safety filters, Model Armor templates, system instructions, tool permissions.
9. Online evaluation and monitoring
| Signal | How |
|---|---|
| Sampled judge scores | Online evaluation monitors run metrics on a sample of live requests |
| User feedback | Thumbs up/down, edits, escalations to humans, task completion |
| Operational | Latency (time to first token, total), token usage, cost, error and 429 rates, safety blocks |
| Tracing | Per-request traces of retrieval and tool calls (Cloud Trace, Agent Runtime tracing) |
| A/B tests | Split traffic between prompt or model versions and compare business metrics |
10. Regression testing in CI/CD
- Store prompts, model version, retrieval settings and tools in version control.
- On every change, a pipeline (Cloud Build or a Pipelines run) generates responses for the frozen evaluation set.
- Compute computation-based checks (schema, exact match, tool calls) and model-based metrics; compare with the current production baseline.
- Gate: block the release if key metrics drop beyond a tolerance or safety checks fail.
- Log the run to Experiments for history; pin model versions so upgrades are deliberate and evaluated.
11. Win-rate and judge-agreement calculator
Pairwise win rate with a 95% Wilson interval (ties excluded), and Cohen's kappa between the judge and human labels.
12. Lab: evaluate two prompt versions and an agent
- Build a 50-row dataset from realistic questions with references (and expected sources for RAG).
- Run prompt A and prompt B. Compute exact match or ROUGE where references fit, and a pointwise groundedness or instruction-following metric.
- Run a pairwise comparison of A vs B; then swap the response order and rerun. How many verdicts flip (position bias)?
- Label 40 rows yourself; compute judge–human kappa with the calculator.
- For an ADK agent, write expected tool trajectories for 10 tasks; compute exact, in-order and any-order match, precision and recall.
- Wire the evaluation into a Cloud Build step that fails when groundedness drops by more than a set tolerance.
13. "Which evaluation method?" chooser
Pick an item to see what it means, why, and the tempting wrong choice.
14. Sample outputs
What the tools return. Expand an item to see a typical result and what to read in it.
Agent Platform Evals summary (simplified)Pairwise comparison of two prompt versions
metric candidate (grounded) baseline (ungrounded)
groundedness (pointwise, 1-5) 4.6 3.1
pairwise_quality win rate 0.71 0.22 (ties 0.07)
rouge_l 0.48 0.41
avg latency (s) 1.9 1.2What to look at: The grounded version wins 71% of pairwise judgements and is much more grounded, at the cost of 0.7 s more latency from retrieval. Before trusting the judge, spot-check its decisions against human labels on a sample.
15. Scenarios
Exam-style situations: how to diagnose each one, the likely cause and the fix.
16. Searchable reference
| Item | Meaning |
|---|
17. Flashcards (click to flip)
18. Common gotchas in one list
- Open-ended outputs need model-based or human evaluation; exact match and BLEU alone mislead.
- Pairwise for comparisons, pointwise for tracking.
- Validate the judge against humans before trusting it; measure agreement with kappa.
- Swap order in pairwise judging to cancel position bias.
- Long answers aren't better answers: watch verbosity bias.
- Don't let a model judge itself when you can avoid it.
- Small win margins on small sets are noise: compute an interval.
- Evaluate agent trajectories, not just final answers.
- Precision punishes extra tool calls; recall punishes missed ones.
- Frozen, versioned datasets with edge cases and past failures; run in CI on every change.
- Pin model versions so upgrades go through evaluation.
- Safety evaluation measures over-refusal too, not just harmful content.
- High ROUGE can hide wrong facts.
- Offline evaluation doesn't replace online monitoring and user feedback.