Score agent trajectories, tool calls and token cost
Score answer quality, citation support, allowed tool use, unnecessary calls, latency and cost while accepting equivalent valid trajectories.
By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.
In short
A trajectory is the full record of one agent run: every model call, tool call, argument, result, timing and token count, plus the final answer. Scoring the trajectory, not just the final text, shows whether the agent used only allowed tools, wasted calls, cited real evidence and stayed inside its latency and cost budgets. Good scoring checks outcomes and constraints, so two different but valid paths both pass.
Explained simply
An agent does not just answer. It decides to search, reads results, maybe looks up a ticket, maybe searches again, and then writes a reply. The record of all those steps is called a trajectory. Two agents can give the same final answer while one of them broke a rule on the way.
Trajectory evaluation scores the whole run. Did the agent use only the tools it is allowed to use? Did it repeat the same search three times? Does each citation really support the sentence it is attached to? How long did it take and how many tokens did it burn?
There is often more than one good path. One run might look up the ticket first and then search the docs; another might do it the other way round. Both are fine if they reach the right outcome, use the needed evidence and stay inside the limits. So instead of comparing to one exact path, you check rules: what must happen, what must never happen, and how much is too much.
To do this, the agent must write down every step as structured data while it runs. Then scoring is just a function that reads that record. You can rerun scoring later without calling the model again.
Press Play on a diagram to walk through it one step at a time.
- 1Outcome
Right result type: answer, clarify, abstain or deny
- 2Answer and citations
Must-include facts present; every claim supported by a cited source
- 3Tool policy
Only allowed tools, valid arguments, caller scope respected
- 4Efficiency
Unnecessary or repeated calls counted
- 5Budgets
Latency and token cost against limits
- Expects one fixed call order
- Fails a valid shortcut
- Easy to write
- Breaks when tools are renamed
- Checks required and forbidden calls
- Accepts any valid order
- Caps total calls and cost
- Survives harmless prompt changes
- Agent to search_docs: search: parental leave days1search: parental leave days
- search_docs to Agent: policy-leave#s2@v32policy-leave#s2@v3
- Agent to search_docs: search: parental leave days (duplicate)3search: parental leave days (duplicate)
- search_docs to Agent: policy-leave#s2@v3 again4policy-leave#s2@v3 again
- Agent to ticket_status: ticket_status: T-10425ticket_status: T-1042
- ticket_status to Agent: status: open6status: open
In depth
Recording a trajectory you can score
Give each run a run ID and record a list of events. Each event has a kind (model, tool or final), a start time and duration, and the fields that matter for that kind. Model events store the model ID, input and output token counts and the finish reason. Tool events store the tool name, validated arguments, a result summary (such as returned source IDs), and status: ok, error, timeout or denied. The final event stores the outcome type, answer text and cited source IDs.
Store source IDs and counts, not whole passages, so the trajectory is small and safe to keep. In tests, the runner writes the trajectory to a JSON file next to the result. Scoring code then loads the file and never touches the agent.
- run_id, case_id, dataset and prompt versions
- model events: model ID, tokens, duration
- tool events: name, args, returned IDs, status
- final event: outcome, answer, cited IDs
Scoring answers and citation support
Score the outcome first: is the result type the expected one? Then check answer content with deterministic rules: every must-include fact appears and no must-not-include text appears. Citation support has two levels. Citation validity is a rule: every cited ID was actually returned by a tool in this run and is visible to the caller. Citation support asks whether the cited passage really backs the sentence, which is harder.
For support, start with simple checks, such as requiring that key numbers in the sentence appear in the cited passage. Add a model grader for the remaining cases only after calibrating it against people, which the next topic covers. Keep validity and support as separate scores, so you know whether a failure came from inventing sources or from misreading real ones.
- 1Cited ID
From the final answer
- 2Was it retrieved?
Appears in a tool result in this run
- 3Is it visible?
Inside the caller's scopes
- 4Is it current?
Not a superseded version
- 5Does it support?
Key facts appear in the passage
Tool policy and unnecessary calls
Tool checks split into hard rules and efficiency. Hard rules fail the case: a call to a tool outside the allowed list, a call with a scope that is not the caller's, or a write action from an agent that must be read-only. Efficiency is scored, not failed: duplicate calls with the same name and arguments, searches whose results were never cited and total calls above the case's budget.
Write per-case requirements as constraints. required_tools lists tools that must appear at least once, for example ticket_status when the user asks about a ticket. forbidden_tools lists ones that must not appear. max_tool_calls caps the total. These three cover most cases without fixing the order.
Accepting equivalent trajectories
Two trajectories are equivalent when they reach the same outcome, cite the required evidence, break no hard rules and stay inside the budgets. Order usually does not matter. When it does, express it as a precise rule, such as the clarifying question must come before any search, rather than a full expected path.
This matters because agents change. A new prompt might skip a redundant search, or a new model might search with better wording first time. A path-matching test would fail that improvement. A constraint-based test passes it and shows the lower call count as a better efficiency score.
Latency and token cost per case
Latency is the wall-clock time from request to final answer; also keep per-step times so you can see whether the model or a tool was slow. Cost is input tokens times the input price plus output tokens times the output price, summed over every model call, plus any priced tool calls. Keep prices in a versioned config file and treat figures as estimates, because providers change prices.
With a deterministic stub, token counts come from the stub's own counting, so cost numbers are illustrative only. Label them so. With a real model, take token counts from the usage data in the response rather than estimating from text length.
- Latency: total and per step
- Cost = input tokens x input price + output tokens x output price
- Prices in a versioned config file
- Label stub costs as illustrative
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Record each run's trajectory~50m
- 2Check allowed and unnecessary tool calls~50m
- 3Score answer and citation support~50m
- 4Accept multiple valid paths~50m
- 5Report latency and token cost~50m
Key points
- Record the trajectory as structured events with a run ID, so scoring is a pure function over data.
- Hard failures (forbidden tool, cross-scope source, uncited claim) should fail the case regardless of other scores.
- Count unnecessary calls, such as repeating an identical search, as a separate efficiency score.
- Accept equivalent trajectories by checking outcome, required evidence and limits rather than call order.
- Report latency and token cost per case so you can see what each quality gain costs.
Key terms
Tap a card to flip it. 0/5 known
Examples
def score_tools(run, case, allowed={"search_docs", "ticket_status"}):
calls = [s for s in run.steps if s.kind == "tool"]
names = [c.name for c in calls]
seen, dupes = set(), 0
for c in calls:
key = (c.name, tuple(sorted(c.args.items())))
dupes += key in seen
seen.add(key)
return {
"forbidden": [n for n in names if n not in allowed],
"missing_required": [n for n in case.required_tools if n not in names],
"duplicate_calls": dupes,
"over_budget": len(calls) > case.max_tool_calls,
}Checks the tool policy without caring about call order.
Two valid paths, one score
Case tick-003 asks: Is my leave request T-1042 approved, and how many days do I have left? Run A calls ticket_status then search_docs. Run B calls search_docs then ticket_status. Step 1: both outcomes are answer. Step 2: both cite policy-leave#s2@v3 and mention the ticket status. Step 3: both used only allowed tools and two calls, under the limit of four. Step 4: both pass. Run B took 1.4 seconds and Run A 1.6 seconds, a difference you report but do not fail on.
Scoring citation validity
Step 1: collect every source ID returned by tool events in the run. Step 2: for each cited ID, check it is in that set, in the caller's visible set and not superseded. Step 3: return the list of bad IDs. An empty list means all citations are valid. A non-empty list is a hard failure, because the agent cited something it never retrieved or should not see.
def invalid_citations(run, visible_ids, superseded_ids):
retrieved = {sid for s in run.steps if s.kind == "tool"
for sid in s.result_ids}
bad = []
for sid in run.final.cited_ids:
if sid not in retrieved:
bad.append((sid, "not retrieved"))
elif sid not in visible_ids:
bad.append((sid, "out of scope"))
elif sid in superseded_ids:
bad.append((sid, "superseded"))
return badQuick reference
- Trajectory = every model call, tool call and result in one run, with timings
- Hard fails: forbidden tool, out-of-scope source, write action, invented citation
- Efficiency: duplicate calls, unused searches, calls over budget
- Constraints: required_tools, forbidden_tools, max_tool_calls
- Citation validity (retrieved, visible, current) is separate from support
- Cost = input tokens x input price + output tokens x output price
- Store IDs and counts in trajectories, not full passages
Common mistakes
- Grading only the final answer, which hides agents that reached it by calling a tool they should not use.
- Hard-coding one expected sequence of calls, so a better agent fails the test.
- Averaging a cross-scope leak into an overall score instead of treating it as a blocking failure.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Given a list of tool events with name and args, count duplicate calls.
- Exercise 2medium
Write check_constraints(names, case) that returns pass or a list of reasons using required_tools, forbidden_tools and max_tool_calls.
- Exercise 3hard
Compute the cost of a run from its model events and a price table in USD per million tokens. Return total cost and the most expensive step.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Do I need a framework to evaluate agent trajectories?
- No. A list of structured events per run and a few Python scoring functions are enough to start. Frameworks help later with dashboards and storage.
- Should a slow run fail the test?
- Only if it exceeds a budget you agreed on. Otherwise report latency as a number so trends are visible without making tests flaky.
- Why not just ask a model whether the run was good?
- Rules are cheaper and give the same verdict every time. Use a model grader only for qualities rules cannot judge, and check it against human labels first.