Lesson 6: evals - see what’s getting better
Welcome to lesson six, our last lesson together. I'm glad you're here. We gave a model tools, put it in a loop, added memory, and taught it to see. Now we get to find out which changes helped.
A small change can look great in a few test runs and then fail on the next one. We'll build a small eval together: 10 cases, 3 runs each, and a little code to grade the 30 results. You can reuse it whenever you change your agent.
Give yourself more than a hunch
A model can answer the same prompt differently each time. Say you edit a description, try it five times, and get four good answers. Nice! But the old description might also pass four times. Running the same test on both versions gives you a fair comparison.
Our eval needs only three pieces: a list of prompts, a function that checks each run, and a loop that prints the score. It all fits in one file. No platform or dashboard needed.
edit the descriptiontry it a few times"seems better"
edit the descriptionrun 10 cases x 321/30 before, 27/30 after
Meet our tiny shop agent
We'll practice with a small support agent. It has three tools, and they all return pretend data. The agent can make mistakes here without touching a real order or anyone's money.
lookup_order(order_id)checks an order's status.search_orders(email)finds a customer's order ids.refund_order(order_id)moves money, so the agent should call it only when the customer asks for a refund.
- lookup_order needs an order id; returns status and total
- search_orders needs an email; returns order ids
- refund_order use only when the customer asks for a refund
We can now ask clear questions. Does the agent search even when it already has an order id? Does it invent an id? Does it mistake a complaint for a refund request? We record every tool call, so a small function can check each answer.
- user prompt
- model + 3 tools
- stubs answer
- trace: [{ name, input }]
- pass(calls)
- true / false
- marks per case: +-+
- total: 27/30
Start with the simplest grader that works
A grader does not need to be clever. It only needs a clear question and a dependable answer. For this agent, we can grade most cases by reading the tool calls.
- Read the trace when you care about the tools, their order, or their inputs. Lesson 3's DOM check worked this way.
- Check the result when you care about a new file, a passing test, or a changed database row.
- Ask another model when you need to grade writing. We'll try that later.
Give each run a pass or fail. A tone score of 7 out of 10 sounds useful, but it is hard to explain why the next answer gets an 8. Yes or no is easier to define and easier to count.
- Which tools ran, and in what order
- The order id or email it used
- A file, test, or database row
- Whether it made no call
- Does the reply sound polite?
- Does the summary keep the key fact?
- Check the judge before you trust it
Start with ten useful cases
Before changing a prompt or description, write down what you want the agent to do. Each case has a customer message and a small function that checks the tool calls. Writing the cases first keeps the comparison fair.
Some cases pass when the agent calls no tool. “Where is my order?” does not include an order id or email, so the agent should ask for one. Waiting for the missing detail is the helpful choice.
| # | User says | Passes when |
|---|---|---|
| 1 | Where is order A-1042? | first call is lookup_order with A-1042 |
| 2 | What's the status of my order? sam@example.com | first call is search_orders with that email |
| 3 | Order A-1042 arrived broken. Unacceptable. | never calls refund_order |
| 4 | Please refund order A-1042, it arrived broken. | calls refund_order with A-1042 |
| 5 | Refund my last order. sam@example.com | searches, then refunds the id the search returned |
| 6 | How much did order B-2210 cost? | first call is lookup_order with B-2210 |
| 7 | Thanks, that's all! | no tool calls |
| 8 | Where is my order? | no tool calls (it has to ask) |
| 9 | Cancel order A-1042. | never calls refund_order (there's no cancel tool) |
| 10 | Is the latest order for alex@example.com shipped? | searches, then looks up the id it found |
- 1 · 6 the id is here, so look it up
- 2 · 10 only an email, so search first
- 4 · 5 refund the order the customer asked about
- 3 a complaint is not a refund request
- 9 there is no cancel tool, so do not refund
- 7 · 8 there is nothing to do yet, so make no call
You do not need every case on day one. Start with mistakes you have already seen. When the agent surprises you again, save the prompt as case 11. Be extra careful around tools that cost money or cannot be undone.
Give each case a few chances
The model may make a different choice next time, so run each case
3 times. Ten cases become 30 runs. If each run uses
about two requests of 1,000 input tokens, the eval uses roughly
60,000 input tokens. Check usage after
your first run to see your number.
Three tries do not remove all the randomness, but they help. If the agent passes 80% of 30 runs, the standard error is √(0.8 × 0.2 ÷ 30), which is about 7 points. A move from 80% to 86% fits inside that noise. At 90 runs, the error drops to about 4 points while the token cost triples.
Use that estimate as a simple guide:
- If only one or two results change out of 30, run it again.
- If a case falls from 3/3 to 0/3, open its traces. That sharp change gives you a clear place to look.
- If the total moves by 15 points or more, repeat the eval. A second run helps confirm that the change holds up.
- 10 runs ±13 pts · 20k
- 30 runs ±7 pts · 60k
- 90 runs ±4 pts · 180k
Try two sets of descriptions
Now we can compare two versions. Variant A uses short tool descriptions. Variant B says when to use each tool, what input it needs, and when not to use it.
lookup_order:
"Look up an order."search_orders:
"Search orders."refund_order:
"Refund an order."
lookup_order:
have an id? never guess onesearch_orders:
email only, then lookup_orderrefund_order:
only on an explicit ask;
a complaint is not a request
- 10 cases x 3
- graders read traces
- evals/A.json
- total A
- 10 cases x 3
- graders read traces
- evals/B.json
- total B
Keep the system prompt, model, pretend data, and cases the same. If you change the description and model together, you will not know which one helped. Change one thing, then test it.
JavaScript example
If you prefer JavaScript, copy this into eval.mjs. Run it
with
VARIANT=A node eval.mjs, then
VARIANT=B node eval.mjs. Prefer Python? Skip to the next
example. Both versions do the same job.
# once
npm install @anthropic-ai/sdk
import Anthropic from "@anthropic-ai/sdk";
import { mkdir, writeFile } from "node:fs/promises";
const client = new Anthropic();
const MODEL = process.env.MODEL ?? "claude-opus-5-5";
const VARIANT = process.env.VARIANT ?? "A";
const RUNS = 3; // run each case three times
const MAX_TURNS = 6; // stop a run after six turns
const SYSTEM = "You are a support agent for a shop. Use the tools. If a tool needs " +
"something the customer hasn't told you, ask for it.";
// A and B use the same tools with different descriptions.
const DESCRIPTIONS = {
A: {
lookup_order: "Look up an order.",
search_orders: "Search orders.",
refund_order: "Refund an order.",
},
B: {
lookup_order: "Get the status and total of an order when you already have its order id " +
"(like A-1042). Never guess an id.",
search_orders: "Find a customer's orders by email when they gave no order id. Returns " +
"ids and dates, not statuses; call lookup_order for those.",
refund_order: "Refund an order in full. Only when the customer explicitly asks for a " +
"refund; a complaint is not a request. Money moves and cannot be undone.",
},
};
const d = DESCRIPTIONS[VARIANT];
const TOOLS = [
{ name: "lookup_order", description: d.lookup_order,
input_schema: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"] } },
{ name: "search_orders", description: d.search_orders,
input_schema: { type: "object", properties: { email: { type: "string" } }, required: ["email"] } },
{ name: "refund_order", description: d.refund_order,
input_schema: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"] } },
];
// Pretend answers only. These functions do not change anything.
const STUBS = {
lookup_order: ({ order_id }) => ({ id: order_id, status: "shipped", total: "$42.00" }),
search_orders: () => ({ orders: [{ id: "A-1042", date: "2026-09-30" }] }),
refund_order: () => ({ refunded: true }),
};
// The trace records each tool name and input in order.
const names = (calls) => calls.map((c) => c.name);
const first = (calls) => calls[0];
const CASES = [
{ id: "status by id", prompt: "Where is order A-1042?",
pass: (c) => first(c)?.name === "lookup_order" && first(c).input.order_id === "A-1042" },
{ id: "status by email", prompt: "What's the status of my order? sam@example.com",
pass: (c) => first(c)?.name === "search_orders" && first(c).input.email === "sam@example.com" },
{ id: "complaint is not a refund", prompt: "Order A-1042 arrived broken. Unacceptable.",
pass: (c) => !names(c).includes("refund_order") },
{ id: "explicit refund", prompt: "Please refund order A-1042, it arrived broken.",
pass: (c) => c.some((x) => x.name === "refund_order" && x.input.order_id === "A-1042") },
{ id: "search then refund", prompt: "Refund my last order. sam@example.com",
pass: (c) => names(c).indexOf("search_orders") !== -1 &&
names(c).indexOf("search_orders") < names(c).indexOf("refund_order") &&
c.some((x) => x.name === "refund_order" && x.input.order_id === "A-1042") },
{ id: "price by id", prompt: "How much did order B-2210 cost?",
pass: (c) => first(c)?.name === "lookup_order" && first(c).input.order_id === "B-2210" },
{ id: "no tool needed", prompt: "Thanks, that's all!",
pass: (c) => c.length === 0 },
{ id: "asks, doesn't guess", prompt: "Where is my order?",
pass: (c) => c.length === 0 },
{ id: "no cancel tool", prompt: "Cancel order A-1042.",
pass: (c) => !names(c).includes("refund_order") },
{ id: "search then lookup", prompt: "Is the latest order for alex@example.com shipped?",
pass: (c) => names(c).indexOf("search_orders") !== -1 &&
names(c).indexOf("search_orders") < names(c).indexOf("lookup_order") },
];
// Run one prompt and return its tool calls.
async function runOnce(prompt) {
const calls = [];
const messages = [{ role: "user", content: prompt }];
for (let turn = 1; turn <= MAX_TURNS; turn++) {
const reply = await client.messages.create({
model: MODEL, max_tokens: 1024, system: SYSTEM, tools: TOOLS, messages,
});
messages.push({ role: "assistant", content: reply.content });
if (reply.stop_reason !== "tool_use") return { calls };
const results = [];
for (const use of reply.content.filter((b) => b.type === "tool_use")) {
calls.push({ name: use.name, input: use.input });
results.push({ type: "tool_result", tool_use_id: use.id,
content: JSON.stringify(STUBS[use.name](use.input)) });
}
messages.push({ role: "user", content: results });
}
return { calls, capped: true }; // the run reached six turns
}
async function runCase(c) {
const runs = [];
for (let i = 0; i < RUNS; i++) {
try {
const { calls, capped } = await runOnce(c.prompt);
runs.push({ pass: !capped && c.pass(calls), calls });
} catch (err) {
// Show API errors separately from failed cases.
runs.push({ pass: false, error: String(err.message ?? err) });
}
}
return { id: c.id, runs };
}
const results = await Promise.all(CASES.map(runCase)); // cases run in parallel
let passed = 0, errors = 0;
for (const r of results) {
const marks = r.runs.map((x) => (x.error ? "!" : x.pass ? "+" : "-")).join("");
passed += r.runs.filter((x) => x.pass).length;
errors += r.runs.filter((x) => x.error).length;
console.log(`${marks} ${r.id}`);
}
const total = CASES.length * RUNS;
console.log(`\nvariant ${VARIANT} on ${MODEL}: ${passed}/${total} (${Math.round(100 * passed / total)}%)` +
(errors ? `, ${errors} API errors, rerun before you trust it` : ""));
await mkdir("evals", { recursive: true });
await writeFile(`evals/${VARIANT}.json`, JSON.stringify({ MODEL, VARIANT, results }, null, 2));
Each case gets a line of output. A plus means pass, a minus means fail,
and a bang means API error. +-- means the case passed once
and failed twice. The script also saves every tool call in
evals/A.json or evals/B.json.
- +++ status by id run 1 ✓ run 2 ✓ run 3 ✓ all three passed; move to the next case
- +-- complaint is not a refund run 1 ✓ run 2 ✗ run 3 ✗ open runs 2 and 3 to see what changed
- !++ explicit refund run 1 API error run 2 ✓ run 3 ✓ the API failed on run 1, so try it again
Python example
If you prefer Python, use this version. It runs the same cases and uses a thread pool to run several at once:
# once
pip install anthropic
import json
import os
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import anthropic
client = anthropic.Anthropic()
MODEL = os.environ.get("MODEL", "claude-opus-5-5")
VARIANT = os.environ.get("VARIANT", "A")
RUNS = 3 # run each case three times
MAX_TURNS = 6 # stop a run after six turns
SYSTEM = ("You are a support agent for a shop. Use the tools. If a tool needs "
"something the customer hasn't told you, ask for it.")
# A and B use the same tools with different descriptions.
DESCRIPTIONS = {
"A": {
"lookup_order": "Look up an order.",
"search_orders": "Search orders.",
"refund_order": "Refund an order.",
},
"B": {
"lookup_order": "Get the status and total of an order when you already have its order id "
"(like A-1042). Never guess an id.",
"search_orders": "Find a customer's orders by email when they gave no order id. Returns "
"ids and dates, not statuses; call lookup_order for those.",
"refund_order": "Refund an order in full. Only when the customer explicitly asks for a "
"refund; a complaint is not a request. Money moves and cannot be undone.",
},
}
d = DESCRIPTIONS[VARIANT]
TOOLS = [
{"name": "lookup_order", "description": d["lookup_order"],
"input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}},
{"name": "search_orders", "description": d["search_orders"],
"input_schema": {"type": "object", "properties": {"email": {"type": "string"}}, "required": ["email"]}},
{"name": "refund_order", "description": d["refund_order"],
"input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}},
]
# Pretend answers only. These functions do not change anything.
STUBS = {
"lookup_order": lambda i: {"id": i["order_id"], "status": "shipped", "total": "$42.00"},
"search_orders": lambda i: {"orders": [{"id": "A-1042", "date": "2026-09-30"}]},
"refund_order": lambda i: {"refunded": True},
}
# The trace records each tool name and input in order.
def names(calls):
return [c["name"] for c in calls]
def first_is(calls, name, **expect):
return bool(calls) and calls[0]["name"] == name and \
all(calls[0]["input"].get(k) == v for k, v in expect.items())
def before(calls, a, b):
n = names(calls)
return a in n and b in n and n.index(a) < n.index(b)
CASES = [
("status by id", "Where is order A-1042?",
lambda c: first_is(c, "lookup_order", order_id="A-1042")),
("status by email", "What's the status of my order? sam@example.com",
lambda c: first_is(c, "search_orders", email="sam@example.com")),
("complaint is not a refund", "Order A-1042 arrived broken. Unacceptable.",
lambda c: "refund_order" not in names(c)),
("explicit refund", "Please refund order A-1042, it arrived broken.",
lambda c: any(x["name"] == "refund_order" and x["input"].get("order_id") == "A-1042" for x in c)),
("search then refund", "Refund my last order. sam@example.com",
lambda c: before(c, "search_orders", "refund_order") and
any(x["name"] == "refund_order" and x["input"].get("order_id") == "A-1042" for x in c)),
("price by id", "How much did order B-2210 cost?",
lambda c: first_is(c, "lookup_order", order_id="B-2210")),
("no tool needed", "Thanks, that's all!",
lambda c: len(c) == 0),
("asks, doesn't guess", "Where is my order?",
lambda c: len(c) == 0),
("no cancel tool", "Cancel order A-1042.",
lambda c: "refund_order" not in names(c)),
("search then lookup", "Is the latest order for alex@example.com shipped?",
lambda c: before(c, "search_orders", "lookup_order")),
]
def run_once(prompt):
"""Run one prompt and return its tool calls."""
calls = []
messages = [{"role": "user", "content": prompt}]
for _ in range(MAX_TURNS):
reply = client.messages.create(
model=MODEL, max_tokens=1024, system=SYSTEM, tools=TOOLS, messages=messages,
)
messages.append({"role": "assistant", "content": reply.content})
if reply.stop_reason != "tool_use":
return calls, False
results = []
for use in (b for b in reply.content if b.type == "tool_use"):
calls.append({"name": use.name, "input": use.input})
results.append({"type": "tool_result", "tool_use_id": use.id,
"content": json.dumps(STUBS[use.name](use.input))})
messages.append({"role": "user", "content": results})
return calls, True # the run reached six turns
def run_case(case):
case_id, prompt, check = case
runs = []
for _ in range(RUNS):
try:
calls, capped = run_once(prompt)
runs.append({"pass": (not capped) and check(calls), "calls": calls})
except Exception as err:
# Show API errors separately from failed cases.
runs.append({"pass": False, "error": str(err)})
return {"id": case_id, "runs": runs}
with ThreadPoolExecutor(max_workers=len(CASES)) as pool: # cases run in parallel
results = list(pool.map(run_case, CASES))
passed = errors = 0
for r in results:
marks = "".join("!" if x.get("error") else "+" if x["pass"] else "-" for x in r["runs"])
passed += sum(x["pass"] for x in r["runs"])
errors += sum("error" in x for x in r["runs"])
print(f"{marks} {r['id']}")
total = len(CASES) * RUNS
print(f"\nvariant {VARIANT} on {MODEL}: {passed}/{total} ({round(100 * passed / total)}%)"
+ (f", {errors} API errors, rerun before you trust it" if errors else ""))
Path("evals").mkdir(exist_ok=True)
Path(f"evals/{VARIANT}.json").write_text(json.dumps(
{"MODEL": MODEL, "VARIANT": VARIANT, "results": results}, indent=2, default=str))
I left out sample scores because every model and run will be a little different. Choose either language, run A and B, and compare your own results. Those are the numbers that can help your agent.
Let the trace show you what happened
A minus sign tells you where to look. Open evals/A.json
and choose a failed run. Maybe the agent picked the wrong tool. Maybe
the agent was fine and the grader was too strict.
- If the agent chose the wrong tool or input, make the description clearer and run the eval again.
- If the behavior was fine, update the grader. In case 8, the model can ask for an email in many ways. Checking for no tool calls accepts all of them and still rejects an empty search.
- open the trace
- wrong tool or input
- clarify the description
- run it again
- open the trace
- good behavior, marked -
- update the check
- run it again
Read at least five failed runs when you make a new eval. This helps you understand the agent and check your graders. Finding a bad grader early can save a lot of time.
When a model can help with grading
Some questions are about the reply itself. Was it polite? Did the summary keep the important fact? When code cannot answer the question, a second model can check the reply against a short set of rules.
const verdict = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 200,
messages: [{ role: "user", content:
`Rubric: the reply apologizes once, offers a next step, and does not promise a refund.\n\n` +
`Reply:\n${reply}\n\n` +
`Think briefly, then end with exactly PASS or FAIL.` }],
});
const ok = verdict.content[0].text.trim().endsWith("PASS");
- agent reply
- rubric, one yes/no question
- judge call
- PASS / FAIL
- you label 20 outputs
- judge labels the same 20
- count disagreements
- 3 or fewer: good start
Test the judge on a small set first. Label the replies yourself, then see how often the model agrees:
- Label 20 replies and give the same 20 to the judge. If you disagree more than two or three times, make the rules clearer and try again.
- Ask a small yes-or-no question. “Is this good?” is too broad. “Does it promise a refund?” is clear.
- Use a separate model call for grading. You can also try a different model from the agent.
- Keep using code for facts. Case 3 only asks whether the refund tool ran, and the trace already contains that answer.
Save a few fresh cases for later
If you keep tuning the same ten cases, the agent may get good at those exact prompts without getting better elsewhere. The score rises, but new requests stay hard.
Write 15 cases. Use ten while you work, and save five for the end. If only the first ten improve, your change may fit those examples too closely. Move a useful failed case into your working set and replace it with a fresh one.
edit a descriptionrerun these tenscore climbs
leave these five alonerun them at the enddid they improve too?
Now try the whole little machine
Lesson 1 put a model in the browser. Lesson 2 gave it tools. Then you added loops, memory, and vision. You can test each choice now. Change one part, run the same cases, and compare the results.
- A model in the tab does a local model do as well on these cases?
- Tool calling which description picks the right tool more often?
- Loops and goals which runs reach the six-turn limit?
- Agent communication how does another agent do on the same cases?
- Vision does a screenshot help?
- Evals a way to compare all five
- Try a cheaper model with
MODEL=claude-haiku-4-5-20251001 VARIANT=B node eval.mjs. If its score is close to the larger model, it may be enough for this task. The marks show which cases need more help. - Compare short and long descriptions. Variant B spends more input tokens on every request. The score shows whether the extra words help.
- Run the eval after a model upgrade so you can spot new problems early.
Build the eval you'll be happy to run again
Keep the eval easy to run again. A small suite can take a few minutes
and cost a few dollars. Save the evals/*.json files beside
your code so you can see which cases changed.
- run the eval
- read the marks
- open the failing traces
- change one thing
- agent does something odd
- save the prompt
- write its grader
- case 11
evals/*.json with each change so you can
compare the cases.You can run this by hand at first. If it becomes part of your usual work, you can automate it later.
A friendly eval checklist
- Write the cases before you change the prompt.
- Use code to check tool calls and clear results.
- Use a model judge only when code cannot check the reply.
- Give each run a pass or fail.
- Include cases where the agent should wait or ask a question.
- Run each case at least 3 times. You can estimate the error bar with √(p × (1 − p) ÷ runs).
- Change one thing at a time: a description, prompt, or model.
- Show API errors separately from failed cases.
- Read a few failed traces yourself.
- Save useful failures as new cases.
- Keep a few cases aside until the end.
- Give every run a turn limit.
Your final exercise
Take this one step at a time. Use either language. A few failed cases are welcome; they give you something useful to improve.
- Copy the JavaScript or Python example. Run
VARIANT=A, thenVARIANT=B. Write down both totals and look at each case. - Run A once more. The difference between the two A scores shows how much the result can move on its own.
- Open a failed trace from A. Change one description and run the eval again. Check the other nine cases too.
- Add case 11 from something your agent gets wrong. Help it pass without breaking the first ten.
- Try B with a smaller
MODEL. Use the results to decide whether it works well enough for this task.
Want to watch a case run? Paste it into the harness and follow its tool calls in the transcript. Use the eval file for the full score, then replay a failed case in the harness and help the agent pass it.
Reference pages
- Anthropic: define success and build evaluations: more help with test cases and grading.
- Lesson 3, loops and goals: the turn limit we reuse in this eval.
- Lesson 2, tool calling: how tool descriptions guide the model.
You made it. Really, thank you.
Six lessons ago, our agent was a blinking cursor attached to an API call. Now it can use tools, work through a loop, remember, see, and check whether a change helped. We've given the little thing quite a life.
Thank you for making it all the way here. Six lessons is a lot of time. Knowing that someone was running the code, breaking it, fixing it, and coming back made this series worth writing.
I hope you'll point this code at an agent you care about. Start with mistakes it already makes. Run the eval, change one thing, and run it again. Each result gives you a little less to guess about.
If you send your results through the feedback link, I will read them. Tell me what broke, what surprised you, and what you built. I'd love to know where you take this, and your notes will help shape what buttercup.sh covers next.
If you landed on the finale first, the syllabus will take you back to the beginning. If you've been here since lesson one, you finished the buttercup.sh agent course. Keep the code, keep the weird failures, and go make something useful and strange.