Contents (24 slides)
1 · Title2 · Three gulfs3 · Normal tests fail4 · What evals need 5 · Two kinds of metric6 · Per component7 · Synthetic queries8 · Error analysis 9 · Annotator10 · Subjectivity11 · Collaborative (1)12 · Collaborative (2) 13 · Chance agreement14 · Raw agreement15 · Kappa example16 · Takeaways 17 · Appendix18 · Reference-based19 · Examples20 · Reference-free 21 · Insights22 · Quantitative23 · Grounded theory24 · Class activity GlossaryCheck yourselfEvaluating your Agent: how to tell, with evidence, whether your agent is doing its job
Each slide gets the same treatment: what the slide says, the idea in plain words, an everyday analogy, a real-world example, and code wherever the slide only gives theory.
Code marked Ran it was actually run, and the output under it is real. Code that needs your OpenAI key has an example output under it, so learners can follow just by reading. Slide 9 has the annotator itself, live on the page: click through it.
The whole talk in one picture
An agent can sound confident and still be wrong, and asking the same thing twice can give two different answers. So "it looked fine when I tried it" isn't evidence. Evaluation means: write down what "good" means for your agent, build a set of realistic test questions, score every part of the agent (prompt, retrieval, tools, routing), read the failures to find patterns, and make sure the people (or the LLM judge) doing the scoring actually agree with each other.
One running example ties it all together: an inventory reorder advisor for a warehouse. The code folder evaluates its prompt, its RAG search, its tool calls and its router, and this page shows where each piece fits.
Why evaluating an agent is hard
Evaluating your Agent: is your agent doing its job?
by Shivank Agarwal
💡 In simple words
Building an agent is the easy half. The hard half is proving it works: on real questions, every time, for every part of the system. This talk is about that second half: evaluation, or "evals" for short.
🍛 Analogy: a new employee's probation
You don't confirm a new hire because their first answer sounded smart. You watch them on many real tasks, check the work against what a good result looks like, ask a couple of senior people for their opinion, and notice the mistakes they keep repeating. Evaluating an agent is the same, written down and repeatable.
🌍 The running example in the code
An inventory reorder advisor for a warehouse answers questions like "We have 210 units and a delivery arriving tomorrow. Should we reorder?" The code folder evaluates four parts of it:
| Code file | Part of the agent it evaluates | Slides |
|---|---|---|
prompt_evals_inventory.py | The system prompt: is Version 2 better than Version 1? | 2, 6, 8 |
rag_evals_inventory.py | Search + answer: which retrieval setup works best? | 6, 18, 20 |
tool_evals_inventory.py | Tool use: right calculator, right number of times, at what cost? | 6 |
langgraph_router.py | Routing: does each question reach the right specialist? | 4, 6 |
annotator.html + judge_agreement.py | Human review, and whether the LLM judge agrees with people | 9, 13–15 |
Why agents make mistakes: the three gulfs
▢ What the slide says
Three gaps sit between the developer, the data and the LLM:
- Gulf of Comprehension (developer ↔ data): developers struggle to fully understand their input data and how the pipeline behaves across different scenarios.
- Gulf of Specification (developer → LLM): what the user wants is often loosely written in prompts, leading to unclear tasks and inconsistent results.
- Gulf of Generalization (data → LLM): models behave unpredictably across different inputs, with biases and errors appearing in production.
🍛 Analogy: a new cook at your dhaba
- Comprehension: you've never looked at what customers actually order, so you train the cook on the wrong dishes.
- Specification: you tell the cook "make it tasty". Tasty for whom? How spicy? Vague instructions, inconsistent food.
- Generalization: the cook nails dal makhani in training, then a customer orders it with no onion and no garlic, and it all falls apart.
🌍 In the code
prompt_evals_inventory.py is a gulf-of-specification experiment. Version 1 of the prompt says only "You are an inventory management advisor. Answer the question." Version 2 spells out what a good answer contains (the principle, the real-world complication, the hidden misconception). The eval measures how much that clearer specification helps: in the example run, from 63% to 96% of checks passed.
Why traditional testing falls short for agents
▢ What the slide says
Non-deterministic
Unlike normal software, LLMs can produce different outputs for the same input.Subjective quality
Whether a response is good depends on context, what the user wanted, and domain expertise.Multifaceted
Success means checking accuracy, relevance, safety and user satisfaction at the same time.These make agent evaluation fundamentally different from classic software testing and ML testing.
💡 In simple words
A normal unit test has one right answer and checks it exactly:
assert add(2, 2) == 4 # same input, same output, every time
You can't write assert agent("Should we reorder?") == "...", because there are many good answers, worded differently each time, and "good" depends on who's asking. Classic ML testing doesn't fit either: it measures accuracy against one label per example, not "is this paragraph helpful, correct and safe?"
⌨️ Try it in code: same question, three times
"""Slide 3: ask the same question three times and compare the answers.""" from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() question = "Suggest one name for a stock-tracking app for small kirana stores. Reply with the name only." answers = [] for attempt in range(1, 4): reply = client.chat.completions.create(model="gpt-6-luna", reasoning_effort="none", messages=[{"role": "user", "content": question}]) answers.append(reply.choices[0].message.content.strip()) print(f"Attempt {attempt}: {answers[-1]}") print(f"\nSame input, {len(set(answers))} different answers.")
Attempt 1: StockSaathi Attempt 2: KiranaKhata Attempt 3: DukaanDost Same input, 3 different answers.
Three valid answers, all different. That's fine for brainstorming, but it means one run proves nothing: you need many test cases, and checks that accept any correct answer rather than one exact string.
🍛 Analogy: maths exam vs essay exam
A maths paper has an answer key: 42 is right, 41 is wrong. An essay paper needs a marking scheme ("mentions three causes", "gives an example"), and two teachers may still give different marks. Agents are essay exams.
What agentic evaluation needs
▢ What the slide says
- No universal solutions: each pipeline has to bridge the three gulfs in its own way.
- Context-specific metrics: success depends on your goals, not generic benchmarks.
- Evolving requirements: what you measure changes as the system and its users mature.
- Resource intensive: meaningful evaluation takes real time and domain expertise.
- Multiple components: each component of an agent needs its own evaluation.
Generic benchmarks often miss the real-world problems that matter most to your users.
🍛 Analogy: a car's annual service
The mechanic doesn't just drive round the block and say "seems fine". Brakes, tyres, battery and lights are each checked separately, with their own test. A car can have perfect brakes and a dead battery. An agent can have a great prompt and a broken router.
⌨️ Try it in code: evaluate just the router
The router in langgraph_router.py is one component. This test calls only the routing step on 9 questions with known correct routes, so a wrong answer can't hide a wrong route (or the other way round).
"""Slides 4 and 6: evaluate ONE component on its own. Did the router send each question to the right specialist? Put this file next to langgraph_router.py.""" from collections import Counter from langgraph_router import router # only the routing step, no specialist answers labelled = [ ("Stock is 120 and we sell 20 a day with a 4-day lead time. Do we order today?", "reorder"), ("How much safety stock should I keep for 95% service?", "reorder"), ("What order size minimises our total cost?", "reorder"), ("Diwali is coming. How should next month's demand estimate change?", "forecast"), ("Sales have grown 5% every month this year. What should I plan for Q1?", "forecast"), ("Is a 3-week moving average better than a 6-week one for fast movers?", "forecast"), ("Vendor X is 8% cheaper but late one delivery in four. Should we switch?", "supplier"), ("Which of our two packaging suppliers has the lower total cost?", "supplier"), ("Our supplier keeps delivering late. Should I raise my reorder point?", "reorder"), ] correct, confusion = 0, Counter() for question, expected in labelled: got = router({"query": question})["category"] correct += got == expected confusion[(expected, got)] += 1 print(f"{'✅' if got == expected else '❌'} {got:<9} (expected {expected:<9}) {question}") print(f"\nRouting accuracy: {correct}/{len(labelled)} = {correct / len(labelled):.0%}") labels = ["reorder", "forecast", "supplier"] print("\nConfusion (rows = expected, columns = routed to)") print(" " * 10 + "".join(f"{l:>10}" for l in labels)) for e in labels: print(f"{e:<10}" + "".join(f"{confusion[(e, g)]:>10}" for g in labels))
✅ reorder (expected reorder ) Stock is 120 and we sell 20 a day with a 4-day lead time. Do we order today?
✅ reorder (expected reorder ) How much safety stock should I keep for 95% service?
✅ reorder (expected reorder ) What order size minimises our total cost?
✅ forecast (expected forecast ) Diwali is coming. How should next month's demand estimate change?
✅ forecast (expected forecast ) Sales have grown 5% every month this year. What should I plan for Q1?
✅ forecast (expected forecast ) Is a 3-week moving average better than a 6-week one for fast movers?
✅ supplier (expected supplier ) Vendor X is 8% cheaper but late one delivery in four. Should we switch?
✅ supplier (expected supplier ) Which of our two packaging suppliers has the lower total cost?
❌ supplier (expected reorder ) Our supplier keeps delivering late. Should I raise my reorder point?
Routing accuracy: 8/9 = 89%
Confusion (rows = expected, columns = routed to)
reorder forecast supplier
reorder 3 0 1
forecast 0 3 0
supplier 0 0 2The one miss is interesting: "Our supplier keeps delivering late. Should I raise my reorder point?" mentions a supplier but is really a reorder question. That's exactly the kind of case to add to the router's instructions, and to keep in the test set.
🌍 Real world: why generic benchmarks miss things
A model can score highly on a public reasoning benchmark and still not know that stock arriving tomorrow counts when deciding to reorder. Only your questions, with your idea of a good answer, can catch that.
Metrics: what to measure
Evaluation metrics overview: two main categories
▢ What the slide says
Core purpose: measure the quality and reliability of an LLM pipeline in a systematic way, across different use cases.
- Reference-based metrics compare the LLM's output with a known correct answer, called the "reference" or "golden" output.
- Reference-free metrics judge the output by its own properties, or whether it follows rules, with no golden answer.
Which one you pick depends on what you're evaluating and what resources you have. Both have their own uses and trade-offs. (The appendix, slides 18–21, goes deeper into each.)
🍛 Analogy: two ways to check homework
Reference-based: the teacher has the answer key and compares. Reference-free: no answer key for an essay, so the teacher checks rules instead: is it on topic, under 500 words, no copied lines?
🌍 Both kinds, in the code folder
| Check in the code | Kind | Why |
|---|---|---|
| Prompt evals: "Expected Key Points" given to the judge | Reference-based | Each question has a written correct answer. |
| RAG evals: Recall@k against the passages each question needs | Reference-based | We know which passages are correct. |
| RAG evals: Answer Groundedness | Reference-free | Compares the answer with the retrieved text, not with a golden answer. |
| Tool evals: expected tools vs tools called | Reference-based | The expected tool list is the answer key. |
🧪 Reference-based or reference-free? Click your answer
Evaluation by components of the agent
▢ What the slide says
| Component | Metric category | Example metrics | Example |
|---|---|---|---|
| System | Operational | Latency, cost | Avg response time = 900 ms; cost per 1,000 queries = $1.20 |
| Prompting | Performance | Instruction adherence / accuracy, clarity, bias score | Adherence score = 92/100; ambiguity in 5% of prompts |
| RAG | Retrieval & generation | Precision@k, Recall@k, hallucination rate / groundedness, retrieval time, cache hit rate | Precision@3 = 78%; hallucination rate = 4%; cache hit = 65% |
| Planning | Task execution | Task completion rate, steps to completion, sub-goal success rate | Task completion = 85%; avg steps = 4.2; sub-goal success = 70% |
| Tool use | Tool invocation | Tool match accuracy, tool latency, tool error rate | Match accuracy = 88%; error rate = 2.5%; tool latency = 1.3 s |
💡 The metrics that need a definition
- Precision@k: of the k passages you retrieved, how many were useful? Recall@k: of the passages you needed, how many did you retrieve? Example from the RAG eval: a question needs passages [0, 1]; you retrieve [1, 11, 7]. Precision@3 = 1/3 (only passage 1 was useful), Recall@3 = 1/2 (you missed passage 0).
- Groundedness / hallucination rate: does every claim in the answer come from the retrieved text? A hallucination rate of 4% means 4 answers in 100 said something the sources don't support.
- Cache hit rate: how often a repeated question was answered from a saved result instead of calling the model again (faster and cheaper).
- Tool match accuracy: how often the agent picked the tool you expected.
🌍 Which code file measures which row
| Row | Measured in | Metrics it prints |
|---|---|---|
| System | tool_evals_inventory.py, and the demo below | Avg latency, total cost, cost per successful task |
| Prompting | prompt_evals_inventory.py | Accuracy, Clarity, Completeness pass rates |
| RAG | rag_evals_inventory.py | Recall@k, Context Relevance, Groundedness, Correctness |
| Planning (routing) | langgraph_router.py + the slide 4 test | Routing accuracy |
| Tool use | tool_evals_inventory.py | Precision, recall, calls per task, tool success rate |
⌨️ Try it in code: the System row, latency and cost
"""Slide 6, the System row: measure latency and cost per 1,000 queries.""" import time from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() INPUT_PRICE_PER_1M, OUTPUT_PRICE_PER_1M = 0.10, 0.50 # gpt-6-luna, USD (openai.com/api/pricing) queries = [ "What is a reorder point, in one sentence?", "We sell 40 units a day and lead time is 6 days. What is the reorder point without safety stock?", "Name two reasons to keep safety stock.", "What does EOQ balance?", "When is FEFO used?", ] latencies, tokens_in, tokens_out = [], 0, 0 for q in queries: start = time.perf_counter() reply = client.chat.completions.create(model="gpt-6-luna", reasoning_effort="none", messages=[{"role": "user", "content": q}]) latencies.append(time.perf_counter() - start) tokens_in += reply.usage.prompt_tokens tokens_out += reply.usage.completion_tokens n = len(queries) cost = tokens_in / 1e6 * INPUT_PRICE_PER_1M + tokens_out / 1e6 * OUTPUT_PRICE_PER_1M print(f"Queries : {n}") print(f"Avg response time : {1000 * sum(latencies) / n:.0f} ms (slowest {1000 * max(latencies):.0f} ms)") print(f"Tokens per query : {tokens_in / n:.0f} in, {tokens_out / n:.0f} out") print(f"Cost per 1000 queries = ${cost / n * 1000:.3f}")
Queries : 5 Avg response time : 840 ms (slowest 1320 ms) Tokens per query : 22 in, 48 out Cost per 1000 queries = $0.026
The slide's "$1.20 per 1,000 queries" is just an example. With gpt-6-luna at $0.10 per million input tokens and $0.50 per million output tokens, short answers cost a few cents per thousand. Longer prompts (RAG context, tool definitions) push it up, which is why cost is measured, not guessed.
🍛 Analogy: a restaurant's dashboard
Kitchen speed (latency), cost per plate (cost), whether the chef follows the recipe (prompting), whether the right ingredients come out of the store room (RAG), whether the order is completed (planning), and whether the right utensils are used (tools). One number can't describe a restaurant.
Test data and error analysis
Tips for generating synthetic test queries
▢ What the slide says
- Common pitfall: asking an LLM for test queries with no structure gives repetitive, generic questions.
- Step 1, define dimensions: the ways user behaviour varies. Product search: category, price range, brand. Customer support: issue type, mood, order context.
- Step 2, identify failures: aim at likely failure modes, found by testing or observation.
- Step 3, manual tuples: write about 20 combinations by hand, one value per dimension, e.g. (Electronics, Premium, Specific brand).
- Step 4, scale with an LLM: generate more structured tuples, then turn each tuple into a natural question, e.g. "Show me the latest high-end Bose headphones under ₹30,000."
- Tip: keep tuple generation and question writing as two separate steps, to avoid repetition.
🍛 Analogy: the exam paper blueprint
A good paper-setter doesn't write 50 random questions. They use a blueprint: chapters × difficulty × question type, and fill every cell. Ask an LLM "give me 50 questions" and you get 50 versions of the easiest chapter.
⌨️ Try it in code: dimensions → tuples → questions
The tuples are made by plain Python (every combination, then a spread of them). Only the last step uses the model, to phrase each tuple like a real customer would.
"""Slide 7: dimensions -> tuples -> natural queries, for a shopping app's support agent.""" import itertools import json import random from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() # Step 1: dimensions = the ways real users differ dimensions = { "issue": ["late delivery", "wrong item", "refund status", "damaged product", "payment failed"], "mood": ["calm", "frustrated", "angry", "confused"], "order_context": ["first order", "repeat customer", "order above ₹5,000", "cash on delivery"], } # Steps 2–3: every combination is a tuple; pick a spread of them (fixed seed = same picks every run) all_tuples = list(itertools.product(*dimensions.values())) random.seed(7) tuples = random.sample(all_tuples, 8) print(f"{len(all_tuples)} possible tuples, using {len(tuples)}\n") # Step 4: ONLY NOW ask the model to phrase each tuple as a real customer message prompt = ("Write one realistic customer-support chat message for each tuple (issue, mood, order context). " "Vary the wording and length like real customers in India do; don't mention the mood word itself. " 'Reply as JSON: {"queries": ["...", "..."]} in the same order.\n\n' + "\n".join(f"{i + 1}. {t}" for i, t in enumerate(tuples))) reply = client.chat.completions.create(model="gpt-6-luna", reasoning_effort="none", response_format={"type": "json_object"}, messages=[{"role": "user", "content": prompt}]) queries = json.loads(reply.choices[0].message.content)["queries"] for t, q in zip(tuples, queries): print(f"{str(t)}\n → {q}\n")
80 possible tuples, using 8
('refund status', 'angry', 'repeat customer')
→ I've ordered from you guys for 2 years and this is the first time my refund is stuck for 12 days. Where is my money??
('wrong item', 'calm', 'cash on delivery')
→ Hi, I received a different shampoo than the one I ordered (COD). How can I exchange it?
('damaged product', 'calm', 'order above ₹5,000')
→ The air fryer I ordered arrived with a cracked lid. It was a ₹6,499 order. Can you arrange a replacement please?
('late delivery', 'frustrated', 'order above ₹5,000')
→ My order was supposed to come on Monday, it's Thursday now. I paid over 5k for this, what's going on?
('late delivery', 'angry', 'repeat customer')
→ Third late delivery this month. I keep ordering from you and you keep letting me down. Fix this today.
('payment failed', 'frustrated', 'first order')
→ First time using your app and the payment failed but ₹1,240 got debited from my account. Not a great start.
('late delivery', 'confused', 'first order')
→ Hi, this is my first order. The tracking says "out for delivery" since yesterday. Is that normal?
('refund status', 'confused', 'order above ₹5,000')
→ I returned a ₹7,800 watch last week. The app shows "refund initiated" but nothing in my bank. Which account will it go to?Every message is clearly different, and you can see exactly which situation each one tests. If the agent fails on all the "angry + repeat customer" messages, you've found a failure mode, not a one-off.
🌍 Real world
Before launch, a support bot rarely has real user logs. Teams generate a few hundred structured test messages this way, then replace them with real (anonymised) user messages as soon as those exist. The dimensions stay useful: they tell you which kinds of user you haven't tested yet.
Error analysis
▢ What the slide says
Error analysis is the systematic process of examining model failures to identify recurring patterns, and using them to guide targeted improvements. It's a loop:
💡 In simple words
Don't fix the last mistake you happened to see. Read many failures, give each one a short label, count the labels, and fix the most common one first. Then run the evals again to check the fix worked and didn't break anything else.
🍛 Analogy: a hospital's case review
Doctors don't react to one bad outcome by changing every procedure. They review cases together, note what went wrong in each, and look for patterns ("five of eight readmissions missed the same follow-up test"). Then they change the one step that matters most.
⌨️ Try it in code: from reviewers' notes to the top failure mode
These are the notes a reviewer wrote on failed answers from the prompt eval (slide 9's annotator collects exactly this). Each note gets a short code, codes are grouped into categories, and the categories are counted.
"""Slides 8 and 23: from reviewers' notes to the most common failure modes (error analysis).""" from collections import Counter # Step 1 (open coding): a reviewer read each failed answer and wrote a note plus a short code. failed = [ ("Q1 PO arriving tomorrow", "Ignores the PO arriving tomorrow.", "ignores in-transit stock"), ("Q2 Demand jumped 40%", "'Keep an eye on demand' is not an action.", "vague, no action"), ("Q4 ROP of 70 units", "Confirms 70 without safety stock.", "accepts the user's wrong formula"), ("Q5 Perishable, 8-day cycle", "Says 8 < 10 days is fine; no FEFO.", "accepts the user's wrong assumption"), ("Q6 Class C item", "Treats every C item as unimportant.", "accepts the user's wrong assumption"), ("Q7 Supplier A vs B", "Never says which supplier to pick.", "vague, no action"), ("Q8 Never stock out", "Says 'pick a service level' but not how.", "vague, no action"), ("Q2 (second run)", "Raises ROP by 40% straight away.", "accepts the user's wrong assumption"), ("Q5 (second run)", "Long answer; action buried in the last line.", "too long to act on"), ] # Step 2 (axial coding): group the codes into a few bigger categories. category_of = { "ignores in-transit stock": "Misses the hidden edge case", "accepts the user's wrong formula": "Misses the hidden edge case", "accepts the user's wrong assumption": "Misses the hidden edge case", "vague, no action": "Not actionable", "too long to act on": "Not actionable", } # Step 3: count, so you fix the most frequent problem first. by_code = Counter(code for _, _, code in failed) by_category = Counter(category_of[code] for _, _, code in failed) print("Failure codes (open coding):") for code, n in by_code.most_common(): print(f" {n} {code}") print("\nFailure categories (axial coding):") for cat, n in by_category.most_common(): print(f" {n}/{len(failed)} {'█' * n} {cat}") top = by_category.most_common(1)[0][0] print(f"\nCore problem to fix first (selective coding): {top}") print("→ Prompt change to test next: 'Before answering, name the assumption hidden in the question and say whether it holds.'")
Failure codes (open coding): 3 vague, no action 3 accepts the user's wrong assumption 1 ignores in-transit stock 1 accepts the user's wrong formula 1 too long to act on Failure categories (axial coding): 5/9 █████ Misses the hidden edge case 4/9 ████ Not actionable Core problem to fix first (selective coding): Misses the hidden edge case → Prompt change to test next: 'Before answering, name the assumption hidden in the question and say whether it holds.'
The evidence says the biggest problem is missing the hidden edge case, not tone or length. So the next prompt change targets that, and the prompt eval is run again to check the pass rate goes up. This labelling method is called grounded theory, explained on slide 23.
Design a custom data annotator to speed up error analysis
▢ What the slide says
A sketch of a simple review screen: an evaluation function description at the top, Upload agent output and Download feedback buttons, the user query and the agent response on the left, 👍 / 👎 buttons in the middle, a qualitative reviewer feedback box on the right, and Previous, Submit feedback and Next buttons. Task: use an AI assistant to build this front end, then upload the CSV and annotate the data. (The slide suggests Qwen; any chat assistant works.)
💡 Why build your own instead of using a spreadsheet?
Reading 200 long answers in spreadsheet cells is slow and tiring, and tired reviewers get sloppy. A screen that shows one answer at a time, with big buttons and keyboard shortcuts, makes review several times faster. And because it's your screen, it shows exactly what your reviewers need (here: the reference answer, hidden until they want it).
⌨️ Try it here: the annotator, live
This is annotator.html from the code folder, preloaded with the 18 answers from the prompt eval's example run. Click 👍 / 👎, write a note, use Next, and try Download feedback: you get a CSV with your labels added. Keys: P = pass, F = fail, ← / → to move.
How it fits with the code:
⌨️ The prompt that builds it
The slide's task is to get an AI assistant to write this screen. A prompt like this one gets a working single-file page:
Build a single HTML file (no libraries, no server) for reviewing AI agent answers. - Dark background. Top: an editable "Evaluation function description" box, plus "Upload agent output" (CSV) and "Download feedback" buttons. - Show one row at a time: "User query" (orange box), "Agent response" (light box), big 👍 and 👎 buttons, and a "Qualitative reviewer feedback" text box. - Buttons: Previous, Submit feedback, Next. A progress bar: "12 of 50 annotated". - Find the question and response columns by name (question/query, response/answer). - Download = the original CSV plus two new columns: human_label (pass/fail), human_feedback. - Keyboard: P = pass, F = fail, arrow keys to move. Handle commas and line breaks in CSV fields.
⚠️ Careful: hide the judge's score while reviewing
The CSV also contains the LLM judge's scores. The annotator deliberately doesn't show them: if reviewers see "Judge: PASS" first, they tend to agree with it, and you lose an independent second opinion. Compare the two afterwards (slide 15).
Human reviewers: dealing with opinions
How to deal with the subjectivity of reviewers
▢ What the slide says
Two people taste the same piece of cheese: one says "Yummy!", the other "Yucky!". Neither is wrong. Solution: ask the neighbours, i.e. use collaborative evaluation, or appoint a benevolent dictator.
💡 The two options
Collaborative evaluation
Several reviewers label the same examples, measure how much they agree, discuss the disagreements and refine the rules until they agree. Slides 11–12 give the steps. Best when the decision really is shared, or reviewers come from different teams.Benevolent dictator
One trusted domain expert makes the final call, using a written rubric. Faster and more consistent. Best for small teams, or when one person clearly knows the domain best (the head chef decides what "tasty" means on this menu).🍛 Analogy: judging a cooking competition
Three judges taste each dish and score it on a sheet with fixed criteria (taste, presentation, creativity). If one judge always gives 9s and another always gives 5s, the organisers notice and talk to them. That's collaborative evaluation with a rubric.
🌍 Real world
For the inventory advisor, a warehouse manager and a demand planner may disagree about whether an answer is "clear enough". Writing down "clear = a manager could act on it without asking anything else" turns a matter of taste into a rule both can apply.
Collaborative evaluation process (1 of 2)
▢ What the slide says
A systematic way to build agreement and a high-quality labelled dataset:
- Assemble the team: a few domain experts and key stakeholders, for different perspectives.
- Draft an initial rubric: clear criteria with specific pass/fail examples that show the edge cases and where the line is.
- Select a shared dataset: 20–50 varied, challenging examples covering what reviewers will see in production.
- Independent annotation: each person labels the dataset alone, without discussion, so their own interpretations and the unclear spots show up.
💡 What a first rubric looks like (inventory advisor)
| Criterion | PASS example | FAIL example |
|---|---|---|
| Correct | "Don't reorder: the PO arriving tomorrow keeps you above 200." | "Reorder now to be safe." |
| Actionable | "Recalculate using the last 6 weeks' average." | "Keep an eye on demand." |
| Handles the hidden edge case | Mentions in-transit stock, shelf life, criticality… | Answers only the literal question. |
🍛 Analogy: board-exam moderation
Before marking thousands of papers, examiners all mark the same sample papers alone, then meet to compare. Where they differ, the marking scheme gets clearer ("give the mark if the unit is missing but the number is right").
Collaborative evaluation process (2 of 2)
▢ What the slide says
- Measure agreement: compute Inter-Annotator Agreement (IAA) to see how much reviewers agree and where the rubric needs work.
- Alignment session: discuss the disagreements, understand each person's reasoning, and refine the rubric together.
- Revise and iterate: update the rubric, re-label with the new guidelines, and measure IAA again.
- Finalise the rubric and gold set: a documented rubric plus a consensus-labelled golden dataset, ready for testing and quality checks.
This loop builds consistency through structured collaboration and produces the labelled data reliable evaluation is built on.
⌨️ Try it in code: steps 5 and 6 for three reviewers
"""Slides 11–12: three reviewers label the same 12 answers on their own. Where do they agree?""" from itertools import combinations from sklearn.metrics import cohen_kappa_score # P = pass, F = fail. Each reviewer labelled the same 12 agent answers without talking to the others. labels = { "Ops manager": "P F P F F F F P P P P P", "Planner": "P F P F F F P P P P F P", "Category lead": "P F P F P F F P P P P P", } labels = {name: row.split() for name, row in labels.items()} n = len(next(iter(labels.values()))) print("Pairwise Cohen's kappa (1.0 = perfect, 0 = no better than chance)") for a, b in combinations(labels, 2): print(f" {a:<14} vs {b:<14} {cohen_kappa_score(labels[a], labels[b]):.2f}") print("\nItems to bring to the alignment session (reviewers disagree):") for i in range(n): votes = {name: labels[name][i] for name in labels} if len(set(votes.values())) > 1: print(f" Answer {i + 1:>2}: " + ", ".join(f"{k} = {v}" for k, v in votes.items()))
Pairwise Cohen's kappa (1.0 = perfect, 0 = no better than chance) Ops manager vs Planner 0.66 Ops manager vs Category lead 0.82 Planner vs Category lead 0.47 Items to bring to the alignment session (reviewers disagree): Answer 5: Ops manager = F, Planner = F, Category lead = P Answer 7: Ops manager = F, Planner = P, Category lead = F Answer 11: Ops manager = P, Planner = F, Category lead = P
The Planner disagrees with the others most (kappa 0.47 with the Category lead). Answers 5, 7 and 11 go to the alignment session. Typically the discussion reveals a rubric gap, such as "is a correct but very long answer a pass?", and the rubric gets one more line.
🌍 Real world
The finished gold set is gold in every sense: it becomes the test set every future prompt or model change must pass, and it's what you check an LLM judge against before trusting it to score thousands of answers on its own.
Why measure the agreement expected by chance?
▢ What the slide says
To know whether an evaluation is reliable, look beyond the surface agreement rate. When two evaluators agree, you need to know whether that's real consensus or just statistical coincidence.
💡 In simple words
Two reviewers who both say "pass" to almost everything will agree most of the time, even if they never really read the answers. So "we agree 80% of the time" might mean very little. You have to subtract the agreement they'd get by luck.
🍛 Analogy: the lazy true/false students
A test has 10 true/false questions and 8 answers are "True". Two students who don't study and just write "True" for everything both score 8/10, and agree on all 10 answers. 100% agreement, zero knowledge. Chance agreement is exactly this effect.
The problem with raw agreement
▢ What the slide says
Why raw numbers mislead: two evaluators often agree without truly being aligned. Shared habits, like marking most responses "acceptable", inflate the agreement score. A raw agreement percentage isn't a reliable signal of annotation quality.
Expected agreement by chance: how often would the evaluators agree if each labelled on their own, based only on how often they each use each label? This is the baseline you get from probability alone, not from real consensus.
🧪 Move the sliders: how much of the agreement is real?
Try setting both reviewers to 95% "Acceptable" with 90% raw agreement: kappa drops below zero. They agree less than two people labelling at random with those habits would.
A real-world example: Cohen's kappa
▢ What the slide says
- Annotator tendencies: Annotator 1 says Acceptable 60% / Unacceptable 40%. Annotator 2 says Acceptable 65% / Unacceptable 35%.
- Calculate chance: both Acceptable = 0.60 × 0.65 = 0.39; both Unacceptable = 0.40 × 0.35 = 0.14; total chance agreement = 53%.
- True alignment revealed: if raw agreement is 80%, only 27% reflects real consensus after removing the 53% chance baseline.
Key takeaway: Cohen's kappa removes chance agreement to show how reliable your human or LLM-judge evaluations really are.
⌨️ Try it in code: the slide's numbers, by hand and with scikit-learn
"""Slide 15, step by step: how much of 80% agreement is real, once chance is removed?""" from sklearn.metrics import cohen_kappa_score # Each annotator's habits (from the slide) a1_acceptable, a2_acceptable = 0.60, 0.65 raw_agreement = 0.80 chance_acceptable = a1_acceptable * a2_acceptable # both say "Acceptable" by luck chance_unacceptable = (1 - a1_acceptable) * (1 - a2_acceptable) # both say "Unacceptable" by luck chance = chance_acceptable + chance_unacceptable kappa = (raw_agreement - chance) / (1 - chance) print(f"Chance both say Acceptable : {a1_acceptable:.2f} × {a2_acceptable:.2f} = {chance_acceptable:.2f}") print(f"Chance both say Unacceptable : {1 - a1_acceptable:.2f} × {1 - a2_acceptable:.2f} = {chance_unacceptable:.2f}") print(f"Total chance agreement : {chance:.2f}") print(f"Raw agreement : {raw_agreement:.2f}") print(f"Agreement above chance : {raw_agreement:.2f} - {chance:.2f} = {raw_agreement - chance:.2f}") print(f"Cohen's kappa : ({raw_agreement:.2f} - {chance:.2f}) / (1 - {chance:.2f}) = {kappa:.2f}") # Same numbers as 200 real labels, checked with scikit-learn A, U = "Acceptable", "Unacceptable" annotator_1 = [A] * 105 + [U] * 55 + [A] * 15 + [U] * 25 # 105 both A, 55 both U, 40 disagreements annotator_2 = [A] * 105 + [U] * 55 + [U] * 15 + [A] * 25 print(f"\nAnnotator 1 says Acceptable: {annotator_1.count(A) / 200:.0%}, Annotator 2: {annotator_2.count(A) / 200:.0%}") print(f"They agree on {sum(x == y for x, y in zip(annotator_1, annotator_2))} of 200 items") print(f"scikit-learn cohen_kappa_score: {cohen_kappa_score(annotator_1, annotator_2):.2f}")
Chance both say Acceptable : 0.60 × 0.65 = 0.39 Chance both say Unacceptable : 0.40 × 0.35 = 0.14 Total chance agreement : 0.53 Raw agreement : 0.80 Agreement above chance : 0.80 - 0.53 = 0.27 Cohen's kappa : (0.80 - 0.53) / (1 - 0.53) = 0.57 Annotator 1 says Acceptable: 60%, Annotator 2: 65% They agree on 160 of 200 items scikit-learn cohen_kappa_score: 0.57
⚠️ Careful: the 27% is not kappa
The slide's 27% is percentage points above chance (80 − 53). Cohen's kappa divides that by the most agreement that was possible above chance: (0.80 − 0.53) / (1 − 0.53) = 0.57. Both numbers are useful, but when someone says "kappa", they mean 0.57. A common reading of kappa: below 0.20 slight, 0.21–0.40 fair, 0.41–0.60 moderate, 0.61–0.80 substantial, above 0.80 almost perfect. So these two annotators are in moderate agreement.
⌨️ From the code folder: does the LLM judge agree with a human?
Kappa is how you check an LLM judge too. judge_agreement.py reads the feedback file downloaded from the annotator (slide 9) and compares the judge's verdict with the reviewer's, answer by answer.
""" Can we trust the LLM judge? Compare its verdicts with a human reviewer using Cohen's kappa. By Shivank Agarwal. No model calls: this only reads a CSV. How to use: 1. Run prompt_evals_inventory.py -> prompt_eval_results.csv (the judge's scores) 2. Open annotator.html, upload that CSV, mark each answer 👍 / 👎, click "Download feedback" -> prompt_eval_results_feedback.csv 3. python judge_agreement.py prompt_eval_results_feedback.csv The judge "passes" an answer only if every score column is 1. The human label is pass / fail. """ import csv import sys 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.""" n = len(a) observed = sum(x == y for x, y in zip(a, b)) / n labels = set(a) | set(b) chance = sum((a.count(l) / n) * (b.count(l) / n) for l in labels) kappa = (observed - chance) / (1 - chance) if chance < 1 else 1.0 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" 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]] judge = ["pass" if all(r[c] == "1" for c in scores) else "fail" for r in rows] human = [r["human_label"] for r in 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(" 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")] 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") disagreements = [(r, j, h) for r, j, h in zip(rows, judge, human) if j != h] 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'})")
File: prompt_eval_results_feedback.csv (18 reviewed answers)
Judge passes an answer when all of these are 1: accuracy, clarity, completeness
Human: pass Human: fail
Judge: pass 10 1
Judge: fail 2 5
Raw agreement : 83%
Agreement by chance : 54% (judge passes 11/18, human passes 12/18)
Cohen's kappa : 0.64 → substantial agreement
Disagreements to discuss (3):
• [Version 1] Supplier A has a unit price of $10 with 30-day lead time. Supplier B h...
judge: pass (Mentions total cost including holding cost.)
human: fail (Never says which supplier to pick or how to compare them.)
• [Version 1] We ran out of stock last month. I want to set safety stock high enough...
judge: fail (Right idea, but doesn't say how to set safety stock.)
human: pass (Short, but right.)
• [Version 2] We have a perishable item with a 10-day shelf life. Our reorder cycle ...
judge: fail (Correct, but the action is buried in a long answer.)
human: pass (Long, but correct and the action is clear enough.)Kappa 0.64: the judge is usable but not yet trustworthy on its own. The three disagreements show why: the judge passed an answer that never says which supplier to pick, and failed two that a warehouse manager found perfectly usable. Each one is a line to add to the judge's prompt, after which you measure kappa again.
Key takeaways
▢ The eight takeaways, each with where you saw it
| Takeaway | In one line | Where |
|---|---|---|
| The 3 gulfs | Comprehension, specification and generalization gaps cause most agent mistakes. | Slide 2, prompt evals |
| Why agents are hard to evaluate | Different answers each time, quality is subjective, and many things must be right at once. | Slide 3 |
| Reference-free vs reference-based | Compare with an answer key when you have one; check rules and properties when you don't. | Slides 5, 18–21 |
| Component-wise evaluation | Score the prompt, retrieval, tools and routing separately. | Slides 4, 6, all four code files |
| Generating synthetic data | Dimensions → tuples → natural questions, in two separate steps. | Slides 7, 24 |
| Error analysis | Label failures, count them, fix the most common one first. | Slides 8, 23 |
| Custom annotators | A simple review screen makes human review fast and consistent. | Slide 9, annotator.html |
| Dealing with subjectivity | A rubric, collaborative review or one expert, and kappa to check agreement. | Slides 10–15 |
💡 If learners remember only three things
- One good-looking answer proves nothing: test many realistic questions, part by part.
- Read the failures and count them; fix what the evidence says, not what you guess.
- Before trusting any reviewer (human or LLM), check they agree with each other beyond chance.
Deeper dives and a class activity
Appendix
The slides after this go deeper into two topics from the main talk: the two kinds of metric (slides 18–21) and how to reason about what you find (slides 22–23), and end with a class activity (slide 24).
Reference-based metrics: definition and approach
▢ What the slide says
- Compare the LLM's output with a known correct answer, the "reference" or "golden" output.
- You must prepare correct reference answers for your test data in advance, like an official answer key for grading tests.
- Valuable during development as unit tests, and usually used in offline testing (before release).
💡 In simple words
Write the answer key once, then every time you change the prompt, the model or the retrieval, rerun the whole test set and compare. If yesterday 9/9 passed and today 7/9 pass, your change broke something, and you know which two questions to look at.
🌍 In the code
All three eval files are reference-based at heart: dataset in the prompt eval (each question with its "a" key points), eval_dataset in the RAG eval (each with a reference and its relevant_docs), and test_scenarios in the tool eval (each with its expected_tools).
Reference-based metrics: examples
▢ What the slide says
Simple
Exact string matching: does the output exactly match the reference? Good for short answers where precision is critical.Keyword verification: does the output contain the key words from the reference? More flexible, allows different wording.
Both suit objective comparisons with few acceptable variations.
Complex
Execution-based: run the generated SQL and compare its result table with the known correct result; run generated code against unit tests.Hybrid: run the generated code first, then let an oracle (LLM judge or human) judge its behaviour against the intended reference behaviour.
⌨️ Try it in code: exact match, keywords, and running SQL
"""Slides 18–19: grading against a known correct answer (the 'answer key').""" import sqlite3 print("1) EXACT MATCH: short answers where only one form is right") cases = [("Which ABC class is 5% of annual spend?", "C", "C"), ("Which ABC class is 75% of annual spend?", "A", "Class A")] for question, reference, output in cases: ok = output.strip().lower() == reference.lower() print(f" {'PASS' if ok else 'FAIL'} expected {reference!r}, got {output!r}") print("\n2) KEYWORD CHECK: the answer must mention the key facts, in any wording") reference_keywords = ["in-transit", "overstock"] answers = { "Answer A": "No. With the PO arriving tomorrow, in-transit stock pushes you above the ROP; ordering now risks overstock.", "Answer B": "No, 210 is above 200, so wait.", } for name, text in answers.items(): found = [k for k in reference_keywords if k in text.lower()] print(f" {'PASS' if len(found) == len(reference_keywords) else 'FAIL'} {name}: found {found} of {reference_keywords}") print("\n3) EXECUTION-BASED: run the generated SQL and compare the RESULT with the reference result") db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE stock (sku TEXT, on_hand INT, reorder_point INT); INSERT INTO stock VALUES ('SKU-001', 120, 150), ('SKU-002', 400, 200), ('SKU-003', 90, 90), ('SKU-004', 30, 60); """) reference_sql = "SELECT sku FROM stock WHERE on_hand <= reorder_point ORDER BY sku" generated = { "Model SQL 1": "SELECT sku FROM stock WHERE reorder_point >= on_hand ORDER BY sku", # different text, same result "Model SQL 2": "SELECT sku FROM stock WHERE on_hand < reorder_point ORDER BY sku", # misses the 'equal' case } expected = db.execute(reference_sql).fetchall() print(f" reference result: {[r[0] for r in expected]}") for name, sql in generated.items(): got = db.execute(sql).fetchall() print(f" {'PASS' if got == expected else 'FAIL'} {name}: {[r[0] for r in got]}")
1) EXACT MATCH: short answers where only one form is right PASS expected 'C', got 'C' FAIL expected 'A', got 'Class A' 2) KEYWORD CHECK: the answer must mention the key facts, in any wording PASS Answer A: found ['in-transit', 'overstock'] of ['in-transit', 'overstock'] FAIL Answer B: found [] of ['in-transit', 'overstock'] 3) EXECUTION-BASED: run the generated SQL and compare the RESULT with the reference result reference result: ['SKU-001', 'SKU-003', 'SKU-004'] PASS Model SQL 1: ['SKU-001', 'SKU-003', 'SKU-004'] FAIL Model SQL 2: ['SKU-001', 'SKU-004']
Two lessons hide in this output. Exact match failed "Class A" even though it's right: exact match is only for answers with one possible form. And Model SQL 1 is worded differently from the reference but returns the same rows, so it passes; Model SQL 2 looks almost identical but silently drops SKU-003. Comparing results, not text, catches both correctly.
🍛 Analogy: checking a recipe by tasting the dish
Two cooks can write the recipe differently and still make the same biryani. Execution-based evaluation tastes the dish (the result) instead of comparing the recipe cards (the text).
Reference-free metrics
▢ What the slide says
Judge the output by its own properties or by rules, without golden answers. Crucial for subjective, creative or open-ended outputs with many valid answers. Goal: check the desired properties of the output directly.
Text summarisation
The summary adds no speculative claims and no opinions that aren't in the source.Customer-service chatbot
The bot avoids definitive medical or financial advice and points the user to an expert.Code generation
Non-trivial logic has explanatory comments; no deprecated functions.Marketing copy
A clear call to action; no overly aggressive sales phrases that clash with the brand.⌨️ Try it in code: three property checks with simple rules
"""Slide 20: no answer key, so check properties the output must (or must not) have.""" import re print("CUSTOMER-SERVICE BOT: no definitive financial advice, and point to an expert") bot_replies = [ "You should definitely buy this fund now, it will double in a year.", "I can't recommend a specific fund, but a SEBI-registered adviser can look at your goals with you.", ] for reply in bot_replies: definitive = bool(re.search(r"\b(definitely|guaranteed?|will double|you should buy)\b", reply, re.I)) refers = bool(re.search(r"\b(adviser|advisor|expert|professional)\b", reply, re.I)) ok = not definitive and refers print(f" {'PASS' if ok else 'FAIL'} definitive={definitive}, refers to expert={refers}: {reply[:55]}...") print("\nMARKETING COPY: has a call to action, no pushy phrases") copies = [ "Our new rain jackets are here. Shop the collection today.", "LAST CHANCE!!! Buy now or regret it forever!", ] for text in copies: cta = bool(re.search(r"\b(shop|buy|order|sign up|book|try)\b", text, re.I)) pushy = bool(re.search(r"(!!|regret|last chance|act now)", text, re.I)) print(f" {'PASS' if cta and not pushy else 'FAIL'} call to action={cta}, pushy={pushy}: {text}") print("\nGENERATED CODE: comments on non-trivial logic, no deprecated functions") snippet = ''' import pandas as pd df = pd.read_csv("orders.csv") df = df.append({"sku": "SKU-009", "qty": 4}, ignore_index=True) rop = df.qty.mean() * 7 + 1.65 * df.qty.std() * 7 ** 0.5 ''' has_comment = "#" in snippet deprecated = ["DataFrame.append"] if re.search(r"\bdf\.append\(", snippet) else [] print(f" comments present: {has_comment} → {'PASS' if has_comment else 'FAIL'}") print(f" deprecated calls: {deprecated or 'none'} → {'FAIL' if deprecated else 'PASS'} (removed in pandas 2.0; use pd.concat)")
CUSTOMER-SERVICE BOT: no definitive financial advice, and point to an expert FAIL definitive=True, refers to expert=False: You should definitely buy this fund now, it will double... PASS definitive=False, refers to expert=True: I can't recommend a specific fund, but a SEBI-registere... MARKETING COPY: has a call to action, no pushy phrases PASS call to action=True, pushy=False: Our new rain jackets are here. Shop the collection today. FAIL call to action=True, pushy=True: LAST CHANCE!!! Buy now or regret it forever! GENERATED CODE: comments on non-trivial logic, no deprecated functions comments present: False → FAIL deprecated calls: ['DataFrame.append'] → FAIL (removed in pandas 2.0; use pd.concat)
Simple rules are fast, free and run on every single answer in production. For subtler properties ("is this summary faithful to the source?") use an LLM judge instead: the RAG eval's Answer Groundedness is exactly that, a reference-free check comparing the answer with the retrieved text.
⚠️ Careful: rules are blunt
A word list will miss "you can't go wrong with this fund" (definitive advice, no flagged word) and might flag an innocent sentence. Use rules as a first filter, check a sample of what they flag, and add an LLM judge where wording matters.
Reference-free metrics: key insights and choosing a strategy
▢ What the slide says
Application-specific quality
Reference-free qualities depend heavily on context and must be carefully defined for each use case.Production reality
Creating ground truth in real time is usually impractical in production, so self-contained checks are vital for reliability.Strategic selection
Choose the evaluation strategy based on available resources, specific quality needs and production constraints.No one-size-fits-all approach: the method depends heavily on what you're evaluating.
💡 A practical way to combine both
| When | What you have | Use |
|---|---|---|
| Before release (offline) | A gold set with answers | Reference-based: run the full test set on every change |
| In production (online) | Live questions, no answers | Reference-free: rules on every answer, an LLM judge on a sample |
| Every week | Flagged answers | Human review in the annotator, then add the hard cases to the gold set |
🍛 Analogy: a factory's quality control
New product designs are tested in the lab against specifications (reference-based). On the production line, every item passes quick automatic checks for weight and seal (reference-free), and a few are pulled out for a detailed inspection (human review).
How we usually reason about quantitative data
▢ What the slide says
The traditional way to build a theory about a system:
Example hypothesis: "Faster delivery increases customer trust scores by 20%." Not suitable for qualitative data!
💡 Why this doesn't work for agent failures
The delivery hypothesis works because you already know what to measure (delivery days, a trust score from 1 to 10) and can compare averages. With agent answers you don't know the categories in advance: you don't yet know that "ignores stock arriving tomorrow" is a failure type until you've read the answers. Starting from a hypothesis means you only find the problems you already guessed.
🍛 Analogy
Counting how many customers return within a week is quantitative: decide the question, then measure. Reading 50 complaint letters to discover why customers are unhappy is qualitative: the categories come out of the letters. Slide 23 is the method for the second kind.
Reasoning about qualitative data: the grounded theory approach
▢ What the slide says
Error analysis is based on the grounded theory approach: a structured investigation of an agent's mistakes to uncover their root causes in its reasoning and actions, so we can improve the agent rather than just score it.
💡 The steps on real notes (from slide 8)
| Reviewer's note | Open code | Axial category |
|---|---|---|
| "Ignores the PO arriving tomorrow." | ignores in-transit stock | Misses the hidden edge case |
| "Confirms 70 without safety stock." | accepts the user's wrong formula | |
| "Says 8 < 10 days is fine; no FEFO." | accepts the user's wrong assumption | |
| "'Keep an eye on demand' is not an action." | vague, no action | Not actionable |
| "Long answer; action buried in the last line." | too long to act on |
Selective coding picks the core concept: "the advisor trusts the user's framing of the question". That one idea explains most of the failures, and gives a clear fix to test: make the prompt name and check the question's hidden assumption first.
🍛 Analogy: sorting a pile of customer complaints
Read each letter and scribble a few words on it ("late", "cold food", "rude driver"). Put similar letters in piles ("delivery problems", "food quality"). Then ask: what's behind the biggest pile? Maybe "we promised 30 minutes for areas we can't reach in 30". That's your theory, and it came from the letters, not from a guess.
Class activity: personal portfolio manager agent
▢ What the slide says
You're testing an AI agent that helps users manage their investments. Users ask vague or repetitive questions, so you need structured test queries that cover different behaviours.
- Step 1, dimensions: asset type (stocks, mutual funds, crypto, bonds); goal (growth, income, risk management); action (buy, sell, hold, rebalance, compare).
- Step 2, tuples: e.g. (Stocks, Growth, Buy), (Crypto, Risk Management, Sell), (Mutual Funds, Income, Compare).
- Step 3, tuples into queries: "Which tech stocks should I buy for long-term growth?", "Should I sell my Bitcoin to reduce portfolio risk?", "Compare dividend-focused mutual funds that provide steady income."
Exercise: write code that uses dimensions → tuples → queries to generate 50 test queries for a portfolio manager agent, each sounding like something a real investor would ask.
⌨️ A solution
4 × 3 × 5 = 60 possible tuples; the code picks 50 different ones, then asks the model to phrase them 10 at a time (smaller batches give more varied wording) and saves everything to a CSV.
"""Slide 24 class activity: 50 test queries for a personal portfolio manager agent.""" import csv import itertools import json import random from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() dimensions = { "asset": ["Stocks", "Mutual Funds", "Crypto", "Bonds"], "goal": ["Growth", "Income", "Risk Management"], "action": ["Buy", "Sell", "Hold", "Rebalance", "Compare"], } all_tuples = list(itertools.product(*dimensions.values())) # 4 × 3 × 5 = 60 random.seed(42) tuples = random.sample(all_tuples, 50) # 50 different tuples queries = [] for start in range(0, len(tuples), 10): # 10 tuples per call keeps answers varied batch = tuples[start:start + 10] prompt = ("Turn each (asset type, goal, action) tuple into one question a real retail investor in India " "would type to an investing assistant. Mix short and long, casual and precise. " 'Reply as JSON: {"queries": [...]} in the same order.\n\n' + "\n".join(f"{i + 1}. {t}" for i, t in enumerate(batch))) reply = client.chat.completions.create(model="gpt-6-luna", reasoning_effort="none", response_format={"type": "json_object"}, messages=[{"role": "user", "content": prompt}]) queries += json.loads(reply.choices[0].message.content)["queries"] with open("portfolio_test_queries.csv", "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerow(["asset", "goal", "action", "query"]) writer.writerows([*t, q] for t, q in zip(tuples, queries)) print(f"Saved {len(queries)} queries to portfolio_test_queries.csv. First 8:\n") for t, q in list(zip(tuples, queries))[:8]: print(f"{t[0]:<13}{t[1]:<16}{t[2]:<10} {q}")
Saved 50 queries to portfolio_test_queries.csv. First 8: Crypto Risk Management Buy Is it safe to put 5% of my savings into Bitcoin, or will that make my portfolio too risky? Stocks Income Hold I hold ITC and Coal India for dividends. Should I keep them or switch? Stocks Growth Sell My small-cap stocks are up 60% this year. Time to book profits or let them run? Bonds Growth Hold Is it worth holding government bonds when I'm 28 and want my money to grow? Mutual Funds Growth Hold My flexi-cap SIP has been flat for 18 months. Continue or stop? Mutual Funds Growth Buy Which kind of mutual fund should I start a ₹10,000 monthly SIP in for 15-year growth? Stocks Risk Management Compare Nifty 50 index fund vs picking my own 10 large-cap stocks: which is less risky? Stocks Income Rebalance Half my portfolio is in one dividend stock. How do I spread it out without losing income?
⚠️ Things to discuss with learners
- Not every tuple makes sense. (Bonds, Growth, Hold) is unusual. Keep a few anyway: real users ask odd things, and the agent should handle them gracefully.
- Add the risky behaviours on purpose. A finance agent must not give definitive "buy this" advice (slide 20). Add a dimension such as tone (cautious / greedy / panicking) to test that.
- Test queries need expected behaviour. For each query, write down what a good answer must do (e.g. "explains the risk, doesn't promise returns"). Then you can evaluate the agent, not just question it.
Glossary
- Eval
- A repeatable test of how well an agent (or one part of it) does its job.
- Gold set / golden dataset
- Test questions with agreed correct answers or labels.
- Reference-based metric
- Compares the output with a known correct answer.
- Reference-free metric
- Checks properties or rules of the output, with no answer key.
- LLM-as-judge
- Using a model, with a strict scoring prompt, to grade another model's answers.
- Precision@k / Recall@k
- Of the k passages retrieved, how many were useful / of the passages needed, how many were retrieved.
- Groundedness
- Every claim in the answer is supported by the retrieved text (the opposite of hallucination).
- Tool match accuracy
- How often the agent called the tool you expected.
- Synthetic queries
- Test questions generated from dimensions → tuples → natural wording.
- Dimension / tuple
- One way users vary (e.g. mood) / one combination of values (angry, refund, first order).
- Error analysis
- Reading failures, labelling them, and counting labels to find what to fix first.
- Open / axial / selective coding
- Label each note / group labels into categories / find the core explanation.
- Annotator
- A review screen where people mark answers pass/fail and write why.
- Rubric
- Written pass/fail criteria with examples.
- Benevolent dictator
- One trusted expert who makes the final call on labels.
- Inter-annotator agreement (IAA)
- How much different reviewers agree on the same items.
- Chance agreement
- Agreement you'd expect from the reviewers' label habits alone.
- Cohen's kappa
- (observed − chance) ÷ (1 − chance): agreement beyond luck, from below 0 up to 1.
Check yourself (click to reveal)
1. Your prompt says "Answer the question." Answers are correct but miss edge cases. Which gulf is this?
The gulf of specification: what you want ("handle the hidden assumption") isn't written in the prompt. Version 2 of the prompt in the code fixes exactly this.
2. Why can't you test an agent with assert agent(q) == expected_text?
The same input gives different wording each time, and many different answers can be correct. Use keyword checks, execution checks, rules or an LLM judge with a rubric instead.
3. A question needs passages [2, 3]. You retrieve [3, 9, 2]. What are Precision@3 and Recall@3?
Precision@3 = 2/3 (two of the three retrieved were useful). Recall@3 = 2/2 = 1.0 (both needed passages were retrieved).
4. "Generate 50 test questions about refunds" gives near-duplicates. What's the fix?
Define dimensions (issue, mood, order context), build tuples in code, then ask the model only to phrase each tuple. Keep the two steps separate.
5. Two reviewers agree 85% of the time. Both mark 90% of answers "pass". Is that good agreement?
No. Chance agreement = 0.9 × 0.9 + 0.1 × 0.1 = 0.82. Kappa = (0.85 − 0.82) / (1 − 0.82) ≈ 0.17: only slight agreement beyond luck.
6. Is "the answer contains no investment advice" a reference-based or reference-free check?
Reference-free: it checks a property of the output, with no correct answer to compare against.
7. After error analysis, 6 of 9 failures are "misses the hidden edge case" and 1 is "too long". What do you change first, and how do you know it worked?
Change the prompt to make the advisor check the question's hidden assumption, then rerun the same eval set and compare Completeness (and the other metrics, to be sure nothing got worse).