Skip to main content

Evaluating AI Agents: A Practical Testing Setup Beyond Vibe Checks

Learn how to evaluate AI agents with a simple Python test harness: trace grading, repeated runs, and a CI gate.

Updated 11 min readMarkdown
Evaluating AI Agents: A Practical Testing Setup Beyond Vibe Checks

You ship an agent. You try five prompts, the answers look good, and you merge it. Two weeks later it calls the wrong tool for a customer, loops on a simple task, or quietly gets worse after a prompt tweak. Nobody noticed because nobody measured anything.

That's the vibe check: eyeballing a few outputs and deciding the agent "feels fine." It breaks down for agents for three reasons:

  • They're non-deterministic. The same input can succeed once and fail the next time.
  • They take multi-step paths. The final answer can look right while the path was wrong (an unsafe tool call, wasted steps, a lucky guess).
  • They change constantly. Every prompt edit, tool change, or model upgrade can cause a regression.

This article shows a practical approach to AI agent evaluation: a small, framework-free Python eval harness you can run locally and in CI. It covers how to evaluate AI agents on their behavior and not only their final text.

Prerequisites: Python 3.10+, basic familiarity with LLM agents and tool calling, and an agent you can call as a function. No evaluation library is required.

Table of Contents

  1. Why testing AI agents is different
  2. The anatomy of an AI agent evaluation framework
  3. Step 1: Capture a trace
  4. Step 2: Write test cases
  5. Step 3: Add graders
  6. Step 4: Run repeatedly and measure reliability
  7. Step 5: Gate your CI
  8. Where LLM-as-judge fits
  9. Benchmarks vs. your own evals
  10. From testing to observability
  11. Summary and key takeaways

Why testing AI agents is different

Traditional unit tests assert that f(x) == y. With agents, three things get in the way:

  • Output variance. Wording changes between runs, so exact-match assertions fail for the wrong reasons.
  • Process matters. An agent that refunds an order without first checking its status has failed, even if its final message is polite.
  • One run proves little. A 100% pass on a single run says nothing about reliability.

So automated AI agent testing needs to do three things: grade the trace (the steps taken) as well as the answer, run each case multiple times, and report rates instead of single results.

The anatomy of an AI agent evaluation framework

The harness has four parts:

flowchart LR
    A[Test cases] --> B[Agent under test]
    B --> C[Trace: tool calls, steps, answer]
    C --> D[Graders]
    D --> E[Metrics: pass rate, reliability, cost]
    E --> F[CI gate + JSONL logs]
  • Cases describe what to ask and what "good" looks like.
  • The adapter wraps your agent and returns a structured trace.
  • Graders are small functions that check one property each.
  • The runner repeats cases, aggregates metrics, and fails the build when quality drops.

Step 1: Capture a trace

Start by defining what a single agent run produces. Everything downstream depends on this structure.

# evals/types.py
from dataclasses import dataclass, field

@dataclass
class ToolCall:
    name: str
    args: dict

@dataclass
class Trace:
    final_answer: str
    tool_calls: list[ToolCall] = field(default_factory=list)
    steps: int = 0
    latency_s: float = 0.0
    tokens: int = 0
    error: str | None = None

@dataclass
class Case:
    id: str
    prompt: str
    must_call: list[str] = field(default_factory=list)      # tools that must be used
    must_not_call: list[str] = field(default_factory=list)  # tools that must never be used
    must_contain: list[str] = field(default_factory=list)   # facts the answer must include
    max_steps: int = 8
    tags: list[str] = field(default_factory=list)

@dataclass
class GradeResult:
    name: str
    passed: bool
    detail: str = ""

The Trace captures not just the answer but the tool calls, step count, latency, and token use. That's what lets you test behavior, cost, and speed with one harness.

Next, wrap your agent in a single function. This is the only part you rewrite for your own stack.

# evals/adapter.py
import time
from evals.types import Trace, ToolCall

def run_agent(prompt: str) -> Trace:
    start = time.perf_counter()
    try:
        # Replace this block with a call to your real agent.
        # It should return the final answer plus the tool calls it made.
        result = my_agent.invoke(prompt)  # <- your agent here

        return Trace(
            final_answer=result["output"],
            tool_calls=[ToolCall(c["name"], c["args"]) for c in result["tool_calls"]],
            steps=result["steps"],
            latency_s=time.perf_counter() - start,
            tokens=result.get("tokens", 0),
        )
    except Exception as exc:  # a crash is a test result, not a harness failure
        return Trace(final_answer="", latency_s=time.perf_counter() - start, error=str(exc))

Catching exceptions matters here. A crashing agent should show up as a failed case, not a broken test run.

Step 2: Write test cases

Start small: 15–30 cases drawn from real usage beat 500 invented ones. Mix three kinds:

  • Happy paths that must work.
  • Edge cases such as ambiguous requests, missing data, and tool errors.
  • Guardrail cases where the right behavior is to refuse or avoid a tool.
