Trajectories and traces
What Viewport Evals records about a run, how capture works, and the Trace helpers you assert with.
A trajectory is the typed record of one agent run: its input, output or error, wall-clock latency, and an
ordered list of events. It is the only thing assertions read. The schema (trajectory/v1) comes from Viewport Core,
so HITL, Context and your own code all emit the same events.
| Event | What it records | Read by |
|---|---|---|
model_call | model, provider, usage (input, output, cache read and write tokens), response_id, finish reason | model_calls, budget |
tool_call | tool_name, args, result or error, call_id, latency | tools |
agent | an agent or graph node run, parent of what ran inside it | agents, within |
handoff | from_agent, to_agent | handoffs |
approval | tool_name, decision and status | approvals, gated, invariants |
world_change | the world, the tool call, and each changed path with before and after | world, invariants |
message | a user or assistant message, including simulated users' turns | events |
skill_load | skill, tokens, status | skills |
| anything else | any event type, including your own | events |
Events nest through parent_id, and each carries turn, the conversation turn it happened in, and in
multi-episode cases episode_id. Under a simulated clock, timestamps are
simulated time.
Capture is ambient
trace() opens a scope. Inside it, adapters emit events into Viewport Core's ambient sink and the scope collects
them; outside a scope, emitting costs one context lookup and records nothing. Your agent never receives a recorder.
with trace() as t:
t.output = support_agent(model.anthropic(), "My order A-1001 arrived damaged.")const t = await trace(() => supportAgent(model.anthropic(), "My order A-1001 arrived damaged."));Where events come from, in order of preference:
- Framework adapters (LangGraph, OpenAI Agents SDK, AI SDK v7) install themselves on the first
trace()or YAML case run and see agents, handoffs and tool calls as the framework reports them. A case agent needs notrace()of its own. - Client wrappers (
wrap(client)for the Anthropic and OpenAI SDKs) see every model round trip and pair tool calls with thetool_resultthat comes back. - Spans: an OpenTelemetry span processor, or
viewport-evals importfor OTLP JSON files.
When two sources see the same model call, the trace keeps one event (matched by response_id) from the
higher-level source and fills missing usage fields from the other, so counts are never doubled. Scripted fakes emit
their own model_call events with synthetic response ids, so they dedupe the same way.
Tool calls dedupe the same way. A framework function tool whose body calls a Viewport Core tool of the same name,
such as a world tool, is one tool_call: matched by call_id, nesting, time or equal arguments, never across two
different call ids. The core event is kept with the framework's agent parent, so its world_change stays under it
and tools, invariants and budgets count the call once. A wrapper with a different name is a different tool, and
both calls stay.
Pick adapters with instrument in config (true, false or a list of slugs, also VIEWPORT_EVALS_INSTRUMENT), which
the YAML case runner follows, or trace(instrument=...) for one scope.
The Trace
trace() gives you a Trace: every trajectory field plus query helpers that run through the same engine as YAML
cases, so an in-code assertion and a YAML expectation cannot disagree.
| Python | TypeScript | Returns |
|---|---|---|
t.tool_names | t.toolNames | tool names in completion order |
t.tool_calls, t.calls("x") | t.toolCalls, t.calls("x") | tool_call events, all or for one tool |
t.model_calls | t.modelCalls | model_call events |
t.agents, t.skills | same | those events (skills: loaded ones only) |
t.approvals, t.gated | same | human approvals (decision: ask), and every policy outcome for a gated action |
t.usage.tokens, .input_tokens, .output_tokens, .cost_usd | same | totals; cost_usd raises evals.unpriced_model rather than guess |
t.called("x", order_id="A-1") | t.called("x", { order_id: "A-1" }) | a truthy Check (Python) or a boolean (TS) |
t.meets({...}), await t.ameets({...}) | await t.meets({...}) | a Check for a full expect: block |
t.upholds(invariants), t.violations(invariants) | same | a Check for invariants, or each violation |
t.diff(baseline) | same | a trajectory diff against another run |
t.within("support") | t.within("support") | a Trace of what ran under that agent |
t.output, t.error, t.latency_ms | same | run result fields |
t.to_trajectory(), t.to_json() | t.toTrajectory() | the plain trajectory |
Two differences follow from each language's idiom:
- Output. In TypeScript
t.outputis the traced function's return value. In Python the scope is awithblock, sot.outputis what a framework adapter reported, or what you assign inside the block (t.output = agent.run(...)). Assign it when a YAML-styleoutputexpectation should see it. - Called. Python's
t.calledreturns aCheckwhosereprexplains a miss, so a bareassertprints why. TypeScript returns a boolean; use the vitest matchertoHaveCalledToolfor a message.
t.called and the matchers that use it raise evals.nothing_captured when the trace holds no model or tool call,
so a negative assertion can never pass because capture was not set up. Pass allow_empty=True / allowEmpty: true
for code that legitimately calls nothing.
Agents and sub-trajectories
Framework adapters record agents and handoffs. t.within(name) scopes every helper to one agent, and the YAML form
is agents.within. From the OpenAI Agents SDK example, where a triage agent hands off to support:
import { lte, trace } from "@viewportai/evals";
import { reply, script, toolCall } from "@viewportai/evals/testing";
import { expect, test } from "vitest";
import { runSupport } from "../src/agent.js";
test("triage hands off to support, which refunds the order", async () => {
const model = script(
toolCall("transfer_to_support", {}),
toolCall("lookup_order", { order_id: "A-1001" }),
toolCall("issue_refund", { order_id: "A-1001", amount: 42.5 }),
reply("Refund R-1001 for $42.50 is on its way."),
{ model: "gpt-5" },
);
const t = await trace(() => runSupport(model.openaiAgents(), "Order A-1001 arrived damaged."));
expect(t.agents.map((a) => a.name)).toEqual(["triage", "support"]);
expect(t.within("support").toolNames).toEqual(["lookup_order", "issue_refund"]);
expect(t).toHaveCalledTool("issue_refund", { order_id: "A-1001", amount: lte(100) });
expect(t).not.toHaveCalledTool("delete_account");
expect(t).toHaveModelCalls(4);
expect(t).toBeWithinBudget({ tokens: 2000, cost_usd: 0.01 });
expect(t.output).toContain("R-1001");
model.assertConsumed();
});
In pytest and vitest
In pytest, every test gets its own fixture file, and the trajectory fixture is a Trace around the whole test:
# `trajectory` is a Trace around the whole test: everything the test's code does is captured.
async def test_with_the_fixture(trajectory: Trace) -> None:
await issue_refund.execute({"order_id": "A-1001", "amount": 42.5})
assert trajectory.called("issue_refund", amount=lte(100))
In vitest, call trace() inside the test; the setup file gives each test its own fixture file in the same layout.
Next: cases and expectations.
Quickstart
Install Viewport Evals, test what your agent changed in a simulated world and the rules it must never break, in code and as a YAML case, then replay in CI. Python and TypeScript side by side.
Cases and expectations
The YAML case format, suite files and defaults, how inputs reach your agent, and every expectation group.