Evals

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.

Install

Runtime: Node 22.3 or later, Python 3.11 or later. Create a project; the Anthropic SDK is for the agent on this page.

Python:

mkdir my-agent-py && cd my-agent-py
uv init --bare
uv add --dev viewport-evals anthropic pytest        # or: pip install viewport-evals anthropic pytest

TypeScript:

mkdir my-agent-ts && cd my-agent-ts
echo '{ "private": true, "type": "module" }' > package.json
pnpm add -D @viewportai/evals vitest @anthropic-ai/sdk typescript        # or: npm install -D ...

Adapters for other stacks are optional extras or peer dependencies, for example viewport-evals[langgraph] or the ai package you already have.

In either language, keep the results directory out of git: every local run writes it to .viewport/ for viewport-evals ui. Fixtures in __fixtures__/ are the part you commit.

echo ".viewport/" >> .gitignore

Add this tsconfig.json:

tsconfig.json
{
  "compilerOptions": { "target": "ES2023", "module": "NodeNext", "strict": true, "noEmit": true, "skipLibCheck": true },
  "include": ["src", "test", "viewport.config.ts", "vitest.config.ts"]
}

Every file below is the complete file from examples/*/quickstart. Copy each into my-agent-py or my-agent-ts at the path in its title.

Write a test in code

Test the world, not the path. The agent's tools act on a simulated world, plain JSON state plus the tools that change it, and the test asserts three things in this order:

  1. What changed in the world: world.changed lists the paths that changed, world.state is the end state.
  2. Guard rules: a tool it must never call, and a turn and cost budget.
  3. Order, only where it truly matters: here the refund amount comes from the lookup, so the lookup must come first. Most agents need no sequence check at all.

Wrap the agent call in trace() to capture what it did. The model here is a script(...) from the testing helpers, so the test runs with no keys; in your project you pass your real client.

The agent under test is a plain tool-use loop on the Messages API. wrap(client) from the Anthropic adapter is the one line that makes its model calls visible; world tools record their own calls and changes, and framework adapters such as LangGraph's need no line at all. In Python the world, the agent, the script and the tests sit in one file:

main.py
"""Quickstart: a support agent on the Anthropic Messages API, tested two ways with no keys.

1. In code: ``trace()`` captures what the agent did. The test asserts what changed in a simulated shop, then the
   guard rules (a tool it must never call, a turn and cost budget), and checks the tool order only where it matters.
2. As a YAML case (evals/refund-happy-path.yaml), run by the same engine.

The model is a script (``viewportai.evals.testing``), so this runs offline. With a real client, the first run records
the model traffic and every run after replays it.

Run: ``pytest main.py``. TypeScript counterpart: examples/ts/quickstart
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from viewportai.core import Tool, ToolContext

from viewportai.evals import CaseInput, WorldError, load_cases, resolve_config, run_cases, trace, world
from viewportai.evals.anthropic import wrap
from viewportai.evals.testing import reply, script, tool_call

# region world
# A tiny simulated shop: plain JSON state plus the tools that act on it. The agent calls these tools; the test asserts
# what they changed. ``WorldError`` is a domain error the model reads; the change rolls back.
shop = world(
    "shop",
    state={
        "customers": {"C-7": {"name": "Ines Moreau", "email": "[email protected]"}},
        "orders": {"A-1001": {"customer_id": "C-7", "status": "delivered", "total": 42.5, "damaged": True}},
        "refunds": {},
    },
)


def order_of(state: dict[str, Any], order_id: str) -> dict[str, Any]:
    if order_id not in state["orders"]:
        raise WorldError("not_found", f"no order {order_id}")
    return state["orders"][order_id]


@shop.tool
def lookup_order(state: dict[str, Any], order_id: str) -> dict[str, Any]:
    """Look up an order by id"""
    return {"order_id": order_id, **order_of(state, order_id)}


@shop.tool
def issue_refund(state: dict[str, Any], order_id: str, amount: float) -> dict[str, Any]:
    """Refund an order, up to its total"""
    order = order_of(state, order_id)
    if amount > order["total"]:
        raise WorldError("invalid_argument", f"the order total is {order['total']}")
    refund_id = f"R-{order_id[2:]}"
    state["refunds"][refund_id] = {"order_id": order_id, "amount": amount}
    order["status"] = "refunded"
    return {"refund_id": refund_id}


@shop.tool
def delete_account(state: dict[str, Any], customer_id: str) -> dict[str, Any]:
    """Delete a customer account and its order history"""
    del state["customers"][customer_id]
    return {"deleted": customer_id}


# endregion world


# region agent
def support_agent(client: Any, tools: tuple[Tool[Any], ...]) -> Any:
    """A tool-use loop on the Messages API. ``wrap`` makes every model call visible; world tools record theirs."""
    model = wrap(client)
    by_name = {t.name: t for t in tools}
    specs = [{"name": t.name, "description": t.description, "input_schema": t.input_schema} for t in tools]

    async def run(prompt: str) -> str:
        messages: list[dict[str, Any]] = [{"role": "user", "content": prompt}]
        while True:
            msg = await model.messages.create(
                model="claude-sonnet-4-6", max_tokens=1024, messages=messages, tools=specs
            )
            messages.append({"role": "assistant", "content": [b.model_dump() for b in msg.content]})
            uses = [b for b in msg.content if b.type == "tool_use"]
            if not uses:
                return "".join(b.text for b in msg.content if b.type == "text")
            results: list[dict[str, Any]] = []
            for u in uses:
                try:
                    out = await by_name[u.name].execute(u.input, ToolContext(call_id=u.id))
                    results.append({"type": "tool_result", "tool_use_id": u.id, "content": json.dumps(out)})
                except WorldError as err:  # a domain error goes to the model; a bug fails the test
                    results.append({"type": "tool_result", "tool_use_id": u.id, "content": str(err), "is_error": True})
            messages.append({"role": "user", "content": results})

    return run


# endregion agent


def refund_script() -> Any:
    """What the model would say. In your project this is a recording of the real model."""
    return script(
        tool_call("lookup_order", order_id="A-1001"),
        tool_call("issue_refund", order_id="A-1001", amount=42.5),
        reply("Sorry about that. Refund R-1001 is on its way."),
        model="claude-sonnet-4-6",
    )


# region test
async def test_refunds_a_damaged_order() -> None:
    model = refund_script()
    w = shop.create()
    agent = support_agent(model.async_anthropic(), w.tools)

    async with trace() as t:
        reply_text = await agent("My order A-1001 arrived damaged.")

    # What changed in the world: one full refund, the order marked refunded, nothing else.
    assert w.changed == ["$.orders['A-1001'].status", "$.refunds['R-1001']"]
    assert w.state["refunds"]["R-1001"] == {"order_id": "A-1001", "amount": 42.5}

    # Guard rules: never delete an account, and stay within a turn and cost budget.
    assert not t.called("delete_account")
    assert len(t.model_calls) <= 4
    assert t.meets({"budget": {"tokens": 2000, "cost_usd": 0.01}})
    assert "R-1001" in reply_text

    # Order matters only where it must: the refund amount comes from the lookup, so the lookup goes first.
    assert t.tool_names == ["lookup_order", "issue_refund"]
    model.assert_consumed()


# endregion test


# region yaml
async def case_agent(case_input: CaseInput) -> str:
    """The agent every YAML case runs. pyproject.toml registers it, and the shop world, for the CLI."""
    return await support_agent(refund_script().async_anthropic(), case_input.worlds["shop"].tools)(case_input.prompt)


def test_yaml_case() -> None:
    cases = load_cases("evals/*.yaml", cwd=Path(__file__).parent)
    # The model is a script, so there is nothing to record: run live.
    report = run_cases(cases, config=resolve_config(agent=case_agent, worlds={"shop": shop}), mode="live")
    assert report["ok"], report["verdicts"]


# endregion yaml

In TypeScript they are four files: the world, the agent, the scripted model, and the test.

src/shop.ts
import { defineWorld, WorldError } from "@viewportai/evals";

type Order = { customer_id: string; status: string; total: number; damaged: boolean };

/**
 * A tiny simulated shop: plain JSON state plus the tools that act on it. The agent calls these tools; the test
 * asserts what they changed. `WorldError` is a domain error the model reads; the change rolls back.
 */
