Skip to main content
LearnMLAcademy
Advanced10 min read

Evaluating Agents: Task Success, Safety, Trajectories & Benchmarks

Evaluate AI agent performance with trajectory benchmarks and safety metrics, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Evaluate both the outcome and the actions used to reach it

Agent evaluation checks both the final outcome and the trajectory that produced it: observations, decisions, tool choices, argument accuracy, permissions, unnecessary steps, recovery, safety, cost, and stopping behavior. A correct final answer is not a successful run if the agent reached it through unsafe or wasteful actions.

What You Will Learn

  • Evaluate both task outcome and the trajectory used to reach it.
  • Choose deterministic checks, human review, and calibrated model judges appropriately.
  • Separate headline success from safe-success.
  • Turn production incidents into representative regression cases.

Evaluate the journey as well as the destination

A final answer can be correct even when the agent chose the wrong tool, used invalid arguments, accessed an unauthorized resource, repeated needless steps, or recovered unsafely. A scenario suite should therefore define the expected outcome, allowed actions, important forbidden actions, and the trace evidence required for success.

Deterministic evaluators are strongest for clear facts such as numeric limits, schema conformance, tool sequence, and citations. Human reviewers handle nuanced high-risk judgment. Model judges can scale rubric-based review, but must be calibrated against human labels and monitored for bias or instability. Public benchmarks are signals, not replacements for application-specific cases.

What to evaluate in an agent run

What to evaluate in an agent run
DimensionEvaluator typeExample failure
Final task successDeterministic or humanCorrect format but wrong outcome
Tool selectionTrace rule / humanSearch used when authoritative lookup was required
Argument correctnessSchema and policy checksWrong order ID or amount
Policy complianceDeterministic guard plus reviewUnauthorized data access
Unnecessary stepsTrace analysisRepeated equivalent searches
RecoveryScenario assertionRetried unsafe side effect
LatencyMeasured tracep95 exceeds service objective
CostUsage calculationSuccessful answer exceeds task budget

Test the complete trajectory against explicit criteria

  1. Build versioned scenario suites from realistic tasks, failures, edge cases, and adversarial inputs, with allowed actions and explicit success conditions.

  2. Record the observable trajectory: decisions, tool calls and arguments, results, approvals, errors, latency, cost, and final output.

  3. Score task success, tool correctness, unnecessary steps, recovery behavior, and policy or safety compliance separately.

  4. Use deterministic checks where rules are clear, human review for nuanced high-risk cases, and model judges only with calibrated rubrics and caveats.

  5. Compare releases on the same scenarios, inspect critical traces, and convert production incidents into regression cases.

Instructional figure

Evaluate every important point in the trajectory

Where can an agent fail even when the final answer looks correct?

User goal
Model decision
Tool + arguments
Observation
Retry / handoff
Final output
task successpolicy + argumentsrecovery + stepslatency + cost
Evaluation attaches checks to decisions, arguments, observations, retries, handoffs, final output, safety, latency, and cost—not just the last sentence.

Worked Example: Task success can hide unsafe trajectories

A fixed offline suite contains 20 representative cases. Seventeen end with the correct task result.

  1. Task-success rate = 17 ÷ 20 = 0.85 = 85%.
  2. Trace review finds policy violations in 2 of those 17 otherwise successful runs.
  3. Runs that are both successful and free of those violations = 17 − 2 = 15.
  4. Safe-success rate = 15 ÷ 20 = 0.75 = 75%.

What the result means: Reporting only 85% would hide two unsafe paths. The 75% safe-success rate better describes deployable behavior.

Choosing an evaluator

Choosing an evaluator
EvaluatorStrengthLimitationBest use
Deterministic checkRepeatable and preciseNeeds an explicit ruleSchemas, limits, exact tool behavior
Human reviewNuanced and context-awareSlow, costly, variableHigh-risk quality and policy judgment
Model judgeScales rubric-based reviewCan be biased or unstableCalibrated semantic scoring with audits

A Realistic Example: Testing a refund agent

Cases include a valid refund, an order owned by another user, a duplicate request, a tool timeout, and a prompt injection hidden in ticket text. The agent must succeed safely in each case.

Read the Mechanism in Code

Use the label and note to understand what this block represents before reading each line.

Conceptual pseudocode
score = {
    "task_success": task_success(trace),
    "tool_accuracy": tool_and_argument_score(trace),
    "unnecessary_steps": count_redundant_actions(trace),
    "safe_recovery": recovery_score(trace),
    "policy_violations": count_policy_violations(trace),
}
assert trace.stops_within(max_steps=8)
assert trace.did_not_repeat(completed_refund)
Learner note: Conceptual evaluator code. task_success(), recovery_score(), and trace helpers are application-specific evaluator functions.

Hands-On Runnable Python Lab: Separate Raw Success from Safe Success

Six synthetic runs cost $0.02 each. Four complete the task, but one of those violates policy. Three therefore count as safe successes. The fixtures are illustrative results, not measurements of a commercial agent.

raw_success = 4/6 = 66.7%; safe_success = 3/6 = 50.0%; cost_per_safe_success = $0.12/3 = $0.04
The same six attempted tasks form both denominators. Total cost includes all attempts, including failures and the unsafe success.
  1. Represent each run with separate task_ok and policy_ok flags.
  2. Count raw successes without conflating them with compliance.
  3. Count the intersection of success and compliance.
  4. Divide total attempt cost by safe successes and apply a zero-policy-violation release gate.

An unsafe success must not count as a safe success