# evals/cases.py
from evals.types import Case

CASES = [
    Case(
        id="order-status-basic",
        prompt="Where is order #1042?",
        must_call=["get_order_status"],
        must_contain=["1042"],
        tags=["happy-path"],
    ),
    Case(
        id="refund-requires-lookup",
        prompt="Refund order #1042, it arrived broken.",
        must_call=["get_order_status", "issue_refund"],
        max_steps=6,
        tags=["happy-path", "high-risk"],
    ),
    Case(
        id="no-refund-without-order-id",
        prompt="I want my money back.",
        must_not_call=["issue_refund"],  # it should ask for the order ID instead
        tags=["guardrail"],
    ),
]

The third case is the one vibe checks usually miss. It tests that the agent does not take a risky action when it lacks information.

Step 3: Add graders

Each grader checks one property and returns a pass or fail with a reason. Prefer deterministic checks wherever you can, because they're fast, free, and repeatable.

# evals/graders.py
from evals.types import Case, Trace, GradeResult

def grade_no_crash(case: Case, trace: Trace) -> GradeResult:
    return GradeResult("no_crash", trace.error is None, trace.error or "")

def grade_tool_use(case: Case, trace: Trace) -> GradeResult:
    called = {c.name for c in trace.tool_calls}
    missing = [t for t in case.must_call if t not in called]
    forbidden = [t for t in case.must_not_call if t in called]
    ok = not missing and not forbidden
    return GradeResult("tool_use", ok, f"missing={missing} forbidden={forbidden}")

def grade_step_budget(case: Case, trace: Trace) -> GradeResult:
    return GradeResult(
        "step_budget",
        trace.steps <= case.max_steps,
        f"{trace.steps}/{case.max_steps} steps",
    )

def grade_contains(case: Case, trace: Trace) -> GradeResult:
    answer = trace.final_answer.lower()
    missing = [s for s in case.must_contain if s.lower() not in answer]
    return GradeResult("contains", not missing, f"missing={missing}")

GRADERS = [grade_no_crash, grade_tool_use, grade_step_budget, grade_contains]

The step budget grader is a cheap way to catch infinite loops and wasteful reasoning, a common failure in agent systems.

Step 4: Run repeatedly and measure reliability

Because agents are non-deterministic, run each case N times. This turns a pass or fail into a rate, which is the basis of AI agent reliability testing.

# evals/runner.py
import json, statistics
from dataclasses import asdict
from evals.adapter import run_agent
from evals.cases import CASES
from evals.graders import GRADERS

N_RUNS = 5

def run_case(case):
    runs = []
    for i in range(N_RUNS):
        trace = run_agent(case.prompt)
        results = [grader(case, trace) for grader in GRADERS]
        runs.append({
            "run": i,
            "passed": all(r.passed for r in results),
            "results": results,
            "trace": trace,
        })
    return runs

def summarize(all_runs):
    per_case = {}
    for case_id, runs in all_runs.items():
        passes = [r["passed"] for r in runs]
        per_case[case_id] = {
            "pass_rate": sum(passes) / len(passes),
            "always_passes": all(passes),  # strict reliability
        }

    traces = [r["trace"] for runs in all_runs.values() for r in runs]
    return {
        "avg_pass_rate": statistics.mean(c["pass_rate"] for c in per_case.values()),
        "reliable_cases": sum(c["always_passes"] for c in per_case.values()) / len(per_case),
        "median_latency_s": statistics.median(t.latency_s for t in traces),
        "avg_steps": statistics.mean(t.steps for t in traces),
        "avg_tokens": statistics.mean(t.tokens for t in traces),
        "per_case": per_case,
    }

def log_runs(all_runs, path="eval_runs.jsonl"):
    with open(path, "w") as f:
        for case_id, runs in all_runs.items():
            for r in runs:
                f.write(json.dumps({
                    "case": case_id,
                    "run": r["run"],
                    "passed": r["passed"],
                    "failures": [asdict(x) for x in r["results"] if not x.passed],
                    "trace": asdict(r["trace"]),
                }) + "\n")

Two metrics are worth tracking separately:

  • Average pass rate tells you how often the agent succeeds on a typical run.
  • Reliable cases (passed on every run) tells you how often a user can count on it. An agent with a 90% pass rate per attempt can still be unreliable across a multi-step workflow, because failures compound.

The JSONL log gives you a replayable record of every failure with its full trace, so you can debug instead of guessing.

Step 5: Gate your CI

Evals only protect you if a regression can block a merge.

# evals/main.py
import sys
from evals.cases import CASES
from evals.runner import run_case, summarize, log_runs

MIN_PASS_RATE = 0.90
MIN_RELIABLE = 0.75

