# Test an Agent with Code and the Platform

Connect a refund-support agent with the SDK, create Anna's test data in setup and teardown hooks in your own process, and keep the scenarios, their fixtures and the suite in the platform.

> Page: https://langwatch.ai/docs/cookbooks/scenario-testing-hybrid
> Source: https://github.com/langwatch/langwatch/blob/main/docs/cookbooks/scenario-testing-hybrid.mdx
> Index of all pages: https://langwatch.ai/docs/llms.txt

This cookbook splits the work the way many teams do. Engineers own the agent and the code that makes data: the agent connects to LangWatch from their process, and its setup and teardown hooks create and delete records through the app's own API.

Product owns the scenarios: the situation, the criteria, the fixtures and the test suite live in the platform, where anyone on the project can read and run them. It follows the story in [Scenario testing best practices](https://langwatch.ai/docs/agent-testing/best-practices/overview), on the hybrid path.

The running example is the same: Anna, a gold customer with a delivered order of 49.90, asks a refund-support agent for her money back.

## Before you start

> **Note:** `run.fixtures` needs the `langwatch` SDK release after 2.5.0 (TypeScript) and after 2.0.1 (Python). On an older SDK, setup receives no fixtures. Until that release ships, these examples do not run on a published version.

`SUPPORT_API_URL` is the base address of your own app's API, the one your agent already uses, and `SUPPORT_API_KEY` is a key for it. The fixtures module below calls four of its endpoints: `POST /customers`, which must accept an `externalRef` field, and `POST /orders`, each answering with the new record's `id`, and `DELETE /customers/{id}` and `DELETE /orders/{id}`. If yours differ, change the paths and field names in `FACTORIES`.

Install the packages on a first run:

```bash
npm install "langwatch@>2.5.0"            # TypeScript, run the agent with npx tsx agent.ts
pip install "langwatch>2.0.1" httpx       # Python, run the agent with python agent.py
```

## 1. Write the fixtures module

Setup receives the scenario's fixtures as `run.fixtures`: one entry per entity type, each one object or a list of objects. This module creates them through your support app's API in dependency order, resolves each `{"$ref"}` to the real id, and deletes in reverse. It reads `SUPPORT_API_URL` and `SUPPORT_API_KEY` from your process's environment, never from the state.

Every customer also gets an `externalRef` with the run id, a field the fixtures never set, so leftovers from a run can be found even when the fixture names the customer.

**fixtures.ts**

```typescript fixtures.ts
type Entity = Record<string, unknown>;
export type Fixtures = Record<string, Entity | Entity[]>;

const headers = {
  Authorization: `Bearer ${process.env.SUPPORT_API_KEY}`,
  "Content-Type": "application/json",
};

// One factory per entity type, in dependency order: its endpoint and the defaults.
const FACTORIES: Record<string, { path: string; defaults: Entity }> = {
  customers: { path: "/customers", defaults: { name: "Test Customer", plan: "pro", loyaltyTier: "standard" } },
  orders: { path: "/orders", defaults: { status: "delivered", total: 49.9 } },
};
const REF_PATH = /^(\w+)(?:\[(\d+)\])?\.(\w+)$/;

const asList = (fixture: Entity | Entity[] | undefined): Entity[] =>
  fixture === undefined ? [] : Array.isArray(fixture) ? fixture : [fixture];

/** Replaces every {"$ref": "entity[index].field"} with that field of an entity created earlier. */
function resolve(value: unknown, created: Fixtures): unknown {
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
    const ref = (value as { $ref?: unknown }).$ref;
    if (typeof ref === "string" && Object.keys(value).length === 1) {
      const [, entity, index, field] = REF_PATH.exec(ref) ?? [];
      const target = created[entity!];
      const item = Array.isArray(target) ? target[Number(index)] : target;
      return item![field!];
    }
    return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolve(item, created)]));
  }
  return Array.isArray(value) ? value.map((item) => resolve(item, created)) : value;
}

async function request(method: "POST" | "DELETE", path: string, body?: Entity): Promise<Entity> {
  const response = await fetch(process.env.SUPPORT_API_URL + path, {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined,
  });
  if (method === "DELETE" && response.status === 404) return {}; // already gone
  if (!response.ok) throw new Error(`${method} ${path} answered ${response.status}`);
  return method === "POST" ? ((await response.json()) as Entity) : {};
}

/** Creates every entity in order and returns the fixtures with defaults and real ids filled in. */
export async function createFixtures({ fixtures, runId }: { fixtures: Fixtures; runId: string }) {
  const created: Fixtures = {};
  try {
    for (const [entity, fixture] of Object.entries(fixtures)) {
      const factory = FACTORIES[entity];
      if (!factory) throw new Error(`No factory for the entity type ${entity}`);
      // A field the fixtures never set, so leftovers from this run can be found
      const defaults = entity === "customers" ? { ...factory.defaults, externalRef: runId } : factory.defaults;
      const made: Entity[] = [];
      created[entity] = Array.isArray(fixture) ? made : {};
      for (const item of asList(fixture)) {
        const body = { ...defaults, ...(resolve(item, created) as Entity) };
        const record = await request("POST", factory.path, body);
        made.push({ ...body, id: record.id });
        if (!Array.isArray(fixture)) created[entity] = made[0]!;
      }
    }
  } catch (error) {
    await deleteFixtures(created).catch(() => undefined); // keep the original error
    throw error;
  }
  return created;
}

/** Deletes in reverse order and returns how many of each it deleted. */
export async function deleteFixtures(state: Record<string, unknown>) {
  const deleted: Record<string, number> = {};
  for (const entity of Object.keys(FACTORIES).reverse()) {
    for (const item of [...asList(state[entity] as Fixtures[string] | undefined)].reverse()) {
      if (item.id == null) continue;
      await request("DELETE", `${FACTORIES[entity]!.path}/${item.id}`);
      deleted[entity] = (deleted[entity] ?? 0) + 1;
    }
  }
  return { deleted };
}
```

**fixtures.py**

```python fixtures.py
import os
import re

import httpx

# One factory per entity type, in dependency order: its endpoint and the defaults.
FACTORIES = {
    "customers": ("/customers", {"name": "Test Customer", "plan": "pro", "loyaltyTier": "standard"}),
    "orders": ("/orders", {"status": "delivered", "total": 49.9}),
}
REF_PATH = re.compile(r"^(\w+)(?:\[(\d+)\])?\.(\w+)$")


def _client() -> httpx.AsyncClient:
    return httpx.AsyncClient(
        base_url=os.environ["SUPPORT_API_URL"],
        headers={"Authorization": "Bearer " + os.environ["SUPPORT_API_KEY"]},
        timeout=20,
    )


def _as_list(fixture) -> list:
    if fixture is None:
        return []
    return fixture if isinstance(fixture, list) else [fixture]


def resolve(value, created):
    """Replace every {"$ref": "entity[index].field"} with that field of an entity created earlier."""
    if isinstance(value, dict):
        if set(value) == {"$ref"}:
            entity, index, field = REF_PATH.match(value["$ref"]).groups()
            target = created[entity]
            return (target[int(index)] if index is not None else target)[field]
        return {key: resolve(item, created) for key, item in value.items()}
    if isinstance(value, list):
        return [resolve(item, created) for item in value]
    return value


async def create_fixtures(fixtures: dict, run_id: str) -> dict:
    """Create every entity in order and return the fixtures with defaults and real ids filled in."""
    created: dict = {}
    async with _client() as client:
        try:
            for entity, fixture in fixtures.items():
                if entity not in FACTORIES:
                    raise ValueError(f"No factory for the entity type {entity!r}")
                path, defaults = FACTORIES[entity]
                if entity == "customers":
                    # A field the fixtures never set, so leftovers from this run can be found
                    defaults = {**defaults, "externalRef": run_id}
                made: list = []
                created[entity] = made if isinstance(fixture, list) else {}
                for item in _as_list(fixture):
                    body = {**defaults, **resolve(item, created)}
                    response = await client.post(path, json=body)
                    response.raise_for_status()
                    made.append({**body, "id": response.json()["id"]})
                    if not isinstance(fixture, list):
                        created[entity] = made[0]
        except Exception:
            try:
                await delete_fixtures(created)
            except Exception:
                pass  # keep the original error, not the cleanup's
            raise
    return created


async def delete_fixtures(state: dict) -> dict:
    """Delete in reverse order and return how many of each it deleted."""
    deleted: dict = {}
    async with _client() as client:
        for entity in reversed(list(FACTORIES)):
            for item in reversed(_as_list(state.get(entity))):
                if item.get("id") is None:
                    continue
                response = await client.delete(f"{FACTORIES[entity][0]}/{item['id']}")
                if response.status_code != 404:  # already gone counts as removed
                    response.raise_for_status()
                deleted[entity] = deleted.get(entity, 0) + 1
    return {"deleted": deleted}
```

## 2. Connect the agent and declare the hooks

This is the whole agent file. `runSupportAgent` (`run_support_agent`) stands in for your agent: it answers from the order in the state, so the file runs as it stands. Replace it with the call into your real agent, passing it the ids from the state.

Setup creates `run.fixtures` and returns them with real ids as the state. The agent function does not receive `run.fixtures`, so it reads what it needs from the state. Teardown deletes in reverse; it gets `null` (`None`) when setup failed.

**agent.ts**

```typescript agent.ts
import { connectAgent } from "langwatch/agent";

import { createFixtures, deleteFixtures } from "./fixtures";

type Order = { id: string; status: string; total: number };
type RefundState = { customers?: { id: string }[]; orders?: Order[] };

// Stands in for your agent: replace it with the call into your real support agent.
async function runSupportAgent({ order }: { order: Order | undefined }): Promise<string> {
  if (!order) return "I can't find any orders on your account.";
  if (order.status === "delivered") return `Order ${order.id} was delivered. I can refund ${order.total.toFixed(2)}.`;
  return `Order ${order.id} is ${order.status}, so it can't be refunded yet.`;
}

