Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 15 min · revision 2

Outcomes, Trajectories and Why Both Matter

Learn the two questions every agent evaluation asks: did the environment end in the right state (outcome), and did the agent get there in an acceptable way (trajectory). Write a task as environment, initial state, instruction and checks, and grade recorded runs against a mock backend.

Contentsand lesson path

What you will learn

  • Build a task suite with reproducible environments (mocked or sandboxed tools) and outcome checks that verify the end state, not just the final message.
  • Score trajectories for tool selection, argument correctness, step efficiency and policy adherence, using code checks and calibrated model graders.

Prerequisites: AI Evaluation, Agent Loops & ReAct

01. Why it matters

A chatbot produces text, so you can grade the text. An agent acts: it calls tools that change records in other systems, such as refunds, bookings or support tickets. When you evaluate an agent, you are asking two separate questions. Did the world end up in the right state? And did the agent get there in an acceptable way? This lesson calls the first an outcome evaluation and the second a trajectory evaluation. You need both, because each one misses failures that the other one catches.

Throughout this skill you will work with one small example: a support agent for an online shop. It can look up a customer, check the customer's security code, read an order, issue a refund and cancel an order. The shop's policy says that the agent must verify the customer's identity before it changes anything. Each lesson grades this agent in a different way, and the labs build a small evaluation harness for it that runs on your own machine, with no API key. If the basic agent loop (model call, tool call, tool result, repeat) is new to you, read The Loop in Sixty Lines first.

02. Outcome and trajectory: two different questions

The outcome is the end state of the environment after the run: which rows exist in the database, which order was cancelled, how much money was refunded. An outcome check reads that state directly and compares it with what the task expects. For a refund task it asks the backend "how much was refunded on order A-1001?" and expects 4,000 pence, however the agent got there.

The trajectory (also called the trace or transcript) is the full record of the run: every model call, every tool call with its arguments, every tool result and the final reply. A trajectory check looks at the path. Did the agent use the right tools, with the right arguments? Did it follow rules such as "verify before refund"? Did it waste steps, for example by reading the same order three times?

Why not use only one? An outcome check alone cannot see a policy breach that happened to end well. If the agent refunds the right amount without checking the security code, the end state is correct, yet this agent would refund anyone who knows an order number. A trajectory check alone cannot see whether anything really happened: an agent can call the right tools in the right order with the wrong amount, or a tool can fail unnoticed. So a typical task has an outcome check and a few trajectory rules, and a run passes only when both hold.

One warning before lesson 3 covers trajectory checks in depth: check rules about the path, not one exact path. Agents often find valid routes the task author did not expect, such as reading the order before looking up the customer. A test that demands one exact sequence of tool calls fails those runs for no good reason.

03. Why the final message is not evidence

The last thing an agent says is the easiest thing to grade, and the least reliable. A reply such as "Your refund of £40.00 has been issued" is a claim. The model writes it, and nothing forces the claim to match what the tools did. There are three common ways for the two to drift apart:

  • A tool call failed, and the model did not notice or did not mention it. The reply describes the plan, not the result.
  • The tool succeeded, but with different arguments from the ones the reply describes, for example another amount or another order.
  • The model never called the tool at all, because it decided that the user only needed reassurance.

In each case, a grader that reads only the reply gives a pass, and a customer who was promised money gets none. A false claim of success is worse than an honest failure, because nobody follows it up. That is why the end-state check reads the backend, not the reply. Anthropic's engineering guide to agent evaluations makes the same point with a flight booking: the agent may say that the flight is booked, but the outcome is whether a reservation exists in the environment's database.

The reply still matters. It is the part the customer reads, so it should be accurate and clear. But you grade it as a separate property, after the end state, and lesson 3 shows how to do that with a model grader.

04. What a task is made of

To check an end state, you need to know the start state and control everything in between. That is why an agent task is more than a prompt. It has four parts:

  1. An environment: the tools the agent may call and the backend behind them. In evaluation this is usually a mock, a small fake implementation in your own code, or a sandbox, a disposable copy of a real system, for example in a container. It is not the live service.
  2. An initial state: the exact data the environment starts with, such as which customers and orders exist.
  3. An instruction: what the user asks. It can be one message or, as in the tau-bench benchmark, a simulated user: another model that follows a hidden goal over several turns.
  4. Checks: the end state that must hold, plus the trajectory rules.