if __name__ == "__main__":
    all_runs = {case.id: run_case(case) for case in CASES}
    log_runs(all_runs)
    report = summarize(all_runs)

    print(f"avg pass rate : {report['avg_pass_rate']:.0%}")
    print(f"reliable cases: {report['reliable_cases']:.0%}")
    print(f"median latency: {report['median_latency_s']:.2f}s")
    print(f"avg steps     : {report['avg_steps']:.1f}")
    for cid, c in report["per_case"].items():
        flag = "OK " if c["always_passes"] else "FAIL"
        print(f"  [{flag}] {cid}: {c['pass_rate']:.0%}")

    if report["avg_pass_rate"] < MIN_PASS_RATE or report["reliable_cases"] < MIN_RELIABLE:
        sys.exit(1)  # fail the build

Run it with python -m evals.main on every pull request that touches prompts, tools, or model settings. Treat the thresholds as a starting point, then ratchet them up as the agent improves.

Where LLM-as-judge fits

Some qualities can't be checked with string matching: tone, helpfulness, whether an explanation is faithful to the retrieved data. For those, add an LLM judge as an additional grader, not a replacement for the deterministic ones.

# evals/judge.py
import json
from evals.types import Case, Trace, GradeResult

RUBRIC = """You are grading an AI agent's reply.
Score 1 if the reply is accurate, stays within the user's request, and
does not invent facts. Otherwise score 0.
Return JSON only: {"score": 0 or 1, "reason": "<one sentence>"}"""

def grade_with_judge(case: Case, trace: Trace) -> GradeResult:
    raw = call_llm(  # your LLM client of choice
        system=RUBRIC,
        user=f"User request:\n{case.prompt}\n\nAgent reply:\n{trace.final_answer}",
    )
    verdict = json.loads(raw)
    return GradeResult("judge", verdict["score"] == 1, verdict["reason"])

Keep these habits:

  • Use a binary rubric with explicit criteria. Vague 1–10 scores drift.
  • Spot-check the judge against a handful of human-labeled examples.
  • Run deterministic graders first, and only call the judge when they pass, to save cost.

Benchmarks vs. your own evals

Public AI agent benchmarks such as SWE-bench (software engineering tasks), τ-bench (tool-using customer-service style tasks), and GAIA (general assistant tasks) are useful for comparing models and getting a rough capability signal. But they don't know your tools, your users, or your failure modes.

Use benchmarks to choose a model, and use your own harness to decide whether your agent is safe to ship. This is also where an LLM evaluation framework or LLM testing framework from the ecosystem can help once your needs outgrow a hand-rolled harness. Starting with the simple version above means you'll know exactly what you need from one.

From testing to observability

Pre-release tests can't cover everything real users will do. The next step is AI agent observability: log traces in production, then feed the failures back into your test suite.

A simple loop works well:

  1. Log every production trace (tool calls, steps, outcome).
  2. Flag failures: errors, loops, thumbs-down, escalations.
  3. Turn each flagged trace into a new test case.
  4. Re-run the suite before the next release.

Over time the suite becomes a record of every way your agent has failed, which is a much stronger safety net than any hand-written list. For the failure modes worth watching for, see Why Multi-Agent Systems Fail: 6 Failure Modes and How to Catch Them (link to your published post).

Summary and key takeaways

  • Grade the trace, not just the answer. Tool calls, step counts, and guardrails reveal problems that polished final text hides.
  • Run each case multiple times. Pass rate and "always passes" reliability tell you far more than one lucky run.
  • Start deterministic, add an LLM judge selectively. Cheap checks catch most regressions, and judges cover the subjective rest.
  • Wire it into CI and close the loop with production traces.

Limitations to keep in mind: a small case set can give false confidence, LLM judges have their own biases, repeated runs add cost, and the thresholds above are placeholders you should tune to your own risk tolerance. Possible next steps include adding cost budgets per case, tracking metrics over time in a dashboard, and building a regression set from real user failures.

About the author

  • We write about multi-agent systems, agentic AI, and omnichannel automation, the architecture decisions behind them, where they break in production, and what actually changes for teams running support, sales, and ops through them. We built BotSailor, where we help businesses run WhatsApp, Instagram, Telegram, and Messenger automation from one place so most of what we write comes from things we've actually shipped, broken, and fixed, not just trend-watching. Currently publishing two series here: Multi-Agent Systems, Practically and Agentic AI in Production. If you're building with agents, orchestration, or omnichannel automation, we'd genuinely like to hear what you're running into, drop it in the comments or reply to any post.

The refund-requires-lookup case is the strongest part for me: grading the trace for a must_call tool catches an agent that sounds polite but skipped the status check. The same idea applies to multi-step plans. In a travel planner we traced, the agent replanned, a flight hold went through, then the hotel hold failed on a price mismatch and the final answer said "Infeasible", leaving half the trip held. A final-text grader would never see that, but a trace check for partial batches and effects after a failed step does.

pip install agentest-ai

Try it on one of your own agent runs and tell us what it caught or missed. It judges recorded traces offline, no API key needed, with 165 tests.