Blog / AI agentsDebugging AI agents, part 4

Your agent worked yesterday. Regression evals from real traces

A prompt tweak in one place breaks behaviour somewhere else. Turn bad traces into eval cases, run them against fake tools, grade with code first, and compare every change with a baseline.

Debugging AI agents, part 4: Your agent worked yesterday. Prove it today.

In Part 1 we logged every turn of the agent loop and saved failed conversations so we could replay them. In Part 2 we fixed tool design and added a tiny tool-choice eval. In Part 3 we gave every run limits and a clean finish.

Now the agent works. Then someone tightens the system prompt to stop it rambling, and a week later a customer gets a refund they shouldn't have. Nobody connects the two, because the prompt change was "only wording" and the refund flow wasn't touched.

This is the most common way a working agent gets worse: a change in one place moves behaviour somewhere else. Prompts, tool descriptions, models and effort settings all interact, and you can't reason your way to the side effects. You have to measure them.

This part turns the traces from Part 1 into a regression suite: a set of real cases you run before every change, graded mostly by plain code, with a model as judge only where code can't decide. By the end you'll be able to change a prompt and know in ten minutes what you broke.

Diagram of a regression eval flow: bad traces become cases, cases run against fake tools, get graded and compared with a baseline
Real failures become cases. Cases run against fakes, get graded, and are compared with the last known good run.

What a case looks like

Part 2's eval checked one thing: which tool the model calls first. That's useful, but most real bugs happen later in a run. The refund that shouldn't have happened came three turns in, after the agent had looked up the order and read the policy.

So a case needs to describe a whole run:

type EvalCase = {
  id: string;
  tags: string[];                       // 'refunds', 'from-trace', 'must-pass'
  input: string | Anthropic.MessageParam[]; // a message, or a saved conversation prefix
  fixtures: Fixtures;                   // what the fake tools return
  checks: Check[];                      // what must be true at the end
  runs?: number;                        // default 3
};

input can be a single message or the start of a saved conversation from Part 1, so you can reproduce a bug that only shows up on turn four. fixtures is the world the agent sees: which orders exist, what state they're in. checks are the things that decide pass or fail.

Here's a real one, written from the refund bug above:

const refundOutsideWindow: EvalCase = {
  id: "refund-outside-30-days",
  tags: ["refunds", "from-trace", "must-pass"],
  input: "Order 51007 arrived broken. I want my money back.",
  fixtures: {
    orders: {
      "51007": { status: "delivered", deliveredAt: daysAgo(45), total: 89.0, customer: "jane@example.com" },
    },
  },
  checks: [
    calledTool("get_order", { order_id: "51007" }),
    neverCalled("refund_order"),
    finishedWith("escalated"),
    judge("Tells the customer a person will review it, without promising a refund."),
  ],
};

Three of those four checks are plain code. Only the last one needs a model. That ratio is deliberate.

Make the tools fake

You can't run evals against your real order system. Refunds would be real, emails would be sent, and the data would change under you between runs. The agent needs to call tools that look exactly the same as production but read from fixtures and record what was asked of them.

That means the agent loop has to accept its tool handlers instead of importing them. If your runAgent from Part 1 calls handlers[name](input) from a module-level map, pass the map in:

export async function runAgent(
  input: string | Anthropic.MessageParam[],
  opts: { handlers: Handlers; maxTurns?: number },
): Promise<RunResult> {
  // ...the loop from Parts 1 and 3, using opts.handlers instead of the imported map
}

type RunResult = {
  runId: string;                 // the trace ID from Part 1
  messages: Anthropic.MessageParam[];
  finish?: { outcome: string; summary: string }; // from the finish tool in Part 3
  finalText: string;             // the last thing the agent said to the customer
  turns: number;
};

Then build fakes from the fixtures:

type ToolCall = { name: string; input: Record<string, unknown> };

function fakeHandlers(fixtures: Fixtures) {
  const calls: ToolCall[] = [];
  const record = <T>(name: string, input: Record<string, unknown>, result: T) => {
    calls.push({ name, input });
    return result;
  };

  const handlers: Handlers = {
    get_order: async ({ order_id }) =>
      record("get_order", { order_id }, fixtures.orders[order_id] ?? { error: `No order ${order_id}` }),
    refund_order: async (input) =>
      record("refund_order", input, { refunded: true, refund_id: "rf_test_1" }),
    finish: async (input) => record("finish", input, { ok: true }),
  };

  return { handlers, calls };
}

The tool definitions stay exactly the ones you ship. Only the implementations are fake. If you eval with different descriptions from production, you're testing a different agent.

Keep fakes dumb. A fake that tries to reproduce your business rules will drift from the real ones and start hiding bugs. Return fixture data, record the call, and let the checks decide whether the call should have happened.

Grade with code first

Most of what matters about an agent run can be checked without a model: what it called, with what, in what order, and how it finished. Code checks are free, instant and never disagree with themselves. Write those first.

type Check = {
  name: string;
  run: (r: RunResult & { calls: ToolCall[] }) => Promise<boolean> | boolean;
};

