# Writing criteria

**Who this page is for:** product managers, technical analysts and QA engineers who decide
what a good trial is, in the eval file. The last part, checking a judge against people, ends
with a few lines of Python for a developer.

A **criterion** is one rule that says whether a trial was good. The criteria of an eval are
written in its **eval file**, `<name>.eval.toml`, next to the name of its cases file and the
number of trials.

- **You will be able to:** write an eval file; choose what must pass and what is only
  measured; use the criteria the developers offer; limit what a trial may spend; have a model
  judge a statement; have a person review a trial; and check how far the judge agrees with
  people.
- **Read first:** [Evals](index.md) and [Writing cases](cases.md).
- **Time:** about 20 minutes.

## Four kinds of criterion

```mermaid
flowchart LR
    evidence[("What was recorded<br/>the conversation, how the run ended,<br/>what the environment reported")]
    use["use<br/>code the developers offer"]
    spends["spends<br/>tokens and calls"]
    judge["judge<br/>a model decides a statement"]
    review["review<br/>a person answers a question"]
    must["Must pass<br/>decide whether the trial passed"]
    measured["Measured<br/>reported beside it"]
    evidence --> use & spends & judge & review
    use & spends & judge & review --> must
    use & spends & judge & review --> measured
```

Every criterion reads what was recorded about the trial: the case, the conversation, how the
run ended and what the environment reported when it ended. None of them runs the harness or
touches the world again. Each gives a trial one of three results: **passed**, **failed** or
**could not judge**. Any kind can be **must pass** or **measured**.

- **Must pass** criteria decide whether a trial **passed**: it passes when every one of them
  passes. A trial where one could not judge and none failed has no overall result, and is left
  out of the pass rate.
- **Measured** criteria are scored and reported with their own pass rate, and never decide
  whether a trial passed. Use them for what you want to watch without failing anything on it
  yet: cost, a judge you do not fully trust, a person's opinion.

## The eval file

This is the support desk's eval file:

```toml
# Does the support desk send each customer to the right place and tell them the truth?
name = "support"
cases = "support.cases.csv"
trials = 2
environment = "shop"
stand_in = "approver"

# Every one of these must hold for a trial to pass.

[[criteria]]
use = "closed"
name = "the case is closed, by an answer or a ticket"

[[criteria]]
use = "right_place"
name = "a person is brought in exactly when needed"

[[criteria]]
use = "key_fact"
name = "the reply states the key fact"

# These are measured and reported; they do not decide whether a trial passed.

[[criteria]]
name = "the reply sticks to the articles"
judge = "Everything the final reply tells the customer about the shop's rules, times and steps is supported by the knowledge base articles found during the conversation, or the reply hands the customer to a person without stating any such rule."
measured = true

[[criteria]]
spends = { tokens = 12000 }
name = "stays within 12000 tokens"
measured = true
```

The keys at the top:

| Key | Required | What it says |
|---|---|---|
| `name` | no | The eval's name, used in run names (`support.baseline`): letters, digits, `-` and `_`. Default: the file name without `.eval.toml`. |
| `cases` | yes | The cases file, relative to this file. |
| `trials` | no | How many times each case runs; default 1. |
| `environment` | yes | The environment trials run in, by a name the project offers. |
| `stand_in` | no | Who answers for people during a trial, by a name the project offers. Without one, a trial that waits for a person stops there (it ends *parked*). |
| `only` | no | Run only the cases with these tags or ids: `only = ["smoke"]`. |

Then one `[[criteria]]` table per criterion. Each has exactly one of `use`, `spends`, `judge`
or `review`, and may have:

| Key | For | What it says |
|---|---|---|
| `name` | all; required for `judge` and `review` | What reports call the criterion. Every criterion of the file needs its own name, and `passed` is taken: it means the trial as a whole. |
| `measured = true` | all | Report it, but do not let it decide whether a trial passed. Leave it out for must pass. At least one criterion must pass. |
| `passes`, `fails` | `judge` only | An example of an answer that satisfies the statement, and one that breaks it. |

How many trials? One trial per case says what a version does; two or three say how reliably it
does it, and show which cases are flaky. More cases narrow the intervals in the report more than
more trials do.

## `use`: a criterion the developers offer

Rules that need code, such as "exactly one ticket was opened when the case's route is
`human`", are written once by the developers and offered under a short key. `gvn eval list`
shows them:

```text
Criteria offered (use = "KEY" in an eval file):
  closed: finishes in escalated or resolved
  key_fact: the reply states the key fact
  right_place: a person is brought in exactly when needed
```

`use = "closed"` brings in the first. Without a `name`, reports call it by its own name,
*finishes in escalated or resolved*; with `name = "the case is closed, by an answer or a
ticket"`, they use yours. A key the project does not offer is refused before anything runs,
with the list of keys it does offer.

## `spends`: what a trial may spend

```toml
[[criteria]]
spends = { tokens = 12000 }
measured = true
```

`tokens` limits the input and output tokens of the trial's model calls together; `calls`
limits the number of calls; give one or both (`spends = { tokens = 12000, calls = 5 }`). The
default name says the limits: *spends at most 12000 tokens*. A failing trial's explanation says
what it spent: *spent 14210 tokens, more than 12000*. What the judge spends is not counted
here; it is in the report's cost.

## `judge`: a statement a model decides

```toml
[[criteria]]
name = "polite"
judge = "The reply is polite and does not blame the customer."
passes = "Sorry about that, I have refunded order 1."
fails = "You should have read the policy."
measured = true
```

A **judge** is a model, chosen by the developers, that reads an account of the trial and
decides whether your statement holds. For each finished trial it is shown:

- the case's brief, and its expect under the heading *Expected (reference data the harness did
  not see)*;
- the conversation as recorded: every message, every tool call with its arguments and result;
- how the run ended, the result it produced, and what the environment reported.

It writes its reasoning first, then gives exactly one verdict: **pass** (the statement holds),
**fail** (it does not) or **cannot_tell** (the account does not let it tell). The verdict comes
back through the model vendor's structured output, so it is always one of those three, never a
guess read out of free text. *cannot_tell* counts as could not judge: the trial is left out of
that criterion's pass rate, and, for a must-pass judge, out of the overall pass rate too.

A trial whose run did not finish (it failed, or stopped waiting for someone) fails a judge
criterion without the judge being asked: there is no final result to judge.

### Writing a good statement

- **One thing per statement.** "The reply is polite and correct" fails for two reasons a report
  cannot tell apart. Write two criteria.
- **Something the account shows.** The judge sees the conversation, the expect and what the
  environment reported, nothing else. "The customer will be happy" cannot be checked;
  "the reply apologises before it explains" can.
- **Say what passes, concretely.** "Everything the reply says about delivery times is in the
  articles found" is decided the same way every time; "the reply is accurate" is not.
- **Name the exceptions.** The support desk's statement ends "...or the reply hands the
  customer to a person without stating any such rule", because a hand-over is a good answer
  that states nothing.
- **Give examples when two readers would disagree.** `passes` and `fails` are shown to the judge
  as an example of an answer that satisfies the statement and one that breaks it.
- **Measure before you require.** Start a new judge as `measured = true`, check it against
  people (below), and make it must pass once you trust it.

Every judgement is recorded with the trial: the verdict, the reasoning and the model that gave
it. The web page shows them beside each trial, so a surprising pass rate can be traced to the
judge's own words.

When a judge gives no verdict that can be read (its call failed), the judgement is *missing*:
the report says so, and running the same command again asks the judge again for exactly
those trials.

## `review`: a question a person answers

```toml
[[criteria]]
name = "would you send this?"
review = "Would you be happy for a customer to receive this reply?"
measured = true
```

A **review** is a question a person answers about each trial, in the **Reviews** view of the
[web page](web-page.md) or with `gvn eval review` in a terminal
([Reading reports](reports.md#answering-reviews-from-the-command-line)): they read what
happened, then choose **pass**, **fail** or **cannot_tell**, with an optional note. Their name
and note are recorded with the verdict.

Unlike a judge, a review is asked for every trial, finished or not. Until someone answers, the
trial's review is *waiting for a reviewer*: the report counts it as not judged yet and says the
eval run is not finished. That has a consequence for CI: a [gate](reports.md#gates-in-ci) holds
only for a finished run, so an eval with a review criterion passes its gate once every review
is answered. Reviews are most useful as measured criteria in an eval people read, and to check
a judge.

## Changing criteria after a run

Criteria can change after a run without running the harness again:

```text
gvn eval regrade examples/support_evals/support.eval.toml --version baseline
```

`regrade` scores every recorded trial of the run again with the eval file's current criteria.
A new or changed judge is asked about each trial (that costs its calls, nothing else); a
removed criterion disappears from the report; reviews answered since are read. The run's
cases, version and number of trials must be what they were; `--only`, `--trials` and `--name`
find the run as `gvn eval run` named it.

A changed criterion is a different measurement. gvn tells changes apart by each criterion's
**identity**: what decides its verdict.

| Criterion | Its identity |
|---|---|
| `judge` | the statement, its `passes` and `fails` examples, and the model that judges |
| `review` | the question and the verdicts it offers |
| `spends` | the limits |
| `use` | the code of the check the project offers under that key |

The name a report shows is not part of it: renaming a criterion changes nothing. Nor are the
type hints, comments, docstrings or layout of a check's code: only an edit to what the code
does changes its identity (the code of that one function or class, not of helpers it calls).

Each eval run records the identities it was scored under, and each trial the identity of each
of its scores. So:

- **Running under the same name after a criterion changed is refused**, naming the criteria
  that changed and giving the `regrade` command for that run, and a free name for a new one.
- **A score given under other criteria never counts.** A trial whose scores are out of date
  waits to be scored again, and the report says so with the command that does it.
- **Comparisons measure with one ruler.** A measured criterion that changed between two runs is
  left out of their comparison and named; a changed must-pass criterion changes what *passed*
  means, so the two runs cannot be compared until both are scored with the same criteria.

[Reading reports](reports.md#regrading-after-changing-criteria) shows each message.

## Checking a judge against people

A judge is only as good as its agreement with the people whose opinion it stands in for. To
check one, put the same question to both in one eval: the judge's statement, and a review that
asks people the same thing. Run it, have people answer the reviews in the web page, then count
how often the two verdicts agree on the same trials:

```toml
[[criteria]]
name = "polite"
judge = "The reply is polite and does not blame the customer."
measured = true

[[criteria]]
name = "polite, says a person"
review = "Is the reply polite, without blaming the customer?"
measured = true
```

Three numbers come out:

- **agreement**: the share of trials where the judge and the person gave the same verdict;
- **kappa**: agreement beyond what chance would give. 1 is perfect, 0 is no better than chance.
  It matters when most trials pass: a judge that says *pass* to everything agrees with people
  90% of the time when 90% of replies are fine, and its kappa is 0;
- **the confusion table**: for each pair of verdicts, how many trials got it, which shows
  whether the judge is too strict (*fail* where people say *pass*) or too lenient.

What to do with them: a judge with high agreement and a kappa well above 0 can become must
pass. A judge that is too strict or too lenient needs a sharper statement or `passes` and
`fails` examples taken from the trials where it disagreed; regrade, and check again. Trials
where people disagree among themselves belong in the cases file tagged `ambiguous`.

A developer computes them from the run's records with `Agreement`, in a few lines:

```python
from gvn.evals.judging import Agreement


def agreement(report, judge, review):
    """How far ``judge`` agrees with ``review`` on the trials both answered."""
    pairs = []
    for record in report.trials():
        judgements = record.get("judgements", {})
        if judge in judgements and review in judgements:
            pairs.append((judgements[judge]["verdict"], judgements[review]["verdict"]))
    return Agreement(pairs)


# The verdicts of eight trials, as the records of a reviewed run would hold them:
pairs = [
    ("pass", "pass"), ("pass", "pass"), ("pass", "fail"), ("fail", "fail"),
    ("pass", "pass"), ("fail", "fail"), ("pass", "pass"), ("pass", "fail"),
]
checked = Agreement(pairs)
print(checked.agreed(), checked.total(), checked.rate())  # 6 8 0.75
print(round(checked.kappa(), 2))  # 0.5
print(checked.confusion())
# {('pass', 'pass'): 4, ('pass', 'fail'): 2, ('fail', 'fail'): 2}
```

`agreement(report, "polite", "polite, says a person")` over a `Report` gives the same object for
a real run; [Writing the project](project.md#reviews-and-agreement-from-python) shows a run,
its reviews and the agreement end to end. Here the judge said *pass* twice where a person said
*fail*: it is too lenient, and its statement needs a sharper line.

## Recap

- An eval file names its cases file, trials, environment and stand-in, then one `[[criteria]]`
  table per criterion: `use`, `spends`, `judge` or `review`, with a `name`, and `measured = true`
  for what does not decide a pass.
- A judge decides a plain statement on finished trials; a review is a person's answer in the
  web page and keeps a run unfinished until given.
- `gvn eval regrade` scores a recorded run again with changed criteria; `Agreement` says how far
  a judge agrees with people.

**Next:** [Reading reports](reports.md).