export const shop = defineWorld({
  name: "shop",
  state: {
    customers: { "C-7": { name: "Ines Moreau", email: "[email protected]" } } as Record<string, object>,
    orders: { "A-1001": { customer_id: "C-7", status: "delivered", total: 42.5, damaged: true } } as Record<
      string,
      Order
    >,
    refunds: {} as Record<string, { order_id: string; amount: number }>,
  },
})
  .tool(
    "lookup_order",
    {
      description: "Look up an order by id",
      input_schema: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"] },
    },
    (state, { order_id }) => ({ order_id, ...orderOf(state.orders, order_id) }),
  )
  .tool(
    "issue_refund",
    {
      description: "Refund an order, up to its total",
      input_schema: {
        type: "object",
        properties: { order_id: { type: "string" }, amount: { type: "number" } },
        required: ["order_id", "amount"],
      },
    },
    (state, { order_id, amount }) => {
      const order = orderOf(state.orders, order_id);
      if (amount > order.total) throw new WorldError("invalid_argument", `the order total is ${order.total}`);
      const refund_id = `R-${order_id.slice(2)}`;
      state.refunds[refund_id] = { order_id, amount };
      order.status = "refunded";
      return { refund_id };
    },
  )
  .tool(
    "delete_account",
    {
      description: "Delete a customer account and its order history",
      input_schema: { type: "object", properties: { customer_id: { type: "string" } }, required: ["customer_id"] },
    },
    (state, { customer_id }) => {
      delete state.customers[customer_id];
      return { deleted: customer_id };
    },
  );