const calledTool = (name: string, input?: Record<string, unknown>): Check => ({
  name: `called ${name}`,
  run: ({ calls }) =>
    calls.some((c) => c.name === name && (!input || matches(c.input, input))),
});

const neverCalled = (name: string): Check => ({
  name: `never called ${name}`,
  run: ({ calls }) => !calls.some((c) => c.name === name),
});

const calledBefore = (first: string, then: string): Check => ({
  name: `${first} before ${then}`,
  run: ({ calls }) => {
    const a = calls.findIndex((c) => c.name === first);
    const b = calls.findIndex((c) => c.name === then);
    return b === -1 || (a !== -1 && a < b);
  },
});

const finishedWith = (outcome: string): Check => ({
  name: `finished ${outcome}`,
  run: ({ finish }) => finish?.outcome === outcome,
});

const withinTurns = (max: number): Check => ({
  name: `within ${max} turns`,
  run: ({ turns }) => turns <= max,
});

// Only the keys you name have to match, so extra fields don't break the check.
const matches = (actual: Record<string, unknown>, expected: Record<string, unknown>) =>
  Object.entries(expected).every(([k, v]) => JSON.stringify(actual[k]) === JSON.stringify(v));

Notice what's missing: no check compares the agent's reply to an expected string. Models phrase things differently every run. A test that wants exact text fails for no reason and soon gets ignored. Check behaviour, and check text only for the specific thing you care about.

withinTurns is cheap insurance against the loops from Part 3. A change that makes the agent take twelve turns to do what used to take four is a regression even if the answer is still right.

Use a judge only for what code can't see

Some things really are about the words. Did the reply promise a refund? Did it ask for the order number when it already had one? Was it rude? For those, ask a model, but ask it a narrow question with a yes or no answer.

import { z } from "zod";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";

const Verdict = z.object({
  reasoning: z.string(),
  pass: z.boolean(),
});

const judge = (criterion: string): Check => ({
  name: `judge: ${criterion}`,
  run: async ({ finalText }) => {
    const response = await client.messages.parse({
      model: "claude-opus-5-5",
      max_tokens: 4000,
      output_config: { effort: "low", format: zodOutputFormat(Verdict) },
      system:
        "You grade one reply from a customer support agent against one criterion. " +
        "Judge only that criterion. Explain briefly, then answer pass true or false.",
      messages: [
        {
          role: "user",
          content: `<criterion>${criterion}</criterion>\n<reply>${finalText}</reply>`,
        },
      ],
    });
    return response.parsed_output?.pass ?? false;
  },
});

A few rules make judges trustworthy:

  • One criterion per judge. "Is this a good reply?" gets you a shrug. "Does it promise a refund?" gets you an answer. If you care about three things, write three judges.
  • Write criteria a person would agree on. If two people on your team would argue about whether a reply passes, the judge will be inconsistent too. Make it more specific.
  • Reasoning first, verdict second. Asking for a short explanation before pass makes the verdict more consistent, and the reasoning is what you read when a judge fails something unexpectedly.
  • Treat a missing verdict as a fail. If parsing fails, parsed_output is null. Count that as a failure you investigate, not a pass.
  • Check the judge against yourself. Before you trust a new judge, grade ten replies by hand, run the judge on the same ten and compare. If it disagrees with you on more than one or two, rewrite the criterion. Do this again whenever you change the judge's model.

Run each case more than once

The same input can produce different runs. Usually they're all fine. Sometimes one in five goes a different way, and that one is exactly the bug you'll hear about from a customer. So every case runs several times, and you look at the pass rate, not a single pass or fail.

type CaseResult = { id: string; tags: string[]; passed: number; runs: number; failures: string[] };

async function runCase(c: EvalCase): Promise<CaseResult> {
  const runs = c.runs ?? 3;
  let passed = 0;
  const failures: string[] = [];

  for (let i = 0; i < runs; i++) {
    const { handlers, calls } = fakeHandlers(c.fixtures);
    const result = await runAgent(c.input, { handlers });
    const failed: string[] = [];
    for (const check of c.checks) {
      if (!(await check.run({ ...result, calls }))) failed.push(check.name);
    }
    if (failed.length === 0) passed++;
    else failures.push(`run ${i + 1}: ${failed.join(", ")} (trace ${result.runId})`);
  }

  return { id: c.id, tags: c.tags, passed, runs, failures };
}

Every failure carries the run's trace ID. When a case fails, you open the trace from Part 1 and read exactly what happened, the same way you would for a production bug.

Run the cases in parallel with a small limit so a big suite doesn't hit rate limits:

async function runAll(cases: EvalCase[], concurrency = 4) {
  const results: CaseResult[] = [];
  const queue = [...cases];
  await Promise.all(
    Array.from({ length: concurrency }, async () => {
      for (let c = queue.shift(); c; c = queue.shift()) results.push(await runCase(c));
    }),
  );
  return results;
}

Compare with the last good run

A score on its own tells you little. 87% is great if yesterday was 80% and bad if yesterday was 95%. What you want after a change is a list: which cases got worse, which got better.

