07. Evaluating Your Agent (Agent Evals)#
A fast, conceptual revision guide for 07-agent-evals. Focused on how to prove with evidence that an agent works — the three gulfs, reference-based vs. reference-free metrics, component-wise evaluation (prompt, RAG, tools, routing), synthetic test data, grounded-theory error analysis, human annotation, and calibrating LLM judges with Cohen's kappa.
Why Evaluating Agents Is Hard: The Three Gulfs#
Revision Notes#
Reference file: agent-evals-notes/evals_explained.html (Slides 1–4)
Concept#
Building an agent is only the first half of the job; proving with repeatable evidence that it works across realistic inputs and edge cases is the hard half. Unlike deterministic software (assert add(2, 2) == 4), an agent can sound confident while being factually wrong, or produce two differently worded answers to the same question.
Key Mental Models#
- The Three Gulfs (where agent failures come from):
- Gulf of Comprehension (developer ↔ data): Not truly understanding your real user inputs, edge cases, or how the pipeline behaves across scenarios.
- Gulf of Specification (developer → LLM): Writing loose, vague prompts ("Answer the question") that leave out domain rules, edge cases, and output expectations.
- Gulf of Generalization (data → LLM): Models behaving unpredictably on unseen or out-of-distribution production inputs, exposing biases or brittle reasoning.
- Why traditional software and ML tests fall short:
- Non-deterministic: The same input can yield different valid phrasings across runs.
- Subjective quality: Whether an answer is "good" depends on user intent, domain context, and audience (more like grading an essay than a math equation).
- Multifaceted: A single response must simultaneously satisfy accuracy, clarity, relevance, grounding, and safety.
- Why generic public benchmarks are not enough:
- High scores on public leaderboards do not prove an agent knows your domain rules (e.g., accounting for in-transit purchase orders before triggering a warehouse reorder).
- Effective agent evals must be context-specific, evolving as users mature, and component-wise (evaluating prompts, retrieval, tools, and routing independently).
Metric Categories & Component-Wise Evaluation#
Revision Notes#
Reference file: agent-evals-notes/evals_explained.html (Slides 5–6, 18–21)
Concept#
No single number can summarize an agent's health. Evaluation pairs two families of metrics (reference-based vs. reference-free) with component-level measurement so you can pinpoint which layer failed instead of guessing from end-to-end symptoms.
Key Mental Models#
- Reference-based metrics (compare output against a golden answer key):
- Simple checks: Exact string matching or keyword verification when acceptable variation is small.
- Complex checks: Execution-based (run generated SQL/code and compare results against expected outputs) and hybrid (execute first, then let an LLM judge or human verify behavior against reference intent).
- Best used: Offline during development and regression testing before release.
- Reference-free metrics (judge output properties or rules with no answer key):
- Checks directly whether the output obeys domain properties (e.g., no hallucinated claims outside retrieved context, no definitive financial/medical advice, clear call to action, no deprecated APIs).
- Best used: In live production where creating ground-truth answers in real time is impractical, and for open-ended or creative tasks.
- Practical combination across the lifecycle:
- Offline (before release): Run reference-based evals against the full golden dataset on every prompt, model, or retrieval change.
- Online (in production): Run fast reference-free rule checks on every response plus an LLM judge on a sample.
- Weekly loop: Send flagged answers to human review in the annotator, then promote hard edge cases into the golden dataset.
- Component-wise evaluation taxonomy:
- System (Operational): End-to-end latency, token cost, cost per successful task.
- Prompting (Performance): Instruction adherence, accuracy, clarity, completeness, bias.
- RAG (Retrieval & Generation):
Precision@k,Recall@k, context relevance, groundedness / hallucination rate, retrieval latency, cache hit rate. - Planning / Routing (Task Execution): Routing accuracy, task completion rate, steps to completion, sub-goal success rate.
- Tool Use (Tool Invocation): Tool precision, tool recall, tool match accuracy, tool error rate, tool latency, attribution.
Trade-Offs & Pitfalls#
- Keyword and rule checks are blunt: A banned-word filter misses paraphrased violations (e.g., "you can't go wrong with this fund") and can false-positive on safe phrasing. Use rules as a cheap first filter, then layer an LLM judge where nuance matters.
Prompt Evaluation & Strict LLM-as-Judge#
Revision Notes#
Reference files: agent-evals-code/prompt_evals_inventory.py, agent-evals-notes/component_evals_code_explainer.html
Concept#
Prompt evaluation tests whether a prompt change actually closes the Gulf of Specification. Rather than eyeballing one or two replies, you run both prompt versions across a golden set of tricky domain questions and score every answer with a strict binary LLM judge.
How It Works#
- Golden dataset: 9 tricky warehouse inventory questions (each with a hidden edge case such as in-transit stock, single-week demand spikes, critical Class C items, perishable FEFO cycles, or zero-variability safety stock) paired with expected key points.
- A/B prompt comparison:
- Version 1: Minimal one-line prompt (
"You are an inventory management advisor. Answer the question."). - Version 2: Explicit specification instructing the advisor to state the core formula/principle, contrast ideal vs. real-world cases, correct hidden misconceptions, and use concrete numbers from the question.
- Version 1: Minimal one-line prompt (
- Strict binary LLM-as-judge (
gpt-6-luna):- Uses JSON mode (
response_format={"type": "json_object"}) to return strict0(Fail) or1(Pass) scores on three criteria: Accuracy (no errors or misleading claims), Clarity (actionable without follow-up questions), and Completeness (addresses the specific hidden edge case). - Also outputs a one-line
Reasonper verdict and saves all rows toprompt_eval_results.csvfor human review.
- Uses JSON mode (
Trade-Offs & Pitfalls#
- Binary
0/1beats 1–5 scales: Ambiguous middle scores ("is this a 3 or a 4?") create noisy, inconsistent evaluations. Strict binary criteria force clear pass/fail boundaries. - Always record the judge's
Reason: Aggregate pass rates tell you that Version 1 failed; the one-line reasons tell you why so you can run error analysis. - Do not trust an unvalidated judge: An LLM judge can be systematically stricter or looser than domain experts — always validate it against human labels (see Section 8).
Code Reference#
import csv
import json
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # reads OPENAI_API_KEY from .env
client = OpenAI()
MODEL = "gpt-6-luna"
METRICS = ["Accuracy", "Clarity", "Completeness"]
# Resolve CSV path next to the script so results land consistently regardless of CWD
RESULTS_CSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompt_eval_results.csv")
def evaluate_response(question, expected_answer, actual_response):
"""LLM-as-judge: strict binary scores (0 = Fail, 1 = Pass) plus a one-line reason."""
# Binary 0/1 scoring avoids vague "3/5" middle-ground grades and forces the judge
# to make an actionable pass/fail call on each independent criterion.
eval_prompt = f"""Evaluate this inventory reorder advisor response with STRICT binary scoring (0=Fail, 1=Pass).
Question: {question}
Expected Key Points: {expected_answer}
Actual Response: {actual_response}
Be STRICT. Only give 1 if the criterion is fully met:
- Accuracy: Is the reorder recommendation correct with NO errors or misleading statements? (0 or 1)
- Clarity: Would a warehouse manager act on this WITHOUT further questions? (0 or 1)
- Completeness: Does it address the SPECIFIC edge case or nuance in the question? (0 or 1)
Respond ONLY with JSON in this exact shape:
{{"Accuracy": 0 or 1, "Clarity": 0 or 1, "Completeness": 0 or 1, "Reason": "one short sentence"}}"""
response = client.chat.completions.create(
model=MODEL,
reasoning_effort="none",
response_format={"type": "json_object"}, # JSON mode: the reply is always valid JSON
messages=[{"role": "user", "content": eval_prompt}],
)
verdict = json.loads(response.choices[0].message.content)
# -> {"Accuracy": 1, "Clarity": 0, "Completeness": 0,
# "Reason": "Does not account for the incoming PO arriving tomorrow."}
# Normalize int/string/bool values defensively in case the model returns "1" or true
scores = {m: 1 if verdict.get(m) in (1, "1", True) else 0 for m in METRICS}
# -> {"Accuracy": 1, "Clarity": 0, "Completeness": 0}
scores["Reason"] = str(verdict.get("Reason", ""))
return scores
def inventory_advisor(system_prompt, question):
"""The agent under test: answers an inventory question using the given system prompt."""
# Parameterizing system_prompt lets us benchmark v1 vs v2 prompts on the exact same dataset
response = client.chat.completions.create(
model=MODEL,
reasoning_effort="none",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": question},
],
)
return response.choices[0].message.content
# Golden edge-case dataset (e.g., on-hand stock + incoming PO already covers ROP)
dataset = [
{
"q": "Our safety stock formula says reorder at 200 units. We have 210 units on hand and a PO arriving tomorrow. Should we reorder now?",
# ... (see full file: prompt_evals_inventory.py)
$ python prompt_evals_inventory.py
=== Prompt v1 (basic) ===
Q1: Accuracy=1 Clarity=0 Completeness=0 | Does not account for the incoming PO arriving tomorrow.
Q2: Accuracy=0 Clarity=1 Completeness=0 | Recommends ordering without checking lead-time spike.
Summary v1 -> Accuracy: 60% Clarity: 70% Completeness: 40%
=== Prompt v2 (structured rubric + edge-case checklist) ===
Q1: Accuracy=1 Clarity=1 Completeness=1 | Clearly says do not reorder since 210 on hand + tomorrow's PO exceeds ROP.
Q2: Accuracy=1 Clarity=1 Completeness=1 | Adjusts order quantity for seasonal lead-time increase.
Summary v2 -> Accuracy: 90% Clarity: 90% Completeness: 80%
Saved detailed rows to prompt_eval_results.csv
RAG Evaluation: Separating Retrieval from Generation#
Revision Notes#
Reference files: agent-evals-code/rag_evals_inventory.py, agent-evals-notes/component_evals_code_explainer.html
Concept#
A RAG system has two distinct failure points: finding the right passages (retrieval) and answering faithfully from them (generation). Evaluating both separately tells you whether to fix your embeddings/top-k retrieval or fix your generation prompt.
How It Works#
Scoring deterministic Recall@k on the retriever independently from the LLM judge's RAG triad pinpoints whether failures stem from missing policy chunks (k too small) or unfaithful generation.
- Knowledge base & golden set: 12 inventory policy passages where several concepts span multiple documents (e.g., ROP basics in Doc 0 + safety stock in Doc 1; EOQ formula in Doc 2 + sensitivity in Doc 3), paired with 10 questions carrying both
relevant_docsand areferenceanswer. - Three configurations compared:
- Config A:
k=1, minimal prompt. - Config B:
k=2, structured prompt. - Config C:
k=3, grounded prompt ("Answer using ONLY the provided context... If the context is incomplete, say what's missing.").
- Config A:
- Four complementary metrics (exported to
rag_eval_results.csv):Recall@k(deterministic, reference-based): Fraction of requiredrelevant_docsactually retrieved. (AlongsidePrecision@k: fraction of thekretrieved passages that were actually useful.)- Context Relevance (judge): Did the retrieved context contain all facts needed to answer?
- Answer Groundedness (judge, reference-free): Is every claim in the answer explicitly supported by the retrieved context (zero hallucination or outside knowledge)?
- Answer Correctness (judge, reference-based): Does the generated answer match the reference answer's key facts?
Trade-Offs & Pitfalls#
- The
ktrade-off: Too small (k=1) starves multi-passage questions of critical caveats (lowRecall@kand Context Relevance). Too large increases noise, hurtsPrecision@k, and adds prompt tokens. - Correct ≠ Grounded: An LLM can score
1on Answer Correctness by leaking pretraining knowledge even whenRecall@kfailed — which is why Answer Groundedness must be scored strictly against the retrieved context alone.
Code Reference#
import csv
import json
import os
import numpy as np
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # reads OPENAI_API_KEY from .env
client = OpenAI()
MODEL = "gpt-6-luna"
EMBED_MODEL = "text-embedding-3-small"
NUM_QUESTIONS = 5 # set to 10 for the full run
# The classic RAG triad: isolates retriever failures (Context Relevance), hallucination
# (Answer Groundedness), and end-to-end factual accuracy (Answer Correctness).
METRICS = ["Context Relevance", "Answer Groundedness", "Answer Correctness"]
RESULTS_CSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "rag_eval_results.csv")
def evaluate_rag_response(question, retrieved_context, generated_answer, reference_answer):
"""LLM-as-judge: 3 binary scores (0/1) plus a one-line reason."""
# Separating the 3 checks pinpoints WHERE a RAG pipeline broke:
# low Context Relevance -> fix chunking/retrieval; low Groundedness -> tighten prompt.
eval_prompt = f"""You are evaluating a RAG system for inventory management. Be STRICT with scoring.
Question: {question}
Retrieved Context: {retrieved_context}
Generated Answer: {generated_answer}
Reference Answer: {reference_answer}
Evaluate these 3 metrics:
1. Context Relevance (0 or 1):
Does the retrieved context contain ALL information needed to fully answer the question?
Score 0 if the context is missing key facts mentioned in the reference answer.
2. Answer Groundedness (0 or 1):
Is EVERY claim in the generated answer explicitly supported by the retrieved context?
Score 0 if the answer includes ANY information not found in the context.
Score 0 if the answer adds details or numbers beyond what the context provides.
3. Answer Correctness (0 or 1):
Does the generated answer match the reference answer's key facts?
Score 0 if any key information is wrong or missing.
Respond ONLY with JSON in this exact shape:
{{"Context Relevance": 0 or 1, "Answer Groundedness": 0 or 1, "Answer Correctness": 0 or 1, "Reason": "one short sentence"}}"""
response = client.chat.completions.create(
model=MODEL,
reasoning_effort="none",
response_format={"type": "json_object"}, # JSON mode: the reply is always valid JSON
messages=[{"role": "user", "content": eval_prompt}],
)
verdict = json.loads(response.choices[0].message.content)
# -> {"Context Relevance": 0, "Answer Groundedness": 1, "Answer Correctness": 0,
# "Reason": "Top-1 chunk missed safety stock exception policy."}
scores = {m: 1 if verdict.get(m) in (1, "1", True) else 0 for m in METRICS}
# -> {"Context Relevance": 0, "Answer Groundedness": 1, "Answer Correctness": 0}
scores["Reason"] = str(verdict.get("Reason", ""))
return scores
# Mini knowledge base embedded once and queried across different top-k / chunking configs
documents = [
# Doc 0: Reorder point basics
# ... (see full file: rag_evals_inventory.py)
$ python rag_evals_inventory.py
Config: top_k=1
Q1: Rel=1 Grd=1 Cor=1 | Retrieved exact ROP formula and answered strictly from context.
Q2: Rel=0 Grd=1 Cor=0 | Top-1 chunk missed safety stock exception policy.
Averages -> Context Relevance: 60% Answer Groundedness: 100% Answer Correctness: 60%
Config: top_k=3
Q1: Rel=1 Grd=1 Cor=1 | All required facts retrieved and faithfully summarized.
Q2: Rel=1 Grd=1 Cor=1 | Retrieved both ROP and safety-stock exception chunks.
Averages -> Context Relevance: 100% Answer Groundedness: 100% Answer Correctness: 100%
Saved results to rag_eval_results.csv
Tool-Use Evaluation: Invocation, Efficiency, Attribution & Cost#
Revision Notes#
Reference files: agent-evals-code/tool_evals_inventory.py, agent-evals-notes/component_evals_code_explainer.html
Concept#
When an agent has callable tools (create_agent), getting the final prose right is not enough: you must verify that it picked the right tools, avoided unnecessary calls, executed without errors, actually used the tool's output, and met latency and cost targets.
How It Works#
- Test suite design (6 tools × 12 scenarios):
- Six
@toolcalculators/utilities (reorder_point_calculator,eoq_calculator,safety_stock_calculator,days_of_supply_calculator,abc_classifier,inventory_date_info). - Four scenario categories:
single_tool(6 cases),multi_tool(2 cases requiring two tools),ambiguous(2 cases where the tool is not named explicitly), andno_tool(2 conceptual questions the model should answer directly without calling tools).
- Six
- Trace-based instrumentation: After
agent.invoke(...), the evaluator inspectsAIMessage.tool_calls,AIMessage.usage_metadata(real input/output tokens), andToolMessageresults/errors directly from the message history.
Key Mental Models#
- Tool Invocation Accuracy:
- Tool Precision: Correct tool calls ÷ total tool calls made (catches wrong or unnecessary calls).
- Tool Recall: Expected tools actually called ÷ total expected tools (catches missed tools).
- Call Efficiency:
- Tracks average calls per task and classifies each task against
optimal_tool_countas optimal, over-calling (excess calls), or under-calling (too few calls).
- Tracks average calls per task and classifies each task against
- Execution & Attribution:
- Tool Success Rate: Share of tool invocations that completed without runtime/status errors.
- Attribution Rate: Checks whether the primary number returned by a tool actually appears in the agent's final answer — catching agents that call a calculator and then ignore or hallucinate over its result.
- Operational Economics:
- Average Latency (end-to-end wall time per task) and Cost per Successful Task (LLM input/output token cost + per-call tool cost ÷ successful tasks), classified into Low / Moderate / High tiers.
Trade-Offs & Pitfalls#
- Always include
no_toolandambiguousscenarios: Testing only explicit single-tool prompts hides over-eager tool calling and poor tool-description matching.
Code Reference#
import math
import re
import time
from dataclasses import dataclass, field
from datetime import date
from typing import Any, Dict, List, Optional
import pandas as pd
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.tools import tool
from langchain_core.messages import AIMessage, ToolMessage
from langchain_openai import ChatOpenAI
load_dotenv() # reads OPENAI_API_KEY from .env
# gpt-6-luna list prices, USD per 1M tokens (openai.com/api/pricing, Nov 2026). Update if they change.
# Tracked per agent trajectory so evals measure cost alongside tool-selection accuracy.
INPUT_PRICE_PER_1M = 0.10
OUTPUT_PRICE_PER_1M = 0.50
TOOL_COST_PER_CALL = 0.0 # these tools run locally, so they're free; set a price for paid APIs
# ---------------------------------------------------------------------------
# 1. Tools — deterministic Python calculators offload arithmetic from the LLM.
# Each @tool docstring becomes the schema description the agent reads to
# decide WHICH tool to call and WHAT arguments to pass.
# ---------------------------------------------------------------------------
@tool
def reorder_point_calculator(avg_daily_demand: float, lead_time_days: float, safety_stock: float = 0) -> str:
"""Calculate reorder point: ROP = (avg_daily_demand * lead_time_days) + safety_stock."""
rop = avg_daily_demand * lead_time_days + safety_stock
# -> 12 * 5 + 20 = 80.0 (Case 1)
return f"Reorder Point = {rop:.1f} units (demand {avg_daily_demand}/day × {lead_time_days} days lead time + {safety_stock} safety stock)"
@tool
def eoq_calculator(annual_demand: float, ordering_cost: float, holding_cost_per_unit: float) -> str:
"""Calculate Economic Order Quantity: EOQ = sqrt(2 * D * S / H)."""
# Guard against division by zero and return a clear message the agent can handle
if holding_cost_per_unit <= 0:
return "Error: holding cost must be > 0"
eoq = math.sqrt(2 * annual_demand * ordering_cost / holding_cost_per_unit)
# -> sqrt(2 * 10000 * 50 / 2) = 707.106... -> "707.1" (Case 2)
return f"EOQ = {eoq:.1f} units (D={annual_demand}, S=${ordering_cost}, H=${holding_cost_per_unit})"
@tool
def safety_stock_calculator(z_score: float, demand_std_dev: float, lead_time_days: float) -> str:
"""Calculate safety stock: SS = Z * σ_demand * sqrt(lead_time)."""
ss = z_score * demand_std_dev * math.sqrt(lead_time_days)
return f"Safety Stock = {ss:.1f} units (Z={z_score}, σ={demand_std_dev}, LT={lead_time_days} days)"
@tool
def days_of_supply_calculator(on_hand_units: float, avg_daily_demand: float) -> str:
"""Calculate days of supply remaining: DoS = on_hand / avg_daily_demand."""
if avg_daily_demand <= 0:
return "Error: daily demand must be > 0"
dos = on_hand_units / avg_daily_demand
return f"Days of Supply = {dos:.1f} days ({on_hand_units} units ÷ {avg_daily_demand} units/day)"
@tool
# ... (see full file: tool_evals_inventory.py)
$ python tool_evals_inventory.py
Case 1: "Demand is 12/day, lead time 5 days, safety stock 20. What's the ROP?"
Expected tool : reorder_point_calculator
Called tools : ['reorder_point_calculator'] [MATCH]
Answer match : PASS (80.0 found) | Latency: 1.12s | Cost: $0.000084
Case 2: "Annual demand 10,000, ordering cost $50, holding cost $2/unit. Find EOQ."
Expected tool : eoq_calculator
Called tools : ['eoq_calculator'] [MATCH]
Answer match : PASS (707.1 found) | Latency: 1.05s | Cost: $0.000079
Overall: Tool Selection = 100% (5/5) | Final Answer Accuracy = 100% (5/5) | Avg Latency = 1.18s
Routing & Planning Evaluation with LangGraph#
Revision Notes#
Reference files: agent-evals-code/langgraph_router.py, agent-evals-notes/component_evals_code_explainer.html
Concept#
In multi-specialist architectures, a router decides which downstream specialist handles a query. Because a misrouted question fails before the right specialist ever sees it, routing should be evaluated as its own standalone classification component.
How It Works#
Constrained Pydantic Literal output records the exact route decision in graph state so routing classification accuracy is measured separately from specialist prompt quality.
- Constrained structured output: A Pydantic
Routeschema withLiteral["reorder", "forecast", "supplier"]bound viallm.with_structured_output(Route)forces the router to emit exactly one valid category label. - Conditional graph edges: LangGraph's
StateGraphwiresadd_conditional_edges("router", route_edge, ...)to dispatch each query to the matching specialist node, where each specialist uses the same base model with a tailored system prompt. - Isolated evaluation: Because
state["category"]is recorded cleanly in the graph state, you can measure routing accuracy directly against expected labels before ever grading the specialist's prose.
Code Reference#
from typing import Literal, TypedDict
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import END, StateGraph
from pydantic import BaseModel
load_dotenv() # reads OPENAI_API_KEY from .env
llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
def ask(system, user):
"""One model call with a system prompt; returns the reply as plain text."""
return llm.invoke([SystemMessage(content=system), HumanMessage(content=user)]).text
# ---------- 1. The router: the model must pick exactly one of three labels ----------
# Constraining `category` with Literal guarantees LangGraph's conditional edge
# never receives an unexpected or hallucinated route string.
class Route(BaseModel):
category: Literal["reorder", "forecast", "supplier"]
router_llm = llm.with_structured_output(Route) # the reply is parsed into a Route object
class State(TypedDict):
query: str
category: str
response: str
def router(state):
# Explicit label definitions reduce misrouting on borderline inventory queries
decision = router_llm.invoke([
SystemMessage(content="Route the inventory query to one of: reorder, forecast, or supplier.\n"
"- reorder: reorder point, EOQ, safety stock, when to order\n"
"- forecast: demand prediction, adjusting forecasts\n"
"- supplier: comparing suppliers, lead times, vendor costs"),
HumanMessage(content=state["query"]),
])
# -> Route(category="reorder") for "When should we place our next order..."
return {"category": decision.category}
# -> {"category": "reorder"} (stored in State["category"] for conditional edge)
# ---------- 2. Three specialists: same model, different system prompts ----------
# Isolating each domain prompt lets us evaluate routing accuracy independently
# from specialist answer quality.
def reorder_node(state):
answer = ask("You are an inventory reorder specialist. Answer concisely using inventory "
"principles like ROP, EOQ, and safety stock.", state["query"])
return {"response": answer}
def forecast_node(state):
answer = ask("You are a demand forecasting specialist. Answer concisely using concepts like "
"rolling averages, seasonality, and trend.", state["query"])
return {"response": answer}
def supplier_node(state):
answer = ask("You are a supplier management specialist. Answer concisely using concepts like "
# ... (see full file: langgraph_router.py)
$ python langgraph_router.py
Query: "When should we place our next order if lead time is 7 days?"
Route: reorder
Answer: Calculate your reorder point as (average daily demand × 7 days) + safety stock, and place the order as soon as inventory position reaches that threshold.
Query: "Sales spike every December—how should we project Q4 demand?"
Route: forecast
Answer: Apply a seasonal index to your rolling baseline average so December's historical lift is reflected in the Q4 forecast.
Query: "Vendor A is 10% cheaper than Vendor B but has twice the lead time."
Route: supplier
Answer: Compare total landed cost—including the extra safety stock required for Vendor A's longer lead time—before deciding.
Synthetic Test Data, Error Analysis & Custom Annotators#
Revision Notes#
Reference files: agent-evals-code/annotator.html, agent-evals-notes/evals_explained.html (Slides 7–9, 22–24)
Concept#
Before launch you rarely have real user logs, and after running evals you need a disciplined way to turn messy failure traces into targeted fixes. Three practices close this loop: structured synthetic query generation, grounded-theory error analysis, and custom human annotation UIs.
Key Mental Models#
- Structured Synthetic Test Queries (two-step generation):
- Pitfall: Asking an LLM directly to "generate 50 test questions" produces repetitive, generic variants of the easiest case.
- Step 1 — Define dimensions & tuples: Identify the axes of user variation (e.g., for a portfolio manager: Asset Type × Goal × Action; for support: Issue Type × Mood × Order Context), target known failure modes, write ~20 manual tuples, then scale tuple combinations in code.
- Step 2 — Convert tuples to natural queries: Ask the LLM in small batches only to phrase each tuple as a realistic user question (keeping unusual and risky tuples to test edge-case handling), and pair each query with expected behavior.
- Replace synthetic queries with anonymized real user logs once in production, while keeping the dimensions to spot coverage gaps.
- Error Analysis & Grounded Theory:
- Why traditional quantitative reasoning falls short: Hypothesis-first testing assumes you already know what categories to measure. With agent outputs, you often do not know the failure modes until you read the failures.
- Grounded Theory (bottom-up coding):
- Open coding: Read failed outputs and attach short descriptive labels to each mistake (e.g., "ignores in-transit stock", "accepts user's wrong formula").
- Axial coding: Group related open codes into failure categories (e.g., "Misses the hidden edge case", "Not actionable").
- Selective coding: Synthesize the core root cause (e.g., "The advisor trusts the user's framing of the question").
- Evidence-driven iteration: Count failure frequencies, fix the most common root cause first (rather than the last bug you noticed), and rerun the full eval set to verify improvement without regressions.
- Custom Data Annotator (
annotator.html):- Reviewing hundreds of long responses inside spreadsheet cells causes fatigue and sloppy labels.
- A lightweight single-file review screen (
annotator.html) loadsprompt_eval_results.csvorrag_eval_results.csv, displays one item at a time with keyboard shortcuts (P= pass,F= fail,←/→navigate,Ctrl+Entersubmit), hides the reference answer behind a toggle, captures qualitative feedback notes, and exports..._feedback.csv. - Critical design rule: Deliberately hide the LLM judge's scores during human review so reviewers are not anchored by the judge and provide an independent second opinion.
Human Subjectivity & Judge Alignment (Cohen's Kappa)#
Revision Notes#
Reference files: agent-evals-code/judge_agreement.py, agent-evals-notes/evals_explained.html (Slides 10–16)
Concept#
Quality is subjective — two reviewers (or a human and an LLM judge) can look at the same response and disagree. Reliable evaluation requires turning taste into a written rubric and measuring chance-corrected agreement with Cohen's kappa before trusting a judge to scale.
Key Mental Models#
- Two ways to handle reviewer subjectivity:
- Collaborative evaluation: Assemble domain experts → write an initial rubric → label a shared sample independently → measure Inter-Annotator Agreement (IAA) → hold an alignment session on disagreements → refine the rubric and re-label → finalize the rubric and golden dataset. Best when multiple teams share ownership.
- Benevolent dictator: One trusted domain expert defines the rubric and makes final label calls. Faster and more consistent for small teams with a clear domain lead.
- Why raw agreement % misleads:
- If two raters both mark "pass" 90% of the time, they will agree on $0.9 \times 0.9 + 0.1 \times 0.1 = 82\%$ of items purely by chance — even if they label randomly.
- Cohen's Kappa ($\kappa$):
- Formula: $\kappa = \frac{p_o - p_e}{1 - p_e}$, where $p_o$ is observed raw agreement and $p_e$ is expected agreement by chance based on each rater's label frequencies.
- Example from the lecture: Rater 1 passes 60%, Rater 2 passes 65% → chance agreement $p_e = (0.60 \times 0.65) + (0.40 \times 0.35) = 0.53$. With 80% raw agreement, the gap above chance is 27 percentage points, and $\kappa = \frac{0.80 - 0.53}{1 - 0.53} = 0.57$ (moderate agreement).
- Landis & Koch interpretation (used in
judge_agreement.py):≤ 0.00poor,≤ 0.20slight,≤ 0.40fair,≤ 0.60moderate,≤ 0.80substantial,> 0.80almost perfect.
- Calibrating an LLM Judge (
judge_agreement.py):- Reads the human-annotated
..._feedback.csvfromannotator.html. - Treats the LLM judge as "pass" only when every score column (
accuracy,clarity,completenessorcontext_relevance,answer_groundedness,answer_correctness) equals1. - Prints the 2×2 confusion matrix, raw agreement, chance agreement, Cohen's kappa, and every disagreement (side-by-side judge reason vs. human feedback note).
- Each disagreement becomes a concrete rule to add to the judge prompt, after which you rerun and re-check kappa.
- Reads the human-annotated
Code Reference#
import csv
import sys
# Supports both prompt-eval CSVs and RAG-eval CSVs by detecting whichever metric columns exist
SCORE_COLUMNS = ["accuracy", "clarity", "completeness", # prompt evals
"context_relevance", "answer_groundedness", "answer_correctness"] # RAG evals
def cohens_kappa(a, b):
"""Agreement between two raters, after removing the agreement expected by chance."""
# Raw % agreement can look misleadingly high on imbalanced datasets (e.g. 90% passes);
# Cohen's kappa adjusts for random agreement so we know if the judge truly aligns with humans.
n = len(a)
observed = sum(x == y for x, y in zip(a, b)) / n
# -> 17 / 20 = 0.85 (85% raw agreement: 11 both-pass + 6 both-fail)
labels = set(a) | set(b)
# -> {"pass", "fail"}
chance = sum((a.count(l) / n) * (b.count(l) / n) for l in labels)
# -> P(both pass) + P(both fail) ≈ 0.54 (judge 13/20, human 12/20)
kappa = (observed - chance) / (1 - chance) if chance < 1 else 1.0
# -> (0.85 - 0.54) / (1 - 0.54) ≈ 0.67 -> "substantial"
return observed, chance, kappa
def describe(k):
"""Common reading of kappa values (Landis & Koch)."""
for limit, word in [(0, "poor"), (0.20, "slight"), (0.40, "fair"), (0.60, "moderate"), (0.80, "substantial")]:
if k <= limit:
return word
return "almost perfect"
if __name__ == "__main__":
path = sys.argv[1] if len(sys.argv) > 1 else "prompt_eval_results_feedback.csv"
# Ignore unlabelled rows so partial human review batches can still be measured
with open(path, encoding="utf-8") as f:
rows = [r for r in csv.DictReader(f) if r.get("human_label") in ("pass", "fail")]
if not rows:
sys.exit("No rows with a human_label of pass/fail. Annotate the file in annotator.html first.")
scores = [c for c in SCORE_COLUMNS if c in rows[0]]
# -> ["accuracy", "clarity", "completeness"]
# Strict all-or-nothing rollup: the judge passes an answer only if EVERY metric scored 1
judge = ["pass" if all(r[c] == "1" for c in scores) else "fail" for r in rows]
# -> 13 "pass", 7 "fail" across 20 rows
human = [r["human_label"] for r in rows]
# -> 12 "pass", 8 "fail" across 20 rows
print(f"File: {path} ({len(rows)} reviewed answers)")
print(f"Judge passes an answer when all of these are 1: {', '.join(scores)}\n")
# Print a 2x2 confusion matrix (judge vs. human) to spot strictness vs. leniency bias
print(" Human: pass Human: fail")
for j in ("pass", "fail"):
cells = [sum(1 for x, y in zip(judge, human) if x == j and y == h) for h in ("pass", "fail")]
# -> [11, 2] when j == "pass"; [1, 6] when j == "fail"
print(f" Judge: {j:<5} {cells[0]:>10} {cells[1]:>11}")
observed, chance, kappa = cohens_kappa(judge, human)
print(f"\nRaw agreement : {observed:.0%}")
print(f"Agreement by chance : {chance:.0%} (judge passes {judge.count('pass')}/{len(rows)}, "
f"human passes {human.count('pass')}/{len(rows)})")
print(f"Cohen's kappa : {kappa:.2f} → {describe(kappa)} agreement")
# Surface every disagreement with both rationales so you can refine the judge rubric
disagreements = [(r, j, h) for r, j, h in zip(rows, judge, human) if j != h]
# -> 3 mismatched (row, judge, human) tuples: 2 judge-pass/human-fail + 1 judge-fail/human-pass
if disagreements:
print(f"\nDisagreements to discuss ({len(disagreements)}):")
for r, j, h in disagreements:
tag = r.get("prompt_version") or r.get("config") or ""
print(f" • [{tag}] {r['question'][:70]}...")
print(f" judge: {j:<4} ({r.get('judge_reason', '')})")
print(f" human: {h:<4} ({r.get('human_feedback') or 'no note'})")
$ python judge_agreement.py prompt_eval_results_feedback.csv
File: prompt_eval_results_feedback.csv (20 reviewed answers)
Judge passes an answer when all of these are 1: accuracy, clarity, completeness
Human: pass Human: fail
Judge: pass 11 2
Judge: fail 1 6
Raw agreement : 85%
Agreement by chance : 54% (judge passes 13/20, human passes 12/20)
Cohen's kappa : 0.67 → substantial agreement
Disagreements to discuss (3):
• [v1] Our safety stock formula says reorder at 200 units. We have 210 units...
judge: pass (Addresses ROP and incoming PO clearly.)
human: fail (Missed explaining why PO transit risk matters)
• [v2] Supplier B doubled lead time from 4 to 8 days; should we double EOQ?...
judge: fail (Response was slightly wordy.)
human: pass (Correctly explained EOQ does not depend on lead time)
How All Building Blocks Connect#
Revision Notes#
Every file in 07-agent-evals fits into one continuous, evidence-driven improvement loop around the warehouse inventory advisor:
Structured synthetic tuples drive component evals, blind human annotation surfaces top failure modes via grounded theory, and Cohen's kappa aligns the LLM judge before each iteration.
Quick Self-Check Questions#
Self-Check Questions#
Your prompt says "Answer the question," and the agent gives technically accurate replies that miss hidden edge cases. Which of the Three Gulfs is this?
The Gulf of Specification — your expectations (handling hidden assumptions and real-world caveats) were not explicitly written into the prompt.
When should you use reference-based metrics vs. reference-free metrics?
Use reference-based metrics offline during development when you have a golden answer key (for regression testing). Use reference-free metrics in live production (and for open-ended tasks) where ground truth isn't available and you must check output properties like groundedness or policy compliance directly.
In RAG evaluation, why can an answer score 1 on Answer Correctness yet 0 on Answer Groundedness?
Because the LLM can answer correctly using its own pretraining knowledge even when the retrieved context lacked those facts. Groundedness strictly checks that every claim is supported by the retrieved passages.
What does Tool Attribution Rate measure in tool_evals_inventory.py, and why does it matter?
It checks whether the key numeric result returned by a tool actually appears in the agent's final response — catching agents that invoke the right calculator but ignore or overwrite its output.
Why should synthetic query generation separate tuple creation from natural-language phrasing?
Asking an LLM directly for many test queries produces repetitive variations of the easiest scenarios. Generating structured (dimension_1, dimension_2, ...) tuples first guarantees systematic coverage across edge cases before the LLM phrases each tuple into natural language.
Why does annotator.html hide the LLM judge's scores while a human is reviewing answers?
To prevent anchoring bias. If reviewers see "Judge: PASS" first, they subconsciously defer to it, destroying the independent ground truth needed to audit the judge.
Two reviewers agree 85% of the time, and both mark 90% of answers as "pass." Is this strong agreement?
No. Expected chance agreement is $0.90 \times 0.90 + 0.10 \times 0.10 = 0.82$, giving Cohen's kappa $\kappa = \frac{0.85 - 0.82}{1 - 0.82} \approx 0.17$ — only slight agreement beyond random chance.