Cases and expectations
The YAML case format, suite files and defaults, how inputs reach your agent, and every expectation group.
A case is an input plus an expect: block. The same expect: shape works inline in code (t.meets({...}),
toMeet({...})), so anything below can be asserted either way. Case files are strict: an unknown key is an error
with file, line, column and a did-you-mean, so a typo like not_caled fails loudly instead of passing silently.
Every key is listed in the case schema reference.
A suite file
One file can hold one case or a suite. A suite has defaults and cases:
# yaml-language-server: $schema=https://getviewport.com/schemas/evals/case/v1.json
# A suite file: shared defaults, then cases. Negative lists such as not_called union with each case's own.
defaults:
tags: [refunds]
expect:
tools: { not_called: [delete_account] }
budget: { tokens: 4000, cost_usd: 0.02 }
cases:
- id: damaged-order
description: A damaged order is looked up and refunded in one pass.
tags: [golden]
input: "My order A-1001 arrived damaged."
expect:
tools:
exactly: [lookup_order, issue_refund]
calls: [{ tool_name: issue_refund, args: { order_id: A-1001, amount: { lte: 100 } } }]
model_calls: 3
output: { contains: R-1001 }
- id: asks-for-the-order
description: Without an order id the agent asks for one before touching any tool.
input:
turns: ["Hi, I have a problem with an order.", "It's A-1001, it arrived damaged."]
expect:
tools: { in_order: [lookup_order, issue_refund], first: lookup_order }
model_calls: { max: 5 }
output: { contains: R-1001 }
Merge rules for defaults: tags union; scalars such as runs or agent are taken from the case when it sets
them; expect merges one level deep per group with the case winning per key, except the negative lists
(not_called, approvals.not_called, world.*.not_changed), which union, so a suite-level guard can never be
dropped by a case; use and invariants concatenate.
Inputs and the agent
input is a prompt string, or an object with one of prompt, turns (scripted user turns; the agent runs once
per turn) or script (episodes: user messages, approval decisions, external
events and clock advances), plus optional messages (prior history) and context (free-form data passed through
untouched). A case can also declare world: (worlds the agent acts on), clock: (a
simulated clock) and replay: (tool responses served from a
production trace). For turns that depend on the agent's replies, use a
simulated user.
The registered agent receives a CaseInput for each turn: prompt, history (every message so far, including the
agent's previous answers), context, session (a dict that persists across the turns of one run), case_id /
caseId and turn, plus worlds (the run's world instances), event and episode (in multi-episode cases) and
model (in a model matrix). TypeScript adds signal, aborted on timeout_ms. In Python, an agent
whose first parameter is annotated str receives just the prompt; any other agent, including an unannotated
lambda, receives the CaseInput.
# The registered agent runs once per turn. ``session`` persists across the turns of one run.
def agent(case_input: CaseInput) -> str:
messages = case_input.session.setdefault("messages", [])
messages.append({"role": "user", "content": case_input.prompt})
return support_agent(fake_model(case_input.prompt), messages)
// The registered agent runs once per turn. `session` persists across the turns of one run.
async function agent(input: CaseInput): Promise<string> {
const messages = (input.session.messages ??= []) as Anthropic.MessageParam[];
messages.push({ role: "user", content: input.prompt });
return supportAgent(fakeModel(input.prompt), messages);
}Register agents in config: agent for the default, agents for named ones that a case selects with agent:.
Python also offers @agent and @agent("name") decorators.
Running a suite from code is what the CLI, the pytest plugin and describeCases do for you:
cases = load_cases("evals/**/*.yaml", cwd=Path(__file__).parent)
config = resolve_config(agent=agent)
report = run_cases(cases, config=config, store=MemoryFixtureStore(), mode="auto")
for v in report["verdicts"]:
print("\n".join(verdict_lines(v)))
# PASS damaged-order ...
# PASS asks-for-the-order ...
assert report["ok"]
assert report["verdicts"][0]["tags"] == ["refunds", "golden"] # suite tags union with the case'sconst cases = await loadCases("evals/**/*.yaml", { cwd: import.meta.dirname });
const config = resolveConfig({ agent });
const report = await runCases(cases, { config, store: memoryFixtureStore(), mode: "auto" });
for (const v of report.verdicts) console.log(verdictLines(v).join("\n"));
// PASS damaged-order ...
// PASS asks-for-the-order ...
assert.ok(report.ok);
assert.deepEqual(report.verdicts[0]?.tags, ["refunds", "golden"]); // suite tags union with the case'sExpectation groups
Every key produces named assertion results such as tools.exactly, budget.cost_usd or
approvals.status.issue_refund. The names are stable API: reporters, CI annotations and the conformance suite use
them.
| Group | Asserts |
|---|---|
tools | tool calls by tool_name: sequences (below), no_errors, and calls with matchers on args, result and error |
model_calls | the number of model round trips, as a Range |
budget | tokens, input_tokens, output_tokens, cost_usd, latency_ms; each number means at most |
output | a matcher, or a list of matchers that must all pass |
error | false (default: must not fail), true (must fail), or { type, message } with a matcher on each |
approvals | human approvals (decision: ask) by tool name, plus status: { tool: approved } and before_side_effect: true |
gated | every policy outcome for a gated action (allow, ask, deny) by tool name, plus status and decision maps |
skills | skill loads by name, plus tokens, a budget on total skill tokens |
agents | agent runs by name, plus within: { name: { ...expect } } for one agent's sub-trajectory |
handoffs | handoffs by target agent |
events | any event type: { type, where, count } with a matcher in where |
invariants | rules over the whole run, inline or { file } |
world | the end state of each declared world: state, changed, only_changed, not_changed |
baseline | the behavior diff against the imported trace: tools: same, output, cost_usd.max_increase |
when | expectations that apply only for matching models in a model matrix |
use | assertion plugins, by name or { name: options } |
Sequences
tools, agents, skills, handoffs, approvals and gated share one vocabulary. A bare list is shorthand for
called, and names may be globs such as mcp__crm__*.
| Key | Passes when |
|---|---|
called: [a, b] | each name appears at least once |
not_called: [c] | none appears |
in_order: [a, b] | they appear as a subsequence; others may be interleaved |
exactly: [a, b] | the full sequence equals this list |
unordered: [a, b, b] | the full sequence is this multiset, in any order |
only: [a, b] | nothing outside this allow-list appears |
first: a, last: b | the first or last entry |
count: Range | total number of entries |
counts: { a: Range } | per-name counts |
Tool calls
Each entry in tools.calls matches calls to one tool. which picks the calls that are checked (any, the default;
all; first; last; or a 1-based index), and count (a Range) says how many of them must match, so count: 0
means none may. agent limits the entry to calls made under one agent. args and result are
matchers; plain objects match partially.
Ranges and budgets
Two count types, never confused. A Range is a count: a number means exactly that number, { min, max } gives
inclusive bounds (model_calls, count, counts). A Budget is a resource limit: a number means at most
(budget.*, skills.tokens). viewport-evals validate prints a hint for model_calls: 4, which means exactly 4, because
{ max: 4 } is the common intent.
Cost uses each model call's reported usage.cost_usd when present, else a bundled, dated price table (overridable
with pricing in config). A model that cannot be priced fails budget.cost_usd and names the model; it never
counts as zero. input_tokens includes cache reads and writes.
Counting rules
- A tool call counts once, whether it succeeded or failed.
no_errorsandcalls[].errorlook at failures. - A call refused before it ran (a HITL deny, a permission callback) is an
approvalevent, not atool_call. - A call the framework rejected (unknown tool, invalid arguments) is a
tool_callwith error typeinvalid_tool_call: the model did try. - Provider retries that never returned are not model calls.
- Calls made by subagents count in the parent; scope with
withinorcalls[].agent. - Multi-turn cases count across all turns.
Repeated runs and thresholds
runs: 5 repeats a case in live and record modes. pass_threshold: 0.8 (a fraction) or min_passes: 4 (a
count) sets how many must pass. In live mode, sequential runs stop as soon as the outcome is decided. retries re-runs a run that
crashed, never one that failed an assertion. In code, the same semantics come from
@pytest.mark.viewport(runs=5, pass_threshold=0.8) and vitest's repeat({ runs: 5, passThreshold: 0.8 }, fn):
# A stand-in for a nondeterministic agent: it skips the lookup on every fifth run.
lookup_order = fake_tool("lookup_order", returns={"status": "delivered", "total": 42.5})
runs = itertools.count()
async def flaky_agent() -> None:
if next(runs) % 5 != 4:
await lookup_order.execute({"order_id": "A-1001"})
await issue_refund.execute({"order_id": "A-1001", "amount": 42.5})
@pytest.mark.viewport(runs=5, pass_threshold=0.8)
async def test_refunds_reliably() -> None:
async with trace() as t:
await flaky_agent()
assert t.tool_names == ["lookup_order", "issue_refund"] # 4/5 runs pass (need 4), so the test passes
// A stand-in for a nondeterministic agent: it skips the lookup on every fifth run.
const lookupOrder = fakeTool("lookup_order", { returns: { status: "delivered", total: 42.5 } });
let calls = 0;
async function flakyAgent(): Promise<void> {
if (calls++ % 5 !== 4) await lookupOrder.execute({ order_id: "A-1001" });
await issueRefund.execute({ order_id: "A-1001", amount: 42.5 });
}
test(
"refunds reliably",
repeat({ runs: 5, passThreshold: 0.8 }, async () => {
const t = await trace(() => flakyAgent());
expect(t.toolNames).toEqual(["lookup_order", "issue_refund"]); // 4/5 runs pass (need 4), so the test passes
}),
);Skip, xfail and placeholders
skip: "reason" skips a case. xfail: "reason" expects it to fail; an unexpected pass is reported as xpass and
fails the run. A ~ placeholder (tools: { exactly: ~ }, model_calls: ~, budget: { tokens: ~ }) is filled from
the recording by viewport-evals run --accept or pytest --viewport-accept, with budgets rounded up by
accept_headroom (default 20%). Written values are never touched, so authoring a trajectory test becomes "run
once, review the diff".
Next: modes and fixtures.