function orderOf(orders: Record<string, Order>, id: string): Order {
  const order = orders[id];
  if (!order) throw new WorldError("not_found", `no order ${id}`);
  return order;
}
src/agent.ts
import type Anthropic from "@anthropic-ai/sdk";
import { type Tool, WorldError } from "@viewportai/evals";
import { wrap } from "@viewportai/evals/anthropic";

/** A tool-use loop on the Messages API. `wrap` makes every model call visible to Viewport; world tools record theirs. */
export function supportAgent(client: Anthropic, tools: readonly Tool[]) {
  const model = wrap(client);
  const specs = tools.map(({ name, description, input_schema }) => ({ name, description, input_schema }));
  return {
    async run(prompt: string): Promise<string> {
      const messages: Anthropic.MessageParam[] = [{ role: "user", content: prompt }];
      for (;;) {
        const msg = await model.messages.create({
          model: "claude-sonnet-4-6",
          max_tokens: 1024,
          messages,
          tools: specs as Anthropic.Tool[],
        });
        messages.push({ role: "assistant", content: msg.content });
        const uses = msg.content.filter((b): b is Anthropic.ToolUseBlock => b.type === "tool_use");
        if (uses.length === 0) return msg.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
        const results: Anthropic.ToolResultBlockParam[] = [];
        for (const u of uses) {
          try {
            const out = await tools.find((t) => t.name === u.name)?.execute(u.input, { callId: u.id });
            results.push({ type: "tool_result", tool_use_id: u.id, content: JSON.stringify(out) });
          } catch (err) {
            if (!(err instanceof WorldError)) throw err; // a bug fails the test; a domain error goes to the model
            results.push({ type: "tool_result", tool_use_id: u.id, content: err.message, is_error: true });
          }
        }
        messages.push({ role: "user", content: results });
      }
    },
  };
}
src/model.ts
import { reply, script, toolCall } from "@viewportai/evals/testing";

/** The model's side of "my order arrived damaged": look it up, refund it, tell the customer. */
export const refundScript = () =>
  script(
    toolCall("lookup_order", { order_id: "A-1001" }),
    toolCall("issue_refund", { order_id: "A-1001", amount: 42.5 }),
    reply("I'm sorry about that. Your refund R-1001 for $42.50 is on its way."),
    { model: "claude-sonnet-4-6" },
  );
test/support.test.ts
import "@viewportai/evals/vitest"; // types for the matchers that vitest.config.ts registers
import { trace } from "@viewportai/evals";
import { expect, test } from "vitest";
import { supportAgent } from "../src/agent.js";
import { refundScript } from "../src/model.js";
import { shop } from "../src/shop.js";

test("refunds a damaged order", async () => {
  const model = refundScript();
  const world = shop.create();
  const agent = supportAgent(model.anthropic(), world.tools);

  const t = await trace(() => agent.run("My order A-1001 arrived damaged."));

  // What changed in the world: one full refund, the order marked refunded, nothing else.
  expect(world.changed).toEqual(["$.orders['A-1001'].status", "$.refunds['R-1001']"]);
  expect(world.state.refunds["R-1001"]).toEqual({ order_id: "A-1001", amount: 42.5 });

  // Guard rules: never delete an account, and stay within a turn and cost budget.
  expect(t).not.toHaveCalledTool("delete_account");
  expect(t).toHaveModelCalls({ max: 4 });
  expect(t).toBeWithinBudget({ tokens: 2000, cost_usd: 0.01 });
  expect(t.output).toContain("R-1001");

  // Order matters only where it must: the refund amount comes from the lookup, so the lookup goes first.
  expect(t.toolNames).toEqual(["lookup_order", "issue_refund"]);
  model.assertConsumed();
});

Register the matchers once in vitest.config.ts; the import "@viewportai/evals/vitest" line at the top of the test brings their types. In Python the pytest plugin loads on install, and async def tests run without pytest-asyncio.

vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: { setupFiles: ["@viewportai/evals/vitest"] },
});

t.called(...) raises evals.nothing_captured when the trace captured no model or tool call, so assert not t.called("delete_account") cannot pass just because capture was not set up.

Write the same test as a YAML case

Register the agent once: the function that runs one case. A str -> str callable gets the prompt; otherwise it gets a CaseInput. Register the function itself, not a factory that builds it. Register the world too: a case that declares it under world: gets a fresh instance per run, in worlds["shop"] (Python) or input.worlds.shop (TypeScript). In Python, append this block to your pyproject.toml (case_agent and shop are defined in main.py above):

