Worlds
Simulated systems your agent acts on, with tools that change their state and end-state assertions on what changed. Ships with crm, calendar, payments and inbox packs.
An agent that acts needs something to act on. A test that only checks tool arguments cannot tell you whether the refund left the order in the right state, or whether the agent booked over another customer. A world is plain JSON state plus tools that act on it. Your agent calls the tools as it would call the real ones; the test asserts what the agent did to the world.
World tools are Viewport Core tools, so every adapter records them as tool_call events, and each call that changes
the state also records a world_change event under it, with the changed paths and their before and after values.
Define a world
Start from a pack or from scratch (world("name", state=...) in Python, defineWorld({ name, state }) in
TypeScript), and add tools. A tool receives the state and its arguments, changes the state in place and returns
what the model sees. Raise WorldError(code, message) for a domain error the model should see, such as "only 32.00
left to refund". Any other exception rolls the call's changes back and fails the test, because it is a bug in the
tool, not a behavior of the agent.
# The payments pack, plus the two support-facing tools the agent gets. A shop's charge carries its order id in the
# idempotency key, so an order maps to exactly one charge.
shop = payments.extend("shop")
def charge_for(state: dict[str, Any], order_id: str) -> dict[str, Any]:
for charge in state["charges"].values():
if charge["idempotency_key"] == f"order:{order_id}":
return charge
raise WorldError("not_found", f"no order {order_id}")
@shop.tool
def lookup_order(state: dict[str, Any], order_id: str) -> dict[str, Any]:
"""Look up an order: its items, total and what was already refunded. Amounts are in cents."""
c = charge_for(state, order_id)
return {"order_id": order_id, "items": c["description"], "total": c["amount"], "refunded": c["amount_refunded"]}
@shop.tool
def issue_refund(state: dict[str, Any], order_id: str, amount: int, reason: str) -> dict[str, Any]:
"""Refund part or all of an order to the card it was paid with. amount is in cents."""
c = charge_for(state, order_id)
left = c["amount"] - c["amount_refunded"]
if amount > left:
raise WorldError("invalid_argument", f"only {left} cents are left to refund")
refund_id = f"RE-{len(state['refunds']) + 1}"
state["refunds"][refund_id] = {"id": refund_id, "charge_id": c["id"], "amount": amount, "reason": reason}
c["amount_refunded"] += amount
c["status"] = "refunded" if c["amount_refunded"] == c["amount"] else "partially_refunded"
return {"refund_id": refund_id, "amount": amount}
# One customer, one paid order: an 86.00 order whose 54.00 kettle arrived cracked.
SEED = {
"customers": {
"CU-1": {
"id": "CU-1",
"name": "Odile Ferreira",
"email": "[email protected]",
"card": {"brand": "visa", "last4": "4242", "status": "valid"},
}
},
"charges": {
"CH-1": {
"id": "CH-1",
"customer_id": "CU-1",
"amount": 8600,
"currency": "usd",
"description": "Order LT-4810: cast iron kettle 5400, oolong sampler 3200",
"idempotency_key": "order:LT-4810",
"status": "succeeded",
"amount_refunded": 0,
}
},
}// The payments pack, plus the two support-facing tools the agent gets. A shop's charge carries its order id in
// the idempotency key, so an order maps to exactly one charge.
const chargeFor = (state: PaymentsState, orderId: string) => {
const charge = Object.values(state.charges).find((c) => c.idempotency_key === `order:${orderId}`);
if (!charge) throw new WorldError("not_found", `no order ${orderId}`);
return charge;
};
export const shop = payments
.extend({ name: "shop" })
.tool(
"lookup_order",
{
description: "Look up an order: its items, total and what was already refunded. Amounts are in cents.",
input_schema: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"] },
},
(state, { order_id }) => {
const c = chargeFor(state, order_id);
return { order_id, items: c.description, total: c.amount, refunded: c.amount_refunded, status: c.status };
},
)
.tool(
"issue_refund",
{
description: "Refund part or all of an order to the card it was paid with. amount is in cents.",
input_schema: {
type: "object",
properties: {
order_id: { type: "string" },
amount: { type: "integer", minimum: 1 },
reason: { type: "string" },
},
required: ["order_id", "amount", "reason"],
},
},
(state, { order_id, amount, reason }) => {
const c = chargeFor(state, order_id);
const left = c.amount - c.amount_refunded;
if (amount > left) throw new WorldError("invalid_argument", `only ${left} cents are left to refund`);
const id = `RE-${Object.keys(state.refunds).length + 1}`;
state.refunds[id] = { id, charge_id: c.id, amount, reason };
c.amount_refunded += amount;
c.status = c.amount_refunded === c.amount ? "refunded" : "partially_refunded";
return { refund_id: id, amount };
},
);
// One customer, one paid order: an 86.00 order whose 54.00 kettle arrived cracked.
export const seed: Seed<PaymentsState> = {
customers: {
"CU-1": {
id: "CU-1",
name: "Odile Ferreira",
email: "[email protected]",
card: { brand: "visa", last4: "4242", status: "valid" },
},
},
charges: {
"CH-1": {
id: "CH-1",
customer_id: "CU-1",
amount: 8600,
currency: "usd",
description: "Order LT-4810: cast iron kettle 5400, oolong sampler 3200",
idempotency_key: "order:LT-4810",
status: "succeeded",
amount_refunded: 0,
},
},
};create(seed) returns a fresh, isolated instance; the seed deep-merges over the default state (objects merge key by
key, arrays and scalars replace). State must be JSON. Calls on one instance run one at a time, and a call either
applies all its changes or none.
Assert on the end state
An instance exposes state (the current state), changed (the sorted list of paths that changed) and changes
(every change, in order). Paths use core's JSONPath subset and start with $, such as $.refunds['RE-1'].
async def test_refunds_the_cracked_kettle_not_the_whole_order() -> None:
model = refund_script()
world = shop.create(SEED)
async with trace() as t:
t.output = await support_agent(
model.async_anthropic(), world.tools, "My order LT-4810 came with a cracked kettle."
)
# What changed in the world: one refund for the kettle, and the charge is only partly refunded.
assert world.changed == ["$.charges['CH-1'].amount_refunded", "$.charges['CH-1'].status", "$.refunds['RE-1']"]
assert world.state["charges"]["CH-1"]["status"] == "partially_refunded"
assert world.state["refunds"]["RE-1"]["amount"] == 5400
# Guard rules: never charge the customer again, and stay within a turn and cost budget.
assert not t.called("create_charge")
assert len(t.model_calls) <= 4
assert t.meets({"budget": {"tokens": 3000, "cost_usd": 0.02}})
# What it said.
assert "$54.00" in t.output
# Order matters here: the refund amount comes from the lookup, so the lookup must come first.
assert t.tool_names == ["lookup_order", "issue_refund"]
model.assert_consumed()
test("refunds the cracked kettle, not the whole order", async () => {
const model = refundScript();
const world = shop.create(seed);
const t = await trace(() =>
supportAgent(model.anthropic(), world.tools, "My order LT-4810 came with a cracked kettle."),
);
// What changed in the world: one refund for the kettle, and the charge is only partly refunded.
expect(world.changed).toEqual(["$.charges['CH-1'].amount_refunded", "$.charges['CH-1'].status", "$.refunds['RE-1']"]);
expect(world.state.charges["CH-1"]).toMatchObject({ amount_refunded: 5400, status: "partially_refunded" });
expect(world.state.refunds["RE-1"]).toMatchObject({ amount: 5400, reason: expect.stringMatching(/crack/i) });
// Guard rules: never charge the customer again, and stay within a turn and cost budget.
expect(t).not.toHaveCalledTool("create_charge");
expect(t).toHaveModelCalls({ max: 4 });
expect(t).toBeWithinBudget({ tokens: 3000, cost_usd: 0.02 });
// What it said.
expect(t.output).toContain("$54.00");
// Order matters here: the refund amount comes from the lookup, so the lookup must come first.
expect(t.toolNames).toEqual(["lookup_order", "issue_refund"]);
model.assertConsumed();
});Worlds in YAML
Declare worlds under world: in a case or in suite defaults. Each run gets a fresh instance, seeded from the case,
and the agent receives the instances as input.worlds / case_input.worlds. Register your worlds under worlds in
config; the packs resolve by name. expect.world.<name> asserts on the end state:
| Key | Passes when |
|---|---|
state | a matcher over the whole end state passes |
changed | exactly these paths changed (a sorted set, no wildcards) |
only_changed | every change is at or under one of these path patterns (* matches one key or index) |
not_changed | nothing changed at, under or above these patterns; unions across suite defaults |
# yaml-language-server: $schema=https://getviewport.com/schemas/evals/case/v1.json
# Given a shop with one paid order, a customer reports one damaged item. The agent must refund that item only.
id: cracked-kettle
description: A cracked kettle is refunded on its own; the rest of the order stands.
input: "My order LT-4810 came with a cracked kettle."
world:
shop:
seed:
customers:
CU-1:
id: CU-1
name: Odile Ferreira
email: [email protected]
card: { brand: visa, last4: "4242", status: valid }
charges:
CH-1:
id: CH-1
customer_id: CU-1
amount: 8600
currency: usd
description: "Order LT-4810: cast iron kettle 5400, oolong sampler 3200"
idempotency_key: "order:LT-4810"
status: succeeded
amount_refunded: 0
expect:
# What changed in the world: one refund for the kettle; the rest of the order stands.
world:
shop:
changed: ["$.charges['CH-1'].amount_refunded", "$.charges['CH-1'].status", "$.refunds['RE-1']"]
state:
charges: { CH-1: { amount_refunded: 5400, status: partially_refunded } }
refunds: { RE-1: { amount: { lte: 5400 }, reason: { icontains: crack } } }
# Guard rules: never charge the customer again, and stay within a turn and cost budget.
invariants:
- name: never charge again
never: { tool: create_charge }
model_calls: { max: 4 }
budget: { tokens: 3000, cost_usd: 0.02 }
output: { contains: "$54.00" }
# Order matters here: the refund amount comes from the lookup, so the lookup must come first.
tools: { exactly: [lookup_order, issue_refund] }
def test_yaml_case() -> None:
"""The same expectations as evals/refunds.yaml. The runner makes a fresh ``shop`` per run from the case's seed and
hands it to the agent as ``case_input.worlds["shop"]``."""
async def agent(case_input: CaseInput) -> str:
tools = case_input.worlds["shop"].tools
return await support_agent(refund_script().async_anthropic(), tools, case_input.prompt)
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=agent, worlds={"shop": shop}), mode="live")
assert report["ok"], report["verdicts"]
// The same expectations as a YAML case (evals/refunds.yaml). The runner makes a fresh `shop` per run from the
// case's seed and hands it to the agent as `input.worlds.shop`. The model is a script, so there is nothing to
// record: run live.
describeCases("evals/*.yaml", {
cwd: import.meta.dirname,
mode: "live",
config: {
worlds: { shop },
agent: (input) => supportAgent(refundScript().anthropic(), input.worlds.shop?.tools ?? [], input.prompt),
},
});Packs
viewportai.evals.worlds and @viewportai/evals/worlds ship four worlds with the same state shape and tool
semantics in both languages. Extend one with your own tools, as the support example does with payments.
| Pack | State | Tools |
|---|---|---|
crm | contacts, deals | find_contacts, get_contact, create_contact, update_contact, add_note, create_deal, update_deal |
calendar | events | list_events, find_free_slots, create_event, reschedule_event, cancel_event |
payments | customers, charges, refunds | get_customer, list_charges, create_charge, refund_charge |
inbox | address, messages | search_emails, read_email, send_email, archive_email, label_email |
The packs behave like the systems they stand in for: confirmed calendar events may not overlap; create_charge is
idempotent on its key and reports a conflict when the key is reused with other parameters; contact emails are
unique. payments ships one invariant, "one charge per idempotency key", added to every case that
uses it. Amounts are integers in cents.
Next: simulated time.
Invariants
Rules over a whole run, such as approval before any send or one charge per booking, checked over every event and shared with Viewport HITL.
Simulated time
Run reminders, waits, scheduled jobs and multi-day conversations in milliseconds on a simulated clock, in code and as multi-episode YAML cases.