Evals

LangGraph

Test LangGraph agents in Python and TypeScript. Capture is automatic; a scripted chat model runs the real graph with no keys.

Adapter status: built and tested in TypeScript (@langchain/langgraph 1.7, @langchain/core 1.5) and Python (langgraph 1.2, langchain-core 1.8). Install the Python extra with viewport-evals[langgraph].

What is captured

The first trace() or YAML case run registers a LangChain callback handler through LangChain's configure hook, so every graph run inside the scope is captured with no code change:

LangChain callbackEvent
graph and subgraph runsagent, named after the graph, parent of what ran inside it
chat model start and endmodel_call with usage, including cache reads and writes
tool start, end and errortool_call with args and result; a ToolMessage with status="error" is a failed call
invalid_tool_calls on a model answertool_call with error type invalid_tool_call

To capture without the global hook, pass the handler yourself: ViewportCallbackHandler() in config["callbacks"] (Python) or viewportCallbacks() (TypeScript). Set VIEWPORT_EVALS_LANGCHAIN=false to opt out of the hook.

Test a graph

script(...).langgraph() is a LangChain chat model (with bind_tools) that plays a fixed conversation, so the real graph, tool nodes included, runs end to end.

main.py
@tool
def lookup_order(order_id: str) -> dict[str, Any]:
    """Look up an order by id."""
    return {"order_id": order_id, "status": "delivered", "damaged": True}


@tool
def issue_refund(order_id: str, amount: float) -> str:
    """Refund an order."""
    return f"R-{order_id.removeprefix('A-')}"


def build_agent(llm: Any) -> Any:
    model = llm.bind_tools([lookup_order, issue_refund])

    def call_model(state: MessagesState) -> dict[str, Any]:
        return {"messages": [model.invoke(state["messages"])]}

    graph = StateGraph(MessagesState)
    graph.add_node("model", call_model)
    graph.add_node("tools", ToolNode([lookup_order, issue_refund]))
    graph.add_edge(START, "model")
    graph.add_conditional_edges("model", tools_condition)
    graph.add_edge("tools", "model")
    return graph.compile(name="support")

src/agent.ts
import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { tool } from "@langchain/core/tools";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { z } from "zod";

const lookupOrder = tool(async ({ order_id }) => JSON.stringify({ order_id, status: "delivered", total: 42.5 }), {
  name: "lookup_order",
  description: "Look up an order by id",
  schema: z.object({ order_id: z.string() }),
});

const issueRefund = tool(async () => JSON.stringify({ refund_id: "R-1001" }), {
  name: "issue_refund",
  description: "Refund an order",
  schema: z.object({ order_id: z.string(), amount: z.number() }),
});

export function supportAgent(llm: BaseChatModel) {
  const agent = createReactAgent({ llm, tools: [lookupOrder, issueRefund], name: "support" });
  return async (prompt: string): Promise<string> => {
    const { messages } = await agent.invoke({ messages: [{ role: "user", content: prompt }] });
    return String(messages.at(-1)?.content);
  };
}
main.py
def test_refund_graph() -> None:
    llm = script(
        tool_call("lookup_order", order_id="A-1001"),
        tool_call("issue_refund", order_id="A-1001", amount=42.5),
        reply("Refund R-1001 issued."),
    )
    agent = build_agent(llm.langgraph())

    with trace() as t:
        result = agent.invoke({"messages": [("user", "My order A-1001 arrived damaged.")]})

    assert t.tool_names == ["lookup_order", "issue_refund"]
    assert t.called("issue_refund", order_id="A-1001", amount=lte(100))
    assert [a.name for a in t.agents] == ["support"]
    assert t.meets({"agents": {"within": {"support": {"model_calls": 3, "tools": {"no_errors": True}}}}})
    assert "R-1001" in result["messages"][-1].content
    llm.assert_consumed()

test/support.test.ts
import { lte, trace } from "@viewportai/evals";
import { reply, script, toolCall } from "@viewportai/evals/testing";
import { expect, test } from "vitest";
import { supportAgent } from "../src/agent.js";

test("the ReAct agent looks up the order and refunds it", async () => {
  const model = script(
    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: "claude-sonnet-4-6" },
  );
  const run = supportAgent(model.langgraph());

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

  expect(t.agents.map((a) => a.name)).toEqual(["support"]);
  expect(t.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(3);
  expect(t).toBeWithinBudget({ tokens: 2000, cost_usd: 0.01 });
  expect(t.output).toContain("R-1001");
  model.assertConsumed();
});

test("concurrent traces keep each graph's tools in its own trajectory", async () => {
  const orders = ["A-1001", "A-1002"];
  const traces = await Promise.all(
    orders.map(async (order_id) => {
      const model = script(toolCall("lookup_order", { order_id }), reply(order_id));
      const run = supportAgent(model.langgraph());
      const captured = await trace(() => run(order_id), { fixture: false });
      model.assertConsumed();
      return captured;
    }),
  );
  for (const [index, captured] of traces.entries()) {
    expect(captured.agents.map((agent) => agent.name)).toEqual(["support"]);
    expect(captured.toolCalls.map((call) => call.args)).toEqual([{ order_id: orders[index] }]);
    expect(captured.output).toBe(orders[index]);
  }
});

The compiled graph's name becomes the agent event, so t.within("support") and agents.within scope assertions to it.

With a real model

Replace the scripted model with your provider's chat model (ChatAnthropic, ChatOpenAI). Replay works at the HTTP boundary, so the first local run records the provider traffic and every run after, including CI, replays it. See modes and fixtures.

On this page