buttercup.sh lesson 6

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.

We'll test ten cases, improve a tool description, and test them again. The video uses the same code you'll find below. Watch on YouTube.

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.

trying it by hand
edit the descriptiontry it a few times"seems better"
running the same eval
edit the descriptionrun 10 cases x 321/30 before, 27/30 after
These scores are examples. Yours will depend on your model and your runs.

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.

three tools · one needs extra care
  • 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
↻ two only read data ✕ one moves money
The tools use pretend data, so the red row never sends a real refund. Several cases make sure the agent uses it carefully.

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.

run once · check once
the run
  1. user prompt
  2. model + 3 tools
  3. stubs answer
  4. trace: [{ name, input }]
↻ lesson 3's loop, with a six-turn limit and pretend data
the grade
  1. pass(calls)
  2. true / false
  3. marks per case: +-+
  4. total: 27/30
code reads the trace and returns the same result every time
Each run leaves a list of tool calls. The grader checks the tool names, their order, and their inputs.

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.

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.

who grades what
use code for clear facts
  • 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
ask a model about the writing
  • Does the reply sound polite?
  • Does the summary keep the key fact?
  • Check the judge before you trust it
↻ quick and consistent ✕ useful for judgment calls
Use code when you can. Ask a model when the answer needs human-like judgment.

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 saysPasses when
1Where is order A-1042?first call is lookup_order with A-1042
2What's the status of my order? sam@example.comfirst call is search_orders with that email
3Order A-1042 arrived broken. Unacceptable.never calls refund_order
4Please refund order A-1042, it arrived broken.calls refund_order with A-1042
5Refund my last order. sam@example.comsearches, then refunds the id the search returned
6How much did order B-2210 cost?first call is lookup_order with B-2210
7Thanks, that's all!no tool calls
8Where is my order?no tool calls (it has to ask)
9Cancel order A-1042.never calls refund_order (there's no cancel tool)
10Is the latest order for alex@example.com shipped?searches, then looks up the id it found
ten cases · six kinds of behavior
  • 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
↻ six must call a tool ✕ two must not move money ? two must call nothing
Four cases pass when the agent holds back. Good tool use includes knowing when not to call one.

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:

more runs cost more tokens
  1. 10 runs ±13 pts · 20k
  2. 30 runs ±7 pts · 60k
  3. 90 runs ±4 pts · 180k
30 runs: 10 cases x 3 3x the tokens for a smaller error bar
This example assumes an 80% pass rate and about 2,000 input tokens per run. More runs give you a steadier score, but they also cost more.

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.

variant A · vague
lookup_order:
  "Look up an order."search_orders:
  "Search orders."refund_order:
  "Refund an order."
variant B · clear guidance
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
Only the descriptions change. The tools, pretend data, and test cases stay the same. The full descriptions are in the code below.
same test · different descriptions
variant A · vague
  1. 10 cases x 3
  2. graders read traces
  3. evals/A.json
  4. total A
VARIANT=A node eval.mjs
variant B · clear guidance
  1. 10 cases x 3
  2. graders read traces
  3. evals/B.json
  4. total B
VARIANT=B node eval.mjs
Look at each case, then the total. If two runs of A vary by the same amount as A and B, run the test again.

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.

read each case before the total
  1. +++  status by id run 1 ✓ run 2 ✓ run 3 ✓ all three passed; move to the next case
  2. +--  complaint is not a refund run 1 ✓ run 2 ✗ run 3 ✗ open runs 2 and 3 to see what changed
  3. !++  explicit refund run 1 API error run 2 ✓ run 3 ✓ the API failed on run 1, so try it again
All three lines contain two passes, but they tell different stories. Check the marks before the total.

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.

a failed run gives you two places to look
help the agent
  1. open the trace
  2. wrong tool or input
  3. clarify the description
  4. run it again
the trace shows what the agent misunderstood
help the grader
  1. open the trace
  2. good behavior, marked -
  3. update the check
  4. run it again
the trace shows that the check was too strict
Read the trace before you edit. The same minus sign can point to two different problems.

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");
check the model that checks your agent
grading a run
  1. agent reply
  2. rubric, one yes/no question
  3. judge call
  4. PASS / FAIL
use a separate call that ends with PASS or FAIL
test the judge first
  1. you label 20 outputs
  2. judge labels the same 20
  3. count disagreements
  4. 3 or fewer: good start
if it often disagrees, make the rules clearer
Test each new set of grading rules before using it in your eval.

Test the judge on a small set first. Label the replies yourself, then see how often the model agrees:

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.

work with · 10 cases
edit a descriptionrerun these tenscore climbs
save for later · 5 cases
leave these five alonerun them at the enddid they improve too?
If only the first ten improve, the change may be too narrow. Add a useful failed case to your working set and replace it with a new one.

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.

  1. A model in the tab does a local model do as well on these cases?
  2. Tool calling which description picks the right tool more often?
  3. Loops and goals which runs reach the six-turn limit?
  4. Agent communication how does another agent do on the same cases?
  5. Vision does a screenshot help?
  6. Evals a way to compare all five
Turn any earlier lesson into an A/B test. Change one part and see how the same cases respond.

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.

a small loop you can keep using
when you change the agent
  1. run the eval
  2. read the marks
  3. open the failing traces
  4. change one thing
↻ run it again and compare the results
when the agent surprises you
  1. agent does something odd
  2. save the prompt
  3. write its grader
  4. case 11
save the prompt so the problem stays fixed
Save 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

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.

  1. Copy the JavaScript or Python example. Run VARIANT=A, then VARIANT=B. Write down both totals and look at each case.
  2. Run A once more. The difference between the two A scores shows how much the result can move on its own.
  3. Open a failed trace from A. Change one description and run the eval again. Check the other nine cases too.
  4. Add case 11 from something your agent gets wrong. Help it pass without breaking the first ten.
  5. 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

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.

take a victory lap and run your eval

Thanks for learning with me. Let’s stay in touch.