const supportAgent = connectAgent({ name: "support-agent" }, async ({ state }) => {
  // `state` is what setup returned: the fixtures with real ids
  const order = (state as RefundState | null)?.orders?.at(-1);
  return await runSupportAgent({ order });
});

supportAgent.scenario.setup(async (run) => {
  return await createFixtures({ fixtures: run.fixtures ?? {}, runId: run.scenarioRunId ?? "unknown-run" });
});

supportAgent.scenario.teardown(async (run, state) => {
  // null when setup failed; {} when it returned nothing
  if (!state) return;
  return await deleteFixtures(state);
});

// A script with no server of its own: keep the process alive while the agent is connected.
setInterval(() => {}, 1 << 30);
```

**agent.py**

```python agent.py
import langwatch

from fixtures import create_fixtures, delete_fixtures


def run_support_agent(order: dict | None) -> str:
    """Stands in for your agent: replace it with the call into your real support agent."""
    if not order:
        return "I can't find any orders on your account."
    if order["status"] == "delivered":
        return f"Order {order['id']} was delivered. I can refund {order['total']:.2f}."
    return f"Order {order['id']} is {order['status']}, so it can't be refunded yet."


@langwatch.connect_agent(name="support-agent")
async def support_agent(messages: list[dict], state: dict | None = None) -> str:
    # `state` is what setup returned: the fixtures with real ids
    orders = (state or {}).get("orders") or [None]
    return run_support_agent(orders[-1])