Here is one task written as data, with a mock backend small enough to read in a minute. Amounts are in pence, so that no rounding can creep in. MockShop makes a deep copy of the initial state when it starts, so a run can never change the task definition, and every run can start from the same data.

Python · refund-check/task.py
"""One agent task as data, plus the mock backend it runs against (stdlib only)."""
import copy

TASK = {
    "id": "refund-broken-kettle",
    "initial_state": {
        "customers": {"ana": {"code": "4417"}},
        "orders": {"A-1001": {"customer": "ana", "total": 4000, "refunded": 0}},
    },
    "instruction": "I'm ana, code 4417. Order A-1001 arrived broken. Refund it.",
    "expected_refund": {"A-1001": 4000},  # pence; the end state we will check
    "step_budget": 4,  # tool calls a careful agent needs, with a little slack
}


class MockShop:
    """Holds state in memory; every tool call reads or changes it."""

    def __init__(self, initial_state: dict) -> None:
        self.state = copy.deepcopy(initial_state)  # never share the original
        self.verified: set[str] = set()

    def verify_identity(self, customer: str, code: str) -> dict:
        if self.state["customers"].get(customer, {}).get("code") != code:
            raise ValueError("identity check failed")
        self.verified.add(customer)
        return {"verified": True}

    def get_order(self, order_id: str) -> dict:
        return dict(self.state["orders"][order_id])

    def issue_refund(self, order_id: str, amount: int) -> dict:
        order = self.state["orders"][order_id]
        if order["refunded"] + amount > order["total"]:
            raise ValueError("refund exceeds order total")
        order["refunded"] += amount
        return {"refunded": order["refunded"]}

05. Grading three recorded runs

The next script grades three recorded runs of this task. Each run is the list of tool calls an agent made, plus its final reply. The script replays each run against a fresh MockShop, so the end state comes from the tool implementations, not from the reply. Then it applies one outcome check, one policy rule and a step count. It needs only Python 3.10 or later (tested with 3.12) and no packages. Save both files in a folder called refund-check and run:

Python · refund-check/grade_runs.py
"""Replay recorded runs against a fresh mock, then grade outcome and trajectory."""
from task import TASK, MockShop

# Each run is what an agent did: its tool calls in order, then its final reply.
RUNS = {
    "run-a": {"calls": [("verify_identity", {"customer": "ana", "code": "4417"}),
                        ("get_order", {"order_id": "A-1001"}),
                        ("issue_refund", {"order_id": "A-1001", "amount": 4500})],
              "reply": "Your refund of £40.00 has been issued."},
    "run-b": {"calls": [("get_order", {"order_id": "A-1001"}),
                        ("issue_refund", {"order_id": "A-1001", "amount": 4000})],
              "reply": "Done! £40.00 is on its way back to you."},
    "run-c": {"calls": [("verify_identity", {"customer": "ana", "code": "4417"}),
                        ("get_order", {"order_id": "A-1001"}),
                        ("get_order", {"order_id": "A-1001"}),
                        ("get_order", {"order_id": "A-1001"}),
                        ("verify_identity", {"customer": "ana", "code": "4417"}),
                        ("issue_refund", {"order_id": "A-1001", "amount": 4000})],
              "reply": "I have refunded £40.00 to your card."},
}


def replay(calls: list) -> tuple[MockShop, list]:
    shop = MockShop(TASK["initial_state"])  # a fresh environment for every run
    log = []
    for name, args in calls:
        try:
            getattr(shop, name)(**args)
            log.append((name, args, "ok"))
        except ValueError as exc:
            log.append((name, args, f"error: {exc}"))
    return shop, log


def outcome_ok(shop: MockShop) -> bool:
    return all(shop.state["orders"][o]["refunded"] == amount
               for o, amount in TASK["expected_refund"].items())