Six runs: task success for 1,2,4,6; policy passes for every run except 2. Safe successes are 1,4,6, so 3 of 6.RunTaskPolicyBoth1✓✓✓2✓××3×✓×4✓✓✓5×✓×6✓✓✓Raw 4/6 = 66.7% · Safe 3/6 = 50%Run 2 blocks the zero-violation gateAll-attempt cost / safe successes = $0.04
A check means pass; a cross means fail. Only runs passing both columns count toward safe success. All six attempted runs contribute to cost.

A check means pass; a cross means fail. Only runs passing both columns count toward safe success. All six attempted runs contribute to cost.

Complete Python ExercisepythonRunnable
runs = [
    {"id": 1, "task_ok": True,  "policy_ok": True,  "cost": 0.02},
    {"id": 2, "task_ok": True,  "policy_ok": False, "cost": 0.02},
    {"id": 3, "task_ok": False, "policy_ok": True,  "cost": 0.02},
    {"id": 4, "task_ok": True,  "policy_ok": True,  "cost": 0.02},
    {"id": 5, "task_ok": False, "policy_ok": True,  "cost": 0.02},
    {"id": 6, "task_ok": True,  "policy_ok": True,  "cost": 0.02},
]
n = len(runs)
raw = sum(run["task_ok"] for run in runs)
safe = sum(run["task_ok"] and run["policy_ok"] for run in runs)
violations = sum(not run["policy_ok"] for run in runs)
total_cost = sum(run["cost"] for run in runs)
for run in runs:
    print(run["id"], "safe success:", run["task_ok"] and run["policy_ok"])
print(f"raw success: {raw}/{n} = {raw / n:.1%}")
print(f"safe success: {safe}/{n} = {safe / n:.1%}")
print(f"total cost: USD {total_cost:.2f}")
if safe:
    print(f"cost per safe success: USD {total_cost / safe:.2f}")
else:
    print("cost per safe success: undefined (zero safe successes)")
print("policy gate:", "PASS" if violations == 0 else "BLOCK")
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
1 safe success: True
2 safe success: False
3 safe success: False
4 safe success: True
5 safe success: False
6 safe success: True
raw success: 4/6 = 66.7%
safe success: 3/6 = 50.0%
total cost: USD 0.12
cost per safe success: USD 0.04
policy gate: BLOCK
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. Run 2 contributes to raw success but not safe success; it also blocks the release gate.
  2. Runs 3 and 5 are policy-compliant failures, distinct from unsafe behavior.
  3. The denominator and all-attempt cost make the operational metric reproducible.

Use the aggregate metrics to compare candidates, then inspect failed trajectories to understand causes. A lower score may originate in retrieval, a tool contract, planning or evaluation itself.

From the Exercise to an Application

From the Exercise to an Application
SituationPractical choiceImportant qualification
Testing a new releaseUse frozen cases plus targeted regressionsDo not tune exclusively to the visible benchmark.
Stochastic agentRun repeated trials by task categoryOne successful trajectory does not establish reliability.
Safety-sensitive workflowEnforce explicit policy gatesA high average task score cannot cancel a serious violation.
Experiment: Make run 2 policy-compliant while keeping everything else unchanged.

Safe success rises to 4/6 and cost per safe success falls to $0.03. The policy gate passes, but other predeclared quality or latency gates may still fail.

Summary / Key Takeaways

  • Agent evaluation must score both the final outcome and the trajectory used to reach it.
  • Useful trajectory metrics include tool selection, argument correctness, unnecessary actions, recovery, policy compliance, latency, cost, and stopping behavior.
  • Deterministic evaluators are best for clear rules, human review is valuable for nuanced high-risk judgments, and model judges need calibrated rubrics and validation.
  • A high task-success average can hide unsafe trajectories, unauthorized actions, or rare critical failures.
  • Evaluation sets should contain realistic tasks, edge cases, adversarial inputs, expected actions, and explicit success conditions.
  • Public benchmarks are useful signals but may be contaminated or mismatched to the application’s real environment.
  • Production failures should be converted into regression cases and rerun before future releases.

Verified Further Reading

These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Evaluating Agents: Task Success, Safety, Trajectories & Benchmarks"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why is final-answer accuracy alone insufficient for evaluating an agent?
Question 2 of 5numerical/formula
A 20-case suite has 17 correct final outcomes. What is the task-success rate?
Question 3 of 5numerical/formula
Those same 20 runs contain two policy violations, both among the 17 successful outcomes. How many runs are both successful and free of those violations?
Question 4 of 5practical selection
Which evaluator is best for verifying that every tool amount is <= an explicit limit?
Question 5 of 5debugging/diagnostic
A public benchmark score improves, but real support-task performance falls. What lesson should the team apply?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why is final-answer accuracy alone insufficient for evaluating an agent?▼

Correct Answer: An agent may reach the right answer through unsafe, unauthorized, wasteful, or incorrect intermediate actions

Agent evaluation must inspect the journey as well as the destination because real-world actions and failures occur during the trajectory.

2A 20-case suite has 17 correct final outcomes. What is the task-success rate?▼

Correct Answer: 85%

17/20 = 0.85 = 85%.

3Those same 20 runs contain two policy violations, both among the 17 successful outcomes. How many runs are both successful and free of those violations?▼

Correct Answer: 15

Two of the 17 successful runs are unsafe, leaving 15 runs that are both successful and violation-free.

4Which evaluator is best for verifying that every tool amount is <= an explicit limit?▼

Correct Answer: A deterministic programmatic check

Clear numeric/policy rules are most reliably and cheaply checked deterministically.

5A public benchmark score improves, but real support-task performance falls. What lesson should the team apply?▼

Correct Answer: Benchmarks can be mismatched; evaluate on representative application scenarios and traces

Benchmarks are useful signals but do not replace task-specific evaluation on realistic cases.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next