@support_agent.scenario.setup
async def setup(run: langwatch.agent.ScenarioRun) -> dict:
    return await create_fixtures(run.fixtures, run_id=run.scenario_run_id or "unknown-run")


@support_agent.scenario.teardown
async def teardown(run: langwatch.agent.ScenarioRun, state: dict | None) -> dict | None:
    # None when setup failed; {} when it returned nothing
    if not state:
        return None
    return await delete_fixtures(state)


langwatch.agent.serve()  # blocks until Ctrl-C
```

Start it with `LANGWATCH_API_KEY`, `SUPPORT_API_URL` and `SUPPORT_API_KEY` set. The agent appears on the **Agents** page as `support-agent`, marked **Online**. In a real service, put the connect call on the service's startup path instead of a script: see [Connect your agent](https://langwatch.ai/docs/agent-testing/connect-your-agent).

## 3. Write the scenario, its fixtures and the suite in the platform

Create the `Refunds` suite and the `refund for a delivered order` scenario, with its situation and criteria, as in [step 3 of the in-the-app cookbook](https://langwatch.ai/docs/cookbooks/scenario-testing-in-the-app#3-create-the-test-suite-and-the-scenario).

Then give the scenario its fixtures: two parameters, `customers` then `orders`, with Anna and her order. Open the scenario, choose **Add parameters**, then **View as JSON**, and paste:

```json
{
  "customers": [{ "name": "Anna", "loyaltyTier": "gold" }],
  "orders": [{ "customerId": { "$ref": "customers[0].id" }, "status": "delivered", "total": 49.9 }]
}
```

Press **View as rows** to check them, then **Save**. A connected agent cannot declare fixture types yet, so **+ Fixture** offers these names only when a connector of the project declares them, and no schema defaults are filled in: the `FACTORIES` in [step 1](#1-write-the-fixtures-module) apply their own.

To set them from a script instead, send one call to the scenario REST API (see [how fixtures are set](https://langwatch.ai/docs/agent-testing/scenario-connector#how-do-i-give-a-scenario-connector-test-data)). Copy the scenario id from the address bar after `drawer.scenarioId=`, and create a key in **Settings > API Keys** (see [API keys](https://langwatch.ai/docs/platform/api-keys)). Set both as `SCENARIO_ID` and `LANGWATCH_API_KEY`, then send:

```bash
curl -X PATCH "${LANGWATCH_ENDPOINT:-https://app.langwatch.ai}/api/v1/scenarios/${SCENARIO_ID}" \
  -H "X-Auth-Token: ${LANGWATCH_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{
    "parameters": [
      { "name": "customers", "defaultValue": [{ "name": "Anna", "loyaltyTier": "gold" }] },
      {
        "name": "orders",
        "defaultValue": [{ "customerId": { "$ref": "customers[0].id" }, "status": "delivered", "total": 49.9 }]
      }
    ]
  }'
