Evals

Production replay

Turn a Langfuse, LangSmith or Braintrust trace into a regression test with one command, replay a new agent version against the trace's real tool responses, and assert the behavior diff.

Your observability platform already holds the runs that matter: the refund that went right, the escalation that went wrong. Trace-to-test turns one of them into a case. The new version of your agent then runs against the tool responses production actually returned, and the case asserts how its behavior differs from production.

Import a trace

uv run viewport-evals import langfuse:<trace id> --case refund-from-prod --tag golden
pnpm exec viewport-evals import langfuse-export.json --case refund-from-prod --tag golden

Sources are langfuse:<trace id>, langsmith:<trace id> and braintrust:<root span id> (fetched with each platform's API keys from the environment; see the CLI reference), or a file or directory: OTLP JSON, a Langfuse, LangSmith or Braintrust export, trajectory JSON or JSONL segments, or trajectory store records. Segments of one run are stitched by episode. A value is replaced with [REDACTED] when its key, split on -, _, spaces and camelCase boundaries, has a segment secret, password, passwd, pwd, token, credential(s), cookie, authorization or auth (db_password, X-Auth-Token, auth_header), or contains api_key, private_key, client_secret, access_key or secret_key with or without separators (clientSecret, APIKey). Words that only contain one stay readable: author, session_id, input_tokens. The credential shapes fixtures mask are masked in every other string. A secret under any other key in any other shape is imported as it is: add exact key names with --redact.

import writes a fixture whose run is the trace (source: imported) and, for a new case, a case file with ~ placeholders. Run run --mode rescore --accept to fill them from the trace, review the diff, and commit both. --sample N picks N traces and writes one case each, which turns a production sample into a golden set.

main.py
# One command turned the production trace into this test (run it from this directory):
#
#   uv run viewport-evals import langfuse-export.json --case refund-from-prod --tag golden
#   uv run viewport-evals run --mode rescore --accept     # fill the ~ placeholders from the trace, then review
#
# It wrote evals/refund-from-prod.yaml (prompt, replay: {tools: recorded}, expect.baseline) and its fixture, whose
# run is the trace (source: imported). Online, ``import langfuse:<trace id>`` fetches it with your keys.
main.ts
// One command turned the production trace into this test (run it from this directory):
//
//   npx @viewportai/evals import langfuse-export.json --case refund-from-prod --tag golden
//   npx @viewportai/evals run --mode rescore --accept    # fill the ~ placeholders from the trace, then review
//
// It wrote evals/refund-from-prod.yaml (prompt, replay: { tools: recorded }, expect.baseline) and its fixture,
// whose run is the trace (source: imported). Online, `import langfuse:<trace id>` fetches it with your keys.

The imported case:

evals/refund-from-prod.yaml
# Imported from langfuse-export.json (trace 6f1c2a9e-4b7d-4e21-9a0c-3d5e8f7a1b42) by viewport-evals import.
# Review it, run `viewport-evals run --accept` to fill the ~ placeholders, then commit the case and fixture.
id: "refund-from-prod"
description: "Imported langfuse trace 6f1c2a9e-4b7d-4e21-9a0c-3d5e8f7a1b42."
tags: [ "imported", "golden" ]
input: "Order LT-4810 came with a cracked kettle. Can you refund it?"
replay:
  tools: recorded
expect:
  tools:
    exactly: [ lookup_order, issue_refund ]
  model_calls: 3
  budget:
    tokens: 5541
    cost_usd: 0.0093
  baseline:
    tools: same
    cost_usd:
      max_increase: "20%"

Serve tools from the trace

A production trace has no HTTP exchanges to replay, and your tools call systems a test cannot reach. With replay: { tools: recorded }, tool calls are served from the trace instead: matched by tool name plus canonical arguments, in recorded order, each recorded call serving once. Model calls are not in the trace, so the first local run records them like any other run, and CI replays that recording.

Secret arguments are recorded masked: core writes a value the tool's input schema marks writeOnly: true (pydantic SecretStr and SecretBytes emit that) as [redacted hmac:<12 hex>], and import keeps that marker as it is. When matching, a recorded marker matches any present live value at that position, and every other argument must still be equal. Comparing masked to masked is not reliable: the HMAC key is random per process unless VIEWPORT_REDACT_KEY is set, and it is derived per tenant. So two calls that differ only in a secret argument are served in recorded order. Core supports a stable key: set the same VIEWPORT_REDACT_KEY when recording and the markers for one secret stay identical across runs (fixtures diff cleanly), but replay still matches them as wildcards.

Every tool that runs through core's tool recording is served: @tool / defineTool, wrap_tool / wrapTool, world tools, and the framework tools adapters wrap. Core asks the replay where the tool body would run, after argument validation and inside every middleware, so HITL gates still decide first; a served call records as an ordinary tool_call with the span attribute viewport.tool.served. Your tools need no changes, and outside a replaying run they execute as usual. In code, RecordedTools(trajectory) is the same replay: pass its serve to core's tool_server / withToolServer.

main.py
# The real tools call production systems that tests cannot reach. They are ordinary core tools: a
# ``replay: {tools: recorded}`` run serves them from the imported trace; outside one they execute as usual.
@tool
async def lookup_order(order_id: str) -> dict[str, Any]:
    """Look up an order: its items, total and refunds. Amounts are in cents."""
    raise ConnectionError("orders-api is not reachable outside production")


@tool
async def issue_refund(order_id: str, amount: int, reason: str) -> dict[str, Any]:
    """Refund part or all of an order to the original card. amount is in cents."""
    raise ConnectionError("payments-api is not reachable outside production")


TOOLS = [lookup_order, issue_refund]
main.ts
// The real tools call production systems that tests cannot reach. They are ordinary core tools: a
// `replay: { tools: recorded }` run serves them from the imported trace; outside one they execute as usual.
const unreachable = (system: string) => {
  throw new Error(`${system} is not reachable outside production`);
};

export const tools = [
  defineTool({
    name: "lookup_order",
    description: "Look up an order: its items, total and refunds. Amounts are in cents.",
    input_schema: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"] },
    execute: async () => unreachable("orders-api"),
  }),
  defineTool({
    name: "issue_refund",
    description: "Refund part or all of an order to the original card. amount is in cents.",
    input_schema: {
      type: "object",
      properties: { order_id: { type: "string" }, amount: { type: "integer" }, reason: { type: "string" } },
      required: ["order_id", "amount", "reason"],
    },
    execute: async () => unreachable("payments-api"),
  }),
] as const;

on_miss decides what happens to a call the trace never made: error (the default) fails the call with evals.replay_tool_miss, world runs the call when a declared world has a tool of that name, and live runs the real tool.

main.py
def test_imported_case_against_the_new_version() -> None:
    """Tool calls are served from the trace; expect.baseline checks the behavior diff against production (same tools
    and arguments, cost within 20%)."""

    async def agent(case_input: CaseInput) -> str:
        return await ask(new_version().langgraph(), case_input.prompt)

    cases = load_cases("evals/*.yaml", cwd=HERE)
    report = run_cases(cases, config=resolve_config(agent=agent), mode="live")
    assert report["ok"], report["verdicts"]

main.ts
// The imported case runs the new version: tool calls are served from the trace, and expect.baseline checks the
// behavior diff against production (same tools and arguments, cost within 20%).
describeCases("evals/*.yaml", {
  cwd: import.meta.dirname,
  mode: "live",
  config: { agent: (input) => supportAgent(newVersion().langgraph())(input.prompt) },
});

Diff behavior against the baseline

A trajectory diff aligns two runs' tool calls (longest common subsequence, ties broken by equal arguments) and reports each step as same, added, removed or changed with argument diffs, plus the output and the model call, token, cost and latency deltas, and new invariant violations.

  • In a case, expect.baseline asserts on the diff against the imported trace: tools: same (same tools and arguments), output: <matcher> (reported next to the baseline's output; a judge checks the meaning still holds), and cost_usd: { max_increase: "20%" } (a percentage or US dollars).
  • In code, t.diff(baseline), or trajectory_diff(a, b) / trajectoryDiff(a, b) with format_diff / formatDiff for text.
  • From the command line, viewport-evals diff <baseline> <candidate> compares fixtures, reports, trajectory files or import sources; --against imported uses the imported trace, --json prints evals/trajectory_diff/v1, and --fail-on-change exits 1 when anything changed.
main.py
def test_diff_catches_a_regression() -> None:
    [prod] = import_traces("langfuse-export.json", cwd=HERE)
    baseline = prod["trajectory"]
    recorded = RecordedTools(baseline)  # serve tool calls from the trace; anything else fails the call
    llm = regressed_version()

    with trace() as t, tool_server(recorded.serve):
        asyncio.run(ask(llm.langgraph(), "My kettle arrived cracked."))

    d = t.diff(baseline)
    assert [(s["op"], s["tool"]) for s in d["steps"]] == [("removed", "lookup_order"), ("changed", "issue_refund")]
    assert d["steps"][1].get("args") == [
        {"op": "replace", "path": "$.amount", "before": 5400, "after": 8600},
        {"op": "replace", "path": "$.reason", "before": "Kettle arrived cracked", "after": "Damaged order"},
    ]
    # The full refund was never in production, so the replay refused it instead of reaching payments.
    assert [m.tool_name for m in recorded.misses] == ["issue_refund"]
    llm.assert_consumed()

main.ts
test("t.diff(baseline) catches a regression against production", async () => {
  const [prod] = await importTraces("langfuse-export.json", { cwd: import.meta.dirname });
  const baseline = prod?.trajectory ?? { events: [] };
  const recorded = new RecordedTools(baseline); // serve tool calls from the trace; anything else fails the call
  const model = regressedVersion();

  const t = await trace(() =>
    withToolServer(recorded.serve, () => supportAgent(model.langgraph())("My kettle arrived cracked.")),
  );

  const d = t.diff(baseline);
  expect(d.steps.map((s) => [s.op, s.tool])).toEqual([
    ["removed", "lookup_order"],
    ["changed", "issue_refund"],
  ]);
  expect(d.steps[1]?.args).toEqual([
    { op: "replace", path: "$.amount", before: 5400, after: 8600 },
    { op: "replace", path: "$.reason", before: "Kettle arrived cracked", after: "Damaged order" },
  ]);
  // The full refund was never in production, so the replay refused it instead of reaching payments.
  expect(recorded.misses.map((m) => m.tool_name)).toEqual(["issue_refund"]);
  model.assertConsumed();
});

Next: results and the viewer.

On this page