Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Evals and observabilityAI guideAdvanced#evals#agents#tool-use#trajectory
Frame · ai-engineering / evals-observability / 05-evaluating-agents-and-tool-use.mdGuide 053 / 103

Evaluating agents and tool use

An agent is a loop: the model reads context, decides on an action (often a tool call), observes the result, and repeats until it thinks it is done. That loop makes evaluation harder than for a single prompt, because there are many ways to reach the right answer, many ways to reach it badly, and some ways to look right while having done something harmful along the way. Good agent evals look at three levels: the final outcome, the path taken (the trajectory), and each individual step.

Why it matters

Agents fail in ways a single-turn eval cannot see. They pick the wrong tool, pass a malformed argument, loop on the same search five times, or get the correct answer after deleting a file they should not have touched. They are also non-deterministic: the same task might succeed on one run and fail on the next. Anthropic's "Demystifying evals for AI agents" makes this point clearly, and introduces a useful distinction between pass@k (at least one of k attempts succeeds) and pass^k (all k attempts succeed). For a coding assistant where a human picks the best attempt, pass@k is reasonable. For a customer-facing agent that must work every time, pass^k is the honest metric, and it drops fast as k grows even when per-run success looks high.

How it works

Rendering diagram…

Outcome evals check the end state. For a booking agent: is there exactly one booking with the right date in the database? For a coding agent: do the tests pass? Checking state in a sandboxed environment is far more reliable than grading the agent's final message, which can claim success it did not achieve. This is the approach behind benchmarks like tau-bench, which compares the final database state against an annotated goal state.

Trajectory evals compare the sequence of actions against a reference or judge it for reasonableness. LangChain's open-source agentevals package provides a trajectory match evaluator with modes strict (same calls, same order), unordered (same calls, any order), subset and superset, and a separate LLM-as-judge trajectory evaluator for when many paths are acceptable.

Step-level evals check individual tool calls: is the tool name valid, do arguments match the schema, are required fields present, was a destructive tool called without confirmation? These are almost always code graders and they are cheap, so run them on everything.

Efficiency is a fourth dimension worth tracking: number of steps, tokens and wall-clock time. An agent that solves the task in 4 calls is better than one that needs 19, even if both pass.

Reference architecture

Rendering diagram…

Each trial needs a fresh environment. If trials share state, one run's side effects contaminate the next and your pass rates become meaningless. Repeat each task k times to estimate reliability.

Code

Trajectory matching with agentevals, plus a hand-rolled step grader and pass^k computation. Messages use the OpenAI chat format with tool_calls, which is what agentevals expects.

import json
from agentevals.trajectory.match import create_trajectory_match_evaluator

reference = [
    {"role": "user", "content": "Refund order 1234"},
    {"role": "assistant", "content": "", "tool_calls": [
        {"function": {"name": "get_order", "arguments": json.dumps({"order_id": "1234"})}}
    ]},
    {"role": "tool", "content": '{"status": "delivered", "total": 40}'},
    {"role": "assistant", "content": "", "tool_calls": [
        {"function": {"name": "issue_refund", "arguments": json.dumps({"order_id": "1234"})}}
    ]},
    {"role": "tool", "content": '{"ok": true}'},
    {"role": "assistant", "content": "Refund issued for order 1234."},
]

match = create_trajectory_match_evaluator(trajectory_match_mode="superset")

FORBIDDEN = {"delete_customer"}

def step_violations(trajectory: list[dict]) -> list[str]:
    problems = []
    for msg in trajectory:
        for call in msg.get("tool_calls", []) or []:
            name = call["function"]["name"]
            if name in FORBIDDEN:
                problems.append(f"forbidden tool: {name}")
            try:
                json.loads(call["function"]["arguments"])
            except json.JSONDecodeError:
                problems.append(f"bad JSON args for {name}")
    return problems

def pass_hat_k(successes: list[bool]) -> bool:
    return all(successes)  # all k trials passed

def grade_task(trials: list[list[dict]]) -> dict:
    per_trial = []
    for traj in trials:
        result = match(outputs=traj, reference_outputs=reference)
        per_trial.append(bool(result["score"]) and not step_violations(traj))
    return {
        "pass_at_k": any(per_trial),
        "pass_hat_k": pass_hat_k(per_trial),
        "per_trial_rate": sum(per_trial) / len(per_trial),
    }

superset mode lets the agent make extra calls (like an additional lookup) as long as the reference calls all appear. Use strict when order and count genuinely matter, such as payment flows.

Trade-offs and pitfalls

  • Grading the transcript instead of the world. The agent saying "done" is not evidence. Check the actual state wherever you can.
  • Over-strict trajectories. Requiring an exact path penalises valid alternative solutions and makes the suite fragile when you add tools. Prefer outcome checks plus a few hard constraints.
  • Shared or leaky environments. Reusing a database across trials, or letting the agent see answers in files, inflates scores. Reset per trial.
  • Ignoring variance. One run per task hides flakiness. Run several trials and report both pass@k and pass^k, or at least per-trial success rate with a confidence interval.
  • Live third-party tools. Calling real APIs in evals is slow, costly and non-reproducible. Mock or record responses, and keep a smaller live suite for integration checks.
  • Unbounded loops. Always set a step and token limit in eval runs, and count hitting the limit as a failure.
  • Judge on long trajectories. LLM judges get less reliable as transcripts grow. Summarise or judge per segment.

Checklist

  • Each task has a deterministic outcome check against environment state.
  • Every tool call is validated for name, schema and forbidden actions.
  • Trajectory checks use the loosest match mode that still encodes real requirements.
  • Environments are reset before every trial.
  • Each task runs multiple trials and you report pass@k and pass^k.
  • Step count, tokens and latency per task are tracked alongside pass rates.
  • Third-party tools are mocked or sandboxed for the main suite.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.