pyproject.toml
# Registers the quickstart's agent and world for the CLI, so `uv run --project ../../../python viewport-evals run`
# works here. Not a project: the example runs on the package's own environment. In your project this section sits in
# your own pyproject.toml.
[tool.viewport.evals]
agent = "main:case_agent"
worlds = { shop = "main:shop" }

In TypeScript, use viewport.config.ts at the project root:

viewport.config.ts
import { defineConfig } from "@viewportai/evals";
import { supportAgent } from "./src/agent.js";
import { refundScript } from "./src/model.js";
import { shop } from "./src/shop.js";

export default defineConfig({
  evals: {
    // A case that declares `world: { shop: ... }` gets a fresh shop per run, as input.worlds.shop.
    worlds: { shop },
    // Every YAML case under evals/ runs this. A fresh scripted model per case keeps runs independent.
    agent: (input) => supportAgent(refundScript().anthropic(), input.worlds.shop?.tools ?? []).run(input.prompt),
  },
});

Then write cases in evals/. A single-case file's id defaults to its file name. expect.world asserts the end state, invariants and the budgets are the guard rules, and tools.exactly comes last because only that order matters:

evals/refund-happy-path.yaml
# yaml-language-server: $schema=https://getviewport.com/schemas/evals/case/v1.json
description: A damaged order gets refunded in full, and nothing else in the shop changes.
input: "My order A-1001 arrived damaged. I want a refund."
world:
  shop: {}
expect:
  # What changed in the world.
  world:
    shop:
      changed: ["$.orders['A-1001'].status", "$.refunds['R-1001']"]
      state: { refunds: { R-1001: { order_id: A-1001, amount: { lte: 42.5 } } } }
  # Guard rules: a tool it must never call, and a turn and cost budget.
  invariants:
    - name: never delete an account
      never: { tool: delete_account }
  model_calls: { max: 4 }
  budget: { tokens: 2000, cost_usd: 0.01 }
  output: { contains: "R-1001" }
  # Order matters only where it must: the refund amount comes from the lookup.
  tools: { exactly: [lookup_order, issue_refund] }

test_yaml_case in main.py runs the same case from a test with run_cases, which is what the CLI and the pytest plugin do.

Run them. Python (main.py does not match pytest's default test_*.py pattern, so name it; a bare pytest collects only the YAML cases):

uv run pytest main.py              # the two tests in main.py
uv run viewport-evals run          # the YAML cases in evals/

TypeScript:

corepack pnpm exec vitest run          # test/support.test.ts
corepack pnpm exec viewport-evals run  # the YAML cases in evals/; or describeCases("evals/**/*.yaml") in a vitest file

The first local CLI run of a case prints (timings vary):

PASS refund-happy-path  15ms

1 passed (auto) in 0.02s

auto recorded the run to evals/__fixtures__/refund-happy-path.fixture.json. Commit it: under CI=true the same command prints 1 passed (replay) and serves the model from that file.

Record once, replay forever

Recording starts once a real client replaces the script. The scripted model on this page makes no HTTP calls, so a test run of main.py or support.test.ts has nothing to record and passes the same way under CI=true. The CLI still writes a fixture for each YAML case: it holds the run's trajectory, which is what the command above recorded.

You do not choose a mode for everyday work. Locally the default is auto: a test or case with a recording replays it, one without calls the model and records. Under CI=true the default is replay, which serves model calls from the fixture, refuses connections it has no recording for (for the transports listed in replay fails closed), and fails on a missing fixture.

With your real client in place of the script:

uv run pytest main.py                             # first local run records __fixtures__/<test file>/<test>.fixture.json
uv run pytest main.py                             # every run after replays: your code runs, the model does not
uv run pytest main.py --rerecord                  # after an intentional behavior change
corepack pnpm exec viewport-evals run --rerecord  # same for YAML cases from the CLI

Commit the fixtures. A fixture holds the recorded HTTP exchanges (auth headers are never stored) and the trajectory of each run. See modes and fixtures for the details and a runnable record, replay and rescore example.

Gate CI

Run the suite in your pull request workflow with no secrets, in replay: model responses come from the fixtures, a connection with no recording errors the case instead of going live, and the exit code fails the check (what replay enforces). CI selects replay by default; pass --mode replay anyway so the gate does not depend on how your CI system is detected:

uv run viewport-evals run --mode replay --reporter junit=reports/evals.xml
corepack pnpm exec viewport-evals run --mode replay --reporter github --reporter markdown=reports/evals.md

A reporter given =path writes that file. When it is the only reporter, the terminal stays quiet; add --reporter pretty to see the verdicts as well. The exit code fails the check either way.

The CI guide has a complete workflow, including a nightly live run with pass thresholds.

Next: trajectories and traces.

On this page