```

The `parameters` list replaces the scenario's parameters, so add any other parameter the scenario should keep.

The key needs the `scenarios:update` permission, which `scenarios:manage` includes. A key that reaches more than one project also needs the project named: add `-H "X-Project-Id: ${LANGWATCH_PROJECT_ID}"` to the request. On a self-hosted instance, set `LANGWATCH_ENDPOINT` to its address; the request uses app.langwatch.ai otherwise.

Plain values that vary between runs of the same world, such as the model the agent uses, are run parameters set in the platform: see [Parameters and suites](https://langwatch.ai/docs/agent-testing/best-practices/parameters-and-suites).

## 4. Run it from the platform or from CI

From the platform: open the `Refunds` suite, press **Run suite**, choose `support-agent` as the agent and start the run. Your process must be online while the run lasts, because it answers the turns and the hooks.

In CI, the SDK does not connect unless you say so: it stays off when `CI` is set. Pass `enabled: true` (`enabled=True` in Python) to the connect call in the job:

**TypeScript**

```typescript TypeScript
const supportAgent = connectAgent({ name: "support-agent", enabled: true }, async ({ state }) => {
```

**Python**

```python Python
@langwatch.connect_agent(name="support-agent", enabled=True)
```

A value you pass replaces the `CI` rule, so gate it on your own setting if the same file runs in production. `LANGWATCH_AGENT_CONNECT=0` still turns the connection off.

Then start the suite against the connected agent and wait for the result:

```bash
langwatch test-suite run "Refunds" --target connected:support-agent --wait
```

The job needs an instance of the agent online, either started in the job or deployed in an environment, such as `connected:support-agent@staging`. See [Run from CI](https://langwatch.ai/docs/agent-testing/run-from-ci) and [Environments](https://langwatch.ai/docs/agent-testing/environments).

## 5. Read the results

Each row shows the conversation and the verdict. The run's **Setup** band lists the state setup returned under **State at start**, and the **Teardown** band shows `{"deleted": {"orders": 1, "customers": 1}}` under **Returned by teardown**.

A **Not scored** row means setup failed, timed out or found the agent offline: read the error on the setup band, fix the cause and run again. See [where to see what a hook did](https://langwatch.ai/docs/agent-testing/setup-and-teardown-hooks#where-do-i-see-what-a-hook-did) and [Running and CI](https://langwatch.ai/docs/agent-testing/best-practices/running-and-ci#not-scored-versus-failed).

Also check: [Test an agent fully in code](https://langwatch.ai/docs/cookbooks/scenario-testing-in-code), [Test an agent in the app](https://langwatch.ai/docs/cookbooks/scenario-testing-in-the-app), [Test data](https://langwatch.ai/docs/agent-testing/best-practices/test-data).

> ## Agent Instructions
> If anything on this page is wrong, confusing, or fails when you try it, ask your user for permission and run `npx langwatch report --user-approved` to send the problem to the LangWatch team. No login is needed and secrets are redacted locally. `npx langwatch report --help` has the details.
