> ## Documentation Index
> Fetch the complete documentation index at: https://laminar.sh/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Write an Agent Evaluation Runner in eval.py

Each [agent evaluation](https://laminar.sh/docs/agent-evaluations/introduction.md) dataset has one `agent/eval.py` file. It holds one `EvalRunner` subclass from `lmnr.evals`, in Laminar's Python SDK. The runner's attributes declare the image, the services, and the secrets. Its methods set up each case, run your app, and grade the result. Your app can be in any language. Only the runner is Python.

This page covers the runner's attributes, its methods, and the `ctx` object the methods receive. For the files around `eval.py`, see [What you write and what lmnr-cli writes](https://laminar.sh/docs/agent-evaluations/concepts.md#what-you-write-and-what-lmnr-cli-writes).

Here is an example runner for a made-up Python support app. The app has a Postgres database, a seed script, and an HTTP server. Your image, services, commands, and checks will be your app's own. The snippets on this page show the API, not a required setup.

```python Example: evals/support/agent/eval.py theme={null}
from lmnr.evals import EvalRunner, Image, Postgres, http, secret


class SupportEval(EvalRunner):
    # Paths are relative to this file (evals/support/agent/eval.py): ../../.. is the repo root.
    image = (
        Image.python("3.12")
        .uv_sync("../../../pyproject.toml")          # locked dependencies: cached until uv.lock changes
        .add_dir("../../../app", "/srv/app/app")     # the live source, last
    )
    # Started, migrated and in DATABASE_URL before setup(), in every trial.
    services = [Postgres("15", database="support", migrations="../../../migrations")]
    model = "anthropic/claude-sonnet-5-5"            # ctx.model; --model overrides it
    # What the app's processes get; a secret() is read from the shell or .env, never written here.
    env = {"ANTHROPIC_API_KEY": secret("ANTHROPIC_API_KEY")}
    new_task_toml = {"environment": {"cpus": 2, "memory_mb": 4096},
                     "agent": {"timeout_sec": 600}}  # cases without a task.toml get these

    async def setup(self, ctx):
        await ctx.container.run_file("seed.py", "/case/case.json")   # reads DATABASE_URL
        # The app: a foreground command; a process that exits counts as crashed.
        await ctx.container.spawn("api", "uvicorn --app-dir /srv/app app.main:app --port 8080",
                                  ready=http("http://127.0.0.1:8080/health"))

    async def run(self, ctx):
        r = await ctx.container.sh(f"python -m app.cli handle /case/case.json --model {ctx.model}",
                                   cwd="/srv/app", timeout=300, check=False)
        if r.return_code == 0:
            ctx.set_result(outcome="completed", reply=r.stdout.strip())
        else:
            ctx.set_result(outcome="failed", error=r.stderr[-2000:])

    async def verify(self, ctx):
        expected = ctx.case.expected()               # tests/expected.json, never in the container
        result = ctx.result()                        # what run() recorded
        if result.get("outcome") != "completed":
            return {"refund": 0, "reply": 0}
        rows = await self.service(Postgres).query(ctx, "SELECT * FROM refunds")
        reply_ok = await judge(result["reply"], expected["reply_should"])   # your own function
        return {"refund": len(rows) == expected["refund_count"], "reply": reply_ok}
```

`eval.py` is imported more than once: first to read its configuration, then again to run it. So keep module-level code to constants and definitions.

## Attributes

| Attribute | What it does |
| - | - |
| `image` | The image each trial starts from. See [Build the image](https://laminar.sh/docs/agent-evaluations/image.md). To let a case pick another image, use a dict of named images, such as `{"support-evals": base, "support-ocr": base.apt_install("tesseract-ocr")}`. The first one is the default. |
| `services` | The databases, caches, and simulated APIs the app talks to. See [Services](https://laminar.sh/docs/agent-evaluations/services.md). |
| `mocks` | Answers for dependencies that can't run in the container. See [Mocks](https://laminar.sh/docs/agent-evaluations/mocks.md). |
| `model` | The default model, read as `ctx.model`. `--model` overrides it for one run. |
| `env` | Env vars for all commands in the container, in all phases. Values are strings, or `secret("NAME")` for a secret. |
| `secrets` | Names of secrets that must stay out of the container, such as an LLM judge's key. `verify()` reads them from `ctx.secrets`. |
| `new_task_toml` | `task.toml` tables that all cases share, such as resources and timeouts. `lmnr-cli` writes them only into a case that has no `task.toml` yet. For existing cases, edit their `task.toml`. |
| `artifacts` | Container files to collect for grading after the run. See [Artifacts](#artifacts). |
| `run_command` | One shell command to run instead of defining `run()`. It records no result and gets no `ctx`. A non-zero exit fails the trial. |
| `grade_with_test_sh` | `True` grades each case with its own `tests/test.sh` instead of `verify()`. See [Grade with per-case scripts](#grade-with-per-case-scripts). |
| `mock_dependencies` | Python packages for the mock server. Defaults to the packages `eval.py` gets. See [Mocks](https://laminar.sh/docs/agent-evaluations/mocks.md#where-handlers-run). |

## Methods

Each trial calls these methods in order. Each method gets a `ctx` for that trial:

* **`setup(ctx)`** runs after the services have started and loaded the case's seed. Use it to start the app, and to seed data that a service seed can't express. By default, it runs the case's own `environment/seed.py` or `seed.sh`, if the case has one.
* **`run(ctx)`** calls your app's entry point and records the outcome with `ctx.set_result(...)`.
* **`collect(ctx)`** is optional. It runs after `run()`, even when `run()` raised or timed out. Use it to save state for grading or to export a trajectory.
* **`verify(ctx)`** grades the result and returns the rewards.

All methods run on the host. `ctx.container` reaches into the trial's container (see [Where the code runs](https://laminar.sh/docs/agent-evaluations/concepts.md#where-the-code-runs)):

| | Where it acts | What |
| - | - | - |
| `ctx.container` | In the container | `sh`, `run_file`, `spawn`, `wait_for`, `copy`, `write_file`, `read_text`, `read_json` |
| The rest of `ctx` | On the host | `case`, `model`, `env`, `logger`, `set_result` and `result`, `artifacts`, and in `verify()`, `secrets`, `mocks`, and `state` |

## Run commands in the container

* **`ctx.container.sh(cmd, env=None, cwd=None, user="agent", timeout=None, check=True)`** runs a `bash` command and returns its `stdout`, `stderr`, and `return_code`. On a non-zero exit, it raises `CommandError`, unless `check=False`. When a command runs past its `timeout`, it is killed with its children. Then `sh` raises `CommandTimeout`, a `TimeoutError` that carries the output so far. `user="agent"` is the case's agent user, and `"root"` is root.
* **`ctx.container.run_file(path, *args)`** uploads a script from the host to a new temporary folder, runs it, and deletes it. This way, harness scripts don't stay where the agent could find them. A script with a shebang runs directly. A `.py` file runs with `python3`, and anything else with `bash`.
* **`ctx.container.spawn(name, cmd, ready=..., env=None, timeout=60, user="agent")`** starts a long-running process, typically the app's server, and waits until `ready` passes. Its output goes to `/logs/agent/<name>.log`. `cmd` must stay in the foreground, for example `postgres -D ...` instead of `pg_ctl start`. A process that exits counts as crashed, and the error shows the end of its log. Readiness checks are `port(8080)`, `http(url)`, and `cmd("pg_isready")` from `lmnr.evals`, or a plain shell command.
* **`ctx.container.wait_for(ready, timeout=60)`** waits for a readiness check without starting anything. For example, it can wait until an async job writes its final status. It raises `TimeoutError` when the check doesn't pass in time.
* **`ctx.container.copy(host, path)`** copies a host file or folder into the container. `write_file(path, content)`, `read_text(path)`, and `read_json(path)` write and read container files.

A relative host path in `run_file` or `copy` is relative to the file whose code calls it. So `ctx.container.run_file("seed.py")` in `eval.py` runs the `seed.py` next to `eval.py`. Keep these files inside the `evals/` folder, because a `--remote` run has only that folder on its host (see [Where the code runs](https://laminar.sh/docs/agent-evaluations/concepts.md#where-the-code-runs)).

## Read the case and record the outcome

* **`ctx.case`** is the current case. It has:
  * `name`: its `[task] name`;
  * `dir`: its folder;
  * `metadata`: `[metadata]` in its `task.toml`;
  * `instruction`: its `instruction.md`;
  * `file(path)`: a file under `environment/`;
  * `expected()`: `tests/expected.json`;
  * `fixture_text(path)`, `fixture_json(path)`, `fixture_bytes(path)`, and `fixture_path(path)`: files under `tests/fixtures/`.
* **`ctx.set_result(**fields)`** records fields in the trial's `result.json`, merged with earlier calls. `ctx.result()` reads them back, also in `verify()`. When the trial has no trajectory, Laminar shows these fields as the trial's output.
* **`ctx.model`** is the model for this run.
* **`ctx.env`** is the resolved env, including the variables that services and mocks set.
* **`ctx.logger`** is a logger. Its lines in `verify()` go to the trial's verifier log.
* **`self.service(Postgres)`** or `self.service("postgres")` returns a declared service, so you can use its helpers.

Two rules keep the scores meaningful:

* **An exception fails the trial.** Harbor records it in `exception.txt`, and the trial gets no score. Call your app with `check=False`, and record its failures as outcomes, such as `ctx.set_result(outcome="failed", ...)` or `"timeout"`. Then `verify()` grades them as wrong answers. Let only harness errors raise, such as a service that won't start.
* **Keep command timeouts below the case's `[agent] timeout_sec`.** That timeout limits the total time of the services' start, the seeds, `setup`, `run`, and `collect`.

Pass `ctx.model` to your app instead of hard-coding a model, so `--model` and model sweeps work.

## Grade the result

`verify(ctx)` returns the rewards: a number, a bool (`True` counts as `1`), or a dict of them, such as `{"refund": True, "reply": 0.5}`. Each key becomes a score in Laminar. The same method grades all cases, using each case's data.

`verify()` reads the reference answer with `ctx.case.expected()`. It reads the state the run left through `ctx.container` and the services' helpers. For example, this checks the credits in the database and a report file the app wrote:

```python Example theme={null}
async def verify(self, ctx):
    expected = ctx.case.expected()
    [credits] = await self.service(Postgres).query(
        ctx, "SELECT coalesce(sum(amount_cents), 0)::int AS cents FROM credits"
    )
    report = await ctx.container.read_json("/srv/app/out/report.json")
    return {
        "credit": credits["cents"] == expected["credit_cents"],
        "report": report["status"] == "sent",
    }
```

Use hard checks on the state the agent changed. Add an LLM judge for what can't be checked exactly, such as the quality of a reply.

### LLM judges

A judge is your own function. `verify()` runs on the host, so it can call any SDK listed in `evals/pyproject.toml`. Decorate the judge with `@observe` to give it its own span in the trial's trace. Leave the API key out of the recorded inputs. This judge is from the [quickstart's example](https://laminar.sh/docs/agent-evaluations/quickstart.md#grading-the-result):

```python Example: evals/billing/agent/eval.py theme={null}
@observe(name="judge", ignore_inputs=["api_key"])
async def judge(reply: str, criteria: str, api_key: str) -> Verdict:
    response = await AsyncAnthropic(api_key=api_key).messages.parse(
        model="claude-haiku-5-5",
        max_tokens=1024,
        messages=[
            {
                "role": "user",
                "content": (
                    "You grade a billing support agent's reply to a customer.\n\n"
                    f"Criteria: {criteria}\n\nReply:\n{reply}\n\n"
                    "Does the reply meet the criteria?"
                ),
            }
        ],
        output_format=Verdict,
    )
    if response.parsed_output is None:
        raise ValueError(f"The judge gave no verdict (stop reason {response.stop_reason})")
    return response.parsed_output
```

Call it from `verify()` with the key from `ctx.secrets`. In Laminar, `verify()` is traced under the trial's `verifier` span, and the judge's LLM calls show up as LLM spans. The `ctx.logger` lines from `verify()` become the trial's `verifier/test-stdout.txt`.

### Artifacts

Artifacts are container files that are collected for grading after the run. Declare them on the runner, or save them from `collect()`. For example:

```python Example theme={null}
from lmnr.evals import Artifact

class SupportEval(EvalRunner):
    artifacts = ["/srv/app/out/", Artifact("/var/lib/app/state.db", destination="app.db")]

    async def collect(self, ctx):
        await ctx.container.sh("python -m app.cli dump-state > /tmp/state.json", check=False)
        await ctx.artifacts.save("/tmp/state.json")  # -> /logs/artifacts/state.json
```

In `verify()`, read them on the host with `ctx.artifacts.read_text(path)`, `read_json(path)`, and `path(path)`. Pass the container path the file came from. `ctx.artifacts.list()` lists them. `ctx.artifacts.save` replaces anything the agent may have put at the same path.

### Grade in a separate container

By default, `verify()` runs while the trial's container is still up. The services are still running, and everything the run left behind is still there. You can instead grade from a fresh container that sees only what you collected. To do that, set `environment_mode = "separate"` under `[verifier]` in each case's `task.toml`. For new cases, also add `{"verifier": {"environment_mode": "separate"}}` to the runner's `new_task_toml`. In the fresh container:

* No services run. To save a service's state after the run, give it `snapshot=["table", ...]`, or `snapshot=True` for a simulator. Read the state with `ctx.state("postgres", "credits")`.
* `ctx.result()`, `ctx.artifacts`, and `ctx.mocks` still work. Declared artifacts are also copied into the grading container at their original paths.

Use it when grading must not see the app's internals. Most datasets grade in the shared container.

### Grade with per-case scripts

Datasets imported from Harbor have a `tests/test.sh` in each case. To grade with those scripts, set `grade_with_test_sh = True` and don't define `verify()`. Each script runs in the container. It writes its reward to `/logs/verifier/reward.txt`, or several named rewards to `/logs/verifier/reward.json`. For such a dataset, `lmnr-cli` doesn't write stub `test.sh` files.

## Secrets and env vars

Declare secrets by name and keep their values out of the code, for example:

* `env = {"ANTHROPIC_API_KEY": secret("ANTHROPIC_API_KEY")}` passes a secret to all commands in the container. `secret()` also declares it.
* `secrets = ["JUDGE_API_KEY"]` declares a secret that must not reach the container. `verify()` reads it as `ctx.secrets["JUDGE_API_KEY"]`. `verify()` can read any declared secret this way.

`lmnr-cli eval run` reads each secret from your shell, then from `.env.local` and `.env` in the current directory. If one is missing, it stops before anything starts, with exit code `19`. With `--remote`, the values travel with the run as env vars. `.env*` files are not uploaded. Commit a `.env.example` that lists the names. Add `.env` and `evals/*/jobs/` to `.gitignore`.

Per-command variables go in `ctx.container.sh(..., env={...})`. In `setup`, `run`, and `collect`, they can't override a key that the runner's `env` sets.

## Python packages

`eval.py` and `verify()` run on the host, so the packages they import, such as an LLM judge's SDK, go in `evals/pyproject.toml` under `[project] dependencies`:

```toml Example: evals/pyproject.toml theme={null}
[project]
name = "billing-support-evals"
version = "0.1.0"
dependencies = ["anthropic>=2.4.0"]
```

`lmnr-cli` installs them next to the runner, on Python 3.13. To add packages for one dataset only, put a PEP 723 block at the top of its `eval.py`. Packages that the app or a container script needs belong in the image.

## Shared runners

Several datasets can test the same app with the same harness. Then put the runner in a folder in `evals/` that isn't a dataset, by convention `evals/_shared/`. Each dataset's `eval.py` subclasses it. For example:

```python Example: evals/_shared/support.py theme={null}
from lmnr.evals import EvalRunner, Image, Postgres, Valkey, secret

class SupportRunner(EvalRunner):
    image = Image.python("3.12").uv_sync("../../pyproject.toml").add_dir("../../app", "/srv/app/app")
    services = [Postgres("16", migrations="../../migrations"), Valkey("8")]
    env = {"ANTHROPIC_API_KEY": secret("ANTHROPIC_API_KEY")}

    async def setup(self, ctx):
        await ctx.container.run_file("seed.py")  # evals/_shared/seed.py

    async def run(self, ctx): ...
    async def verify(self, ctx): ...
```

```python Example: evals/refunds/agent/eval.py theme={null}
from _shared.support import SupportRunner

class RefundsEval(SupportRunner):
    env = {**SupportRunner.env, "SUPPORT_QUEUE": "refunds"}
```

* The `evals/` folder is on the import path. `--remote` uploads the shared folder with the run.
* Relative paths are relative to the file that declares them. So the shared runner's paths and scripts work from any dataset.
* Datasets whose images come out the same share one build.
* `lmnr-cli eval describe <dataset>` shows the runner's class chain. For each image step and service, it shows the file and line that declared it.

## Next steps

> [card] [Build the image](https://laminar.sh/docs/agent-evaluations/image.md)
>
> Bases, dependencies, and source, or an existing Dockerfile.

> [card] [Services](https://laminar.sh/docs/agent-evaluations/services.md)
>
> Postgres, ClickHouse, Valkey, custom services, and simulated SaaS APIs.

> [card] [Mocks](https://laminar.sh/docs/agent-evaluations/mocks.md)
>
> Answer for an internal service or an observed function.

> [card] [Capture the trajectory](https://laminar.sh/docs/agent-evaluations/trajectories.md)
>
> Get the app's LLM and tool calls into each trial's trace.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.