def policy_ok(log: list) -> bool:
    """Rule: no refund before a successful identity check."""
    verified = False
    for name, _args, result in log:
        if name == "verify_identity" and result == "ok":
            verified = True
        if name == "issue_refund" and not verified:
            return False
    return True


for run_id, run in RUNS.items():
    shop, log = replay(run["calls"])
    errors = [f"{n}: {r}" for n, _a, r in log if r != "ok"]
    print(f"{run_id}  reply: {run['reply']}")
    print(f"        outcome  {'PASS' if outcome_ok(shop) else 'FAIL'}"
          f"  (refunded {shop.state['orders']['A-1001']['refunded']} pence)")
    print(f"        policy   {'PASS' if policy_ok(log) else 'FAIL'}"
          "  (verify_identity before issue_refund)")
    print(f"        steps    {len(log)} of budget {TASK['step_budget']}"
          f"{'  (over budget)' if len(log) > TASK['step_budget'] else ''}")
    if errors:
        print(f"        errors   {'; '.join(errors)}")
    passed = outcome_ok(shop) and policy_ok(log)
    print(f"        verdict  {'PASS' if passed else 'FAIL'}")
Terminal
python3 grade_runs.py
Expected output
run-a  reply: Your refund of £40.00 has been issued.
        outcome  FAIL  (refunded 0 pence)
        policy   PASS  (verify_identity before issue_refund)
        steps    3 of budget 4
        errors   issue_refund: error: refund exceeds order total
        verdict  FAIL
run-b  reply: Done! £40.00 is on its way back to you.
        outcome  PASS  (refunded 4000 pence)
        policy   FAIL  (verify_identity before issue_refund)
        steps    2 of budget 4
        verdict  FAIL
run-c  reply: I have refunded £40.00 to your card.
        outcome  PASS  (refunded 4000 pence)
        policy   PASS  (verify_identity before issue_refund)
        steps    6 of budget 4  (over budget)
        verdict  PASS

Read the three runs as three different stories:

  • run-a says the refund was issued, and every step was in policy. But the agent asked for 4,500 pence on a 4,000-pence order, the tool refused, and the reply ignored the error. The outcome check reads 0 pence refunded and fails the run. A grader that read only the reply would have passed it.
  • run-b reached the right end state but never verified the customer. The outcome check passes it and the policy rule fails it. Outcome-only grading would have let it through.
  • run-c is correct and in policy, but read the same order three times and verified twice: six tool calls where three were enough (the budget allows four). Wasted steps cost tokens and time, and a count that grows between versions is an early sign of a confused agent. Here, as in many teams, efficiency is reported next to the verdict rather than failing the run.

What decided each verdict was the state read from the backend and rules applied to the recorded calls. The reply text changed no verdict. The next lesson builds a harness that produces runs like these against a resettable backend.

06. Check your understanding

Practice check · 3 questions

Outcomes and trajectories

Answer from the code and the runs in this lesson.

Q1. In `grade_runs.py` you change the refund amount of run-a from 4500 to 4000 and leave its reply unchanged. What does the script now print for run-a?
Q2. A teammate wants to replace `outcome_ok` with a check that the reply mentions "£40.00", because it is simpler. Which run would that grade wrongly?
Q3. Why does `MockShop.__init__` deep-copy the initial state of the task?
Practice only: not graded, not saved, not evidence.

07. Apply it

The practice project for this skill is a 25-task suite for your own support agent. Start it now with three tasks written as data, in the shape of TASK: one refund, one cancellation and one request the agent must refuse. For each, write the initial state, the instruction, one end-state check and one trajectory rule, such as "no issue_refund before a successful verify_identity". Then write two runs by hand for one task, one that should pass and one that claims success without the state to show for it, and check that your grader tells them apart. Lab 2 turns these into a harness that runs an agent for you.

08. Review prompt

Without looking back: name the four parts of an agent task, and say what an outcome check reads and what a trajectory check reads. Describe one run that passes the outcome check and fails a trajectory rule, and one that does the opposite. Then explain why a reply such as "your refund has been issued" is not evidence that a refund exists.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check