Save the results of a run you're happy with as a baseline, and compare every new run against it:

import { readFileSync, writeFileSync, existsSync } from "node:fs";

const BASELINE = "evals/baseline.json";

function compare(results: CaseResult[]) {
  const base: Record<string, number> = existsSync(BASELINE)
    ? JSON.parse(readFileSync(BASELINE, "utf8"))
    : {};

  const worse = results.filter((r) => base[r.id] !== undefined && r.passed / r.runs < base[r.id]);
  const better = results.filter((r) => base[r.id] !== undefined && r.passed / r.runs > base[r.id]);
  const brokenMustPass = results.filter((r) => r.tags.includes("must-pass") && r.passed < r.runs);

  for (const r of worse) console.log(`▼ ${r.id}: ${r.passed}/${r.runs} (was ${Math.round(base[r.id] * r.runs)}/${r.runs})\n  ${r.failures.join("\n  ")}`);
  for (const r of better) console.log(`▲ ${r.id}: ${r.passed}/${r.runs}`);
  for (const r of brokenMustPass) console.log(`✗ MUST PASS ${r.id}: ${r.failures.join("; ")}`);

  return { worse, better, brokenMustPass };
}

export function saveBaseline(results: CaseResult[]) {
  writeFileSync(BASELINE, JSON.stringify(Object.fromEntries(results.map((r) => [r.id, r.passed / r.runs])), null, 2));
}

Two kinds of case need two different rules:

  • Must-pass cases are the ones where a single failure means real harm: refunds, deleting things, anything sent to a customer that can't be taken back. These must pass every run. One failure out of three blocks the change.
  • Everything else is judged by direction. A case dropping from 3/3 to 2/3 is worth a look. A case dropping from 3/3 to 0/3 is a regression. Small wobbles between runs are normal, so don't panic over a single case moving by one run.

Only update the baseline on purpose, after you've looked at a run and decided it's the new normal. A baseline that updates itself every run catches nothing.

Where cases come from

The suite is only as good as its cases, and the best cases are things that already went wrong.

  • Every bad trace becomes a case. When Part 1's logging shows a run that went wrong, save the conversation, write the fixtures it needed and add checks for what should have happened. Tag it from-trace.
  • Every complaint becomes a case. If a customer had to tell you, it's a must-pass case.
  • Add the boring path too. Five or six ordinary requests that should just work. Regressions often break the easy stuff first, because nobody looks at it.
  • Add the boundaries. The order on day 29 and day 31 of a 30-day window. The customer with two orders. The question that needs no tool at all.

Twenty to fifty cases is plenty to start. Past that, each new case should earn its place by catching something the others don't.

Run it before every change

The suite is useless if you only remember to run it after something breaks. Make it part of the change itself:

{
  "scripts": {
    "eval": "tsx evals/run.ts",
    "eval:quick": "tsx evals/run.ts --tag must-pass",
    "eval:baseline": "tsx evals/run.ts --save-baseline"
  }
}
// evals/run.ts
const tag = argValue("--tag");
const cases = tag ? allCases.filter((c) => c.tags.includes(tag)) : allCases;

const results = await runAll(cases);
const { worse, brokenMustPass } = compare(results);

if (process.argv.includes("--save-baseline")) saveBaseline(results);

const passed = results.reduce((n, r) => n + r.passed, 0);
const total = results.reduce((n, r) => n + r.runs, 0);
console.log(`\n${passed}/${total} runs passed across ${results.length} cases`);

// Fail the build on any broken must-pass case, or on more than a couple of regressions.
process.exit(brokenMustPass.length > 0 || worse.length > 2 ? 1 : 0);

A workable rhythm:

  • Every prompt or tool description change: run eval:quick. Must-pass cases only, a few minutes.
  • Before you ship: run the full suite and read the regressions list. In CI, this is the step that blocks a merge.
  • Before switching model or effort setting: run the full suite with more runs per case, and compare cost per run too. Part 3's token tracking already gives you the numbers.

Evals cost money, because every run calls the model. Keep an eye on it the same way you would for production: log tokens per eval run, and if the full suite gets expensive, run it nightly and keep the quick set for every change.

Checklist

To stop a working agent from quietly getting worse:

  • Turn every bad trace and every complaint into an eval case.
  • Describe whole runs: input, fixtures, and checks on what happened.
  • Run the real tool definitions against fake implementations that read fixtures and record calls.
  • Grade behaviour with code first: which tools, with what input, in what order, how it finished, how many turns.
  • Use a judge only for wording, one narrow yes or no criterion per judge, and check the judge against your own grading.
  • Run each case several times and look at pass rates.
  • Compare against a saved baseline, and update the baseline on purpose.
  • Make must-pass cases block the change on any failure.
  • Run the quick set on every change and the full suite before you ship.

Next in this series: your agent reads text written by other people: emails, web pages, support tickets, tool results. Part 5 covers prompt injection and untrusted input, how instructions hidden in that text can steer an agent, and how to limit what a hijacked run can do.

  • ai agents
  • evals
  • testing