> For the complete documentation index, see [llms.txt](https://docs.stackai.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.stackai.com/stackai-api/stackai-api-developer-guide/evaluations-and-monitors.md).

# Evaluations and monitors

#### Example: verify a request classifier before release

Suppose a workflow routes requests by returning a category such as `billing`. Check that a saved version still classifies a known billing request correctly. An exact-match evaluator is appropriate because the result is a category, not free-form prose.

Use a project with one selected input and one selected output. Set `PROJECT_ID`, `PROJECT_VERSION`, and `STACKAI_API_KEY` as in the quickstart. Read `/v2/projects/{project_id}/io-schema?version={saved-version}` first. Replace `in-0`, `out-0`, and `legacy_input_nodes` in every body below with the returned contract. Use a key with the required `projects.read`, `evals.read`, `evals.create`, `evals.update`, and `evals.run` permissions, plus access to the project.

This Python example uses `httpx`. It creates one dataset, one rule evaluator, and one experiment, then runs and reads them. It does not automatically retry writes.

```python
import os
import time
import httpx

project_id = os.environ["PROJECT_ID"]
version = int(os.environ["PROJECT_VERSION"])
contract = {"input_kind": "legacy_input_nodes",
            "input_keys": ["in-0"], "output_node_ids": ["out-0"]}
headers = {"Authorization": f"Bearer {os.environ['STACKAI_API_KEY']}"}
with httpx.Client(base_url=os.environ["STACKAI_BASE_URL"].rstrip("/"),
                  headers=headers, timeout=30) as client:
    def post(path, body):
        response = client.post(path, json=body)
        response.raise_for_status()
        return response.json()["data"]

    dataset = post("/v2/evals/datasets", {
        "project_id": project_id, "name": "Request classification",
        "node_contract": contract,
    })
    dataset_id = dataset["dataset_id"]
    print("Save dataset:", dataset_id)
    post(f"/v2/evals/datasets/{dataset_id}/rows", {"rows": [{
        "inputs": {"in-0": "I was charged twice for my subscription."},
        "expected_output": {"out-0": "billing"},
    }]})
    evaluator = post("/v2/evals/evaluators", {
        "project_id": project_id, "name": "Correct request category",
        "evaluator_type": "builtin_rule", "node_contract": contract,
        "config": {"rule": "exact_match", "target_output_node_id": "out-0"},
    })
    evaluator_id = evaluator["evaluator_id"]
    print("Save evaluator:", evaluator_id)
    experiment = post("/v2/evals/experiments", {
        "dataset_id": dataset_id, "project_version_id": version,
        "evaluator_ids": [evaluator_id], "name": "Saved-version category check",
    })
    experiment_id = experiment["experiment_id"]
    print("Save experiment:", experiment_id)
    job = post(f"/v2/evals/experiments/{experiment_id}/jobs", {
        "mode": "generate", "evaluator_ids": [evaluator_id],
    })
    job_id = job["job_id"]
    print("Save job:", job_id)
    deadline = time.monotonic() + 300
    while job["status"] in {"queued", "running"}:
        if time.monotonic() >= deadline:
            raise TimeoutError(f"Inspect existing job {job_id}; do not start another")
        time.sleep(2)
        response = client.get(
            f"/v2/evals/experiments/{experiment_id}/jobs/{job_id}")
        response.raise_for_status()
        job = response.json()["data"]
    print("Job status:", job["status"])
    response = client.get(f"/v2/evals/experiments/{experiment_id}/rows")
    response.raise_for_status()
    print(response.json())
```

Read each row's `generated_output`, `status`, `error`, and `scores`. A matching output `{"out-0":"billing"}` receives an exact-match score of `1`; a different category receives `0`. A score of `0` is a completed comparison, not an execution error. A failed scoring status means the comparison could not complete—for example, because an expected value was missing. Inspect job and row errors before judging quality.

One case checks only one behavior. Add representative inputs and known correct categories to the dataset, then create another experiment for the version you want to compare. Experiments snapshot the dataset: editing it later does not change an existing experiment. Use a semantic or judge-based evaluator when more than one wording can be correct.

#### Job lifecycle and conflicts

202 means the job was queued. Terminal statuses are `completed`, `completed_with_failures`, `failed`, and `cancelled`. Inspect row-level failures even if some outputs succeeded. Only one job may be active per experiment: a 409 can include the active job's Location/status URL and IDs in metadata. Follow that job instead of repeatedly creating jobs. A 503 on a job read means live state is temporarily unavailable; retry that GET.

Dataset detail reads expose contract-drift warnings. Dataset PATCH can re-key rows against a replacement contract; inspect the update body before using it as a simple rename. Evaluator config changes create immutable versions when material. Explicit null clears a row's expected output and clears experiment notes where documented; omitted fields remain unchanged.

Deleting a dataset also removes its rows and experiments. Deleting an experiment removes its snapshot rows and scores. Evaluator deletion is soft and preserves historical scores. These operations have different retention semantics.

#### Monitor production quality

GET `/v2/evals/monitor-limits` first. Choose a reference-free evaluator and POST a monitor with the project, evaluator, sampling rate, and daily cap. Current schema bounds sampling to greater than zero and at most 0.3 and the daily cap to 1–1000; use the limits endpoint rather than hard-coding policy forever.

Read/update the monitor, inspect `/v2/evals/monitors/{monitor_id}/score-stats`, tune `/v2/evals/monitors/{monitor_id}/alert`, and traverse `/v2/evals/monitors/{monitor_id}/sampled-runs`. Windows are `24h`, `7d`, `30d`, or `all`. Explicit null on an alert knob resets it to the server default; omit it to keep the stored setting. Sampled-run traversal preserves an insertion cutoff. Deleting the monitor retains scores already present in run history.

#### Score individual runs

POST `/v2/evals/runs/{run_id}/scores` using a reference-free evaluator. This appends a score; it does not overwrite history, so retries can create additional scores. List the run's scores (oldest first) or GET a specific `/v2/evals/scores/{score_id}`. Trace-backed scoring and score reads require analytics access in addition to their evaluation permissions.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.stackai.com/stackai-api/stackai-api-developer-guide/evaluations-and-monitors.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
