Browse documentation
Evals
View Markdown
On this page

Writing the project

Who this page is for: developers. You write the project once; afterwards product managers and QA engineers write cases and criteria in files, run gvn eval and review in the web page, without touching Python.

A project is where the names in eval files mean something. An eval file says environment = "shop", use = "refunds" and --version careful; the project is the Python object that maps each of those names to the code behind it, and says where runs are recorded and which models run and judge them.

  • You will be able to: write a Project for your harness (its versions, environments, stand-ins, criteria, models, prices and stores), point gvn eval at it, build versions from a gvn-domains harness, and use gvn.evals directly from Python: run evals, read reports, compare them, route on the verdict, and answer reviews.
  • Read first: Evals and Writing criteria for what the files need; Testing your harness for the fakes used below.
  • Time: about 30 minutes.

The picture

flowchart LR
    files[("Eval and cases files<br/>names only")]
    cli["gvn eval / web page"]
    project["Project<br/>name -> object"]
    subgraph offered ["What the project offers"]
        direction TB
        versions["versions<br/>Subject"]
        environments["environments<br/>Environments"]
        standins["stand-ins<br/>StandIn"]
        criteria["criteria<br/>Criterion or Check"]
    end
    runner["Runner<br/>models by role, rates, currency"]
    stores[("Journal and Results<br/>every run, every trial record")]
    files --> cli --> project
    project --> offered
    project --> runner --> stores

Eval files hold names and text, nothing else. The project resolves them: Project.eval(...) turns an eval file into an Eval (cases read, criteria looked up or built, environment and stand-in found), and Project.runner(...) builds the Runner that runs it over the project's journal, results store, models and clock. A name the project does not offer is refused before anything runs, with the list of what it does offer, so a typo in a file never becomes a half-run eval.

Where it fits

gvn.evals is a layer of its own, between the runtime it drives and the console that people use:

console (gvn eval, the web page, Project)  ->  adapters (eval files, SqliteResults)
    ->  evals (cases, criteria, judging, running, report, comparison)  ->  runtime  ->  harness  ->  kernel

Its ports, in gvn.evals.ports, are what you implement or choose:

Port What it is Ready-made
Subject a version: how to start one run of it HarnessSubject in gvn_domains.evaluating; FixedSubject in gvn.testing.eval_fakes
Environments / Environment a fresh environment for each trial: its tools, policy and what it reports at the end HarnessEnvironment in gvn_domains.evaluating; FixedEnvironments for tests
StandIn who answers what a person would, during a trial Approving in gvn.evals.stand_ins; ScriptedStandIn for tests
Results the store of eval runs and trial records SqliteResults in gvn.adapters.eval_store; MemoryResults for tests

Contract suites for each port are in gvn.testing.eval_contracts, like those for the other ports (see contract suites).

How the command line finds it

Write a module with a function that returns the project, then tell gvn eval its name as package.module:attribute. gvn looks, in order, at:

  1. --project package.module:attribute on the command line;
  2. the environment variable GVN_PROJECT;
  3. project = "package.module:attribute" under [tool.gvn] in a pyproject.toml, in the current folder or the nearest folder above it that has the setting. That folder is where the module is imported from.

The [tool.gvn] section

[tool.gvn] in pyproject.toml is where a repository records its project, so nobody has to pass --project on every command. The gvn command line and the Workbench both read it. It accepts two settings:

Setting Value What it does
project text, "package.module:attribute" Names the project to load: the module, then the attribute in it.
pythonpath a list of folder names, relative to the pyproject.toml The folders the module is imported from, in place of the folder holding the file. Each must be a folder inside it.

gvn's own repository sets only project, because its module is importable from the repository root:

[tool.gvn]
project = "examples.support_evals.project:project"

A project in the src/ layout adds pythonpath, so gvn needs no PYTHONPATH and no install to find the module:

[tool.gvn]
project = "release_review.project:project"
pythonpath = ["src"]

The attribute may be a Project or a function of no arguments returning one. A function is better: building the project opens the stores and the model clients, which should happen when a command runs, not when the module is imported.

The parts of a project

Argument What it is
root The folder holding the eval and cases files; searched with its subfolders for *.eval.toml, *.cases.csv and *.cases.jsonl. The web page reads and writes only files under it.
versions Name -> Subject, at least one: what --version may name.
environments Name -> Environments, at least one: what environment = "..." may name.
journal Where every trial's run, and every judge's and reviewer's run, is journaled: a SqliteJournal or any Journal.
results The Results store: one manifest per eval run, one record per trial.
model The model that serves every model call naming no role: the harness's own calls.
clock The clock runs are driven by: SystemClock() in production.
criteria Key -> Criterion or Check: what use = "<key>" may name. Optional.
stand_ins Name -> StandIn: what stand_in = "..." may name. Optional.
model_roles Role -> Model. A judge criterion needs the role "judge"; a harness whose agents name roles needs those too.
rates The Rates that price model calls. Without them reports show no cost and --budget is refused.
currency What the rates are in, such as "USD", shown beside every cost.
harnesses The harnesses the project offers, each a gvn.runtime.harnesses.Harness known by its own name(). The Workbench draws them and reads their runs. Optional.

A complete project

The example below is a refund desk: one agent with one tool, refund. Two versions differ only in their instructions: eager refunds whatever is asked about; careful only what arrived damaged. It runs offline, with scripted models from gvn.testing standing in for the desk's model and the judge, and in-memory stores; swap those for real ones and nothing else changes.

The world of a trial

An Environment holds one trial's world, built fresh by Environments.open(case, trial): the tools the run acts with, bound to that world, the tool policy, and observe(), which reports what the world holds when the run ends, as plain JSON. Criteria read that report, never the world.

import hashlib

from gvn.evals.ports import Environment, Environments
from gvn.harness.agent import VERDICTS
from gvn.harness.tools import Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.shortcuts import FunctionTool


def refund_tool(refunded):
    """The refund tool, writing to the list of refunds it is given."""

    def refund(order):
        refunded.append(order)
        return {"refunded": order}

    arguments = Record({"order": Text()})
    return FunctionTool("refund", "Refund an order in full.", arguments, refund,
                        namespace="shop.payments")  # fmt: skip


class ClearEveryCall(Decision):
    """The tool policy of a trial: every call may run."""

    def outcomes(self):
        return VERDICTS

    def judge(self, consultation):
        return VERDICTS.named("cleared")


class Shop(Environment):
    """One trial's world: no refunds yet, and the tool that makes them."""

    def __init__(self):
        self._refunded = []
        self._toolbox = Toolbox([refund_tool(self._refunded)])

    def toolbox(self):
        return self._toolbox

    def policy(self):
        return ClearEveryCall()

    async def observe(self):
        return {"refunded": list(self._refunded)}


class Shops(Environments):
    """A fresh shop for every trial."""

    def name(self):
        return "shop"

    async def open(self, case, trial):
        return Shop()

An environment can also answer extra request kinds (fulfillers()), name request kinds the stand-in answers (external()), and release what it holds (close(), called once after observe, also when the trial failed).

The versions

A Subject is a version: its name(), the actor_class() its runs are (what replay rebuilds), start(run_id, brief) giving a fresh actor and the event that starts it, and a fingerprint() that changes whenever the version would behave differently. The fingerprint is recorded with every eval run; continuing a run against a version whose fingerprint changed is refused, so a run is always of one version.

from gvn.evals.ports import Subject
from gvn.harness.agent import Agent
from gvn.harness.events import Event


class Desk(Subject):
    """A version of the refund desk: one agent under these instructions."""

    def __init__(self, name, instructions):
        self._name = name
        self._instructions = instructions
        self._offered = [refund_tool([])]  # what the agent offers its model

    def name(self):
        return self._name

    def fingerprint(self):
        text = Agent.definition().fingerprint() + self._instructions
        return hashlib.sha256(text.encode()).hexdigest()

    def actor_class(self):
        return Agent

    def start(self, run_id, brief):
        agent = Agent(run_id, self._instructions, tools=self._offered, turns=3)
        prompt = f"Order {brief['order']}: {brief['message']}"
        return agent, Event("started", {"prompt": prompt})


VERSIONS = {
    "eager": Desk("eager", "Refund every order the customer asks about."),
    "careful": Desk("careful", "Refund an order only when it arrived damaged."),
}

The agent built by start offers the model a tool with the same identity as the environment's (shop.payments.refund); the call itself runs on the trial's own tool. The brief is the case's brief.* columns.

The criteria and the models

The criteria offered are the rules that need code. Each reads only what was recorded:

  • Answer(label, accepts): the run finished and accepts(payload, case) holds for its result's payload. For an agent, the payload's "text" is its last reply.
  • EnvironmentHolds(label, accepts): accepts(observed, case) holds for what the environment reported, whether the run finished or not.
  • any Check from gvn.runtime.evaluation (Finishes, Gated, Within, ...): it passes when the check finds no problem in the trial's trace.
  • Spends(tokens=..., calls=...), and Named(name, criterion) to show any criterion under another name. The eval file's spends and name build these two for you.

accepts returns a bool or a Score; a Score carries an explanation, which reports and the web page show beside a failing trial, so prefer it for anything a person will debug.

from gvn.evals.criteria import Answer, EnvironmentHolds
from gvn.evals.evidence import Score
from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import Reply
from gvn.runtime.evaluation import Finishes
from gvn.testing.fakes import FunctionModel, answer_reply


def refunded_as_expected(observed, case):
    """The shop holds a refund of the case's order exactly when the case expects one."""
    wanted = [case.brief()["order"]] if case.expect()["refund"] else []
    if observed["refunded"] == wanted:
        return Score.passing(f"refunded {wanted}")
    return Score.failing(f"refunded {observed['refunded']}, expected {wanted}")


def names_the_order(payload, case):
    """The agent's last reply names the case's order."""
    return case.brief()["order"] in payload["text"]


CRITERIA = {
    "finished": Finishes("completed"),
    "refunds": EnvironmentHolds("refunds exactly when due", refunded_as_expected),
    "names_order": Answer("the reply names the order", names_the_order),
}


def desk_model(exchange):
    """Stands in for the desk's model: it refunds when its instructions allow it."""
    prompt = exchange.messages()[0].text()
    order = prompt.split(":")[0].removeprefix("Order ")
    if any(message.role() == TOOL for message in exchange.messages()):
        return Reply(Message.assistant(f"Order {order} is refunded."), 50, 10)
    if "only when" in exchange.instructions() and "broken" not in prompt:
        return Reply(Message.assistant(f"Order {order} cannot be refunded, sorry."), 50, 10)
    return Reply(Message.assistant("", [ToolCall("c1", "refund", {"order": order})]), 50, 10)


def judge_model(exchange):
    """Stands in for the judge: every reply here is polite."""
    return answer_reply({"reasoning": "Short and courteous.", "verdict": "pass"}, 200, 20)

The keys (refunds, names_order) are what eval files write after use =; the labels are what reports show unless the file names the criterion itself. Keep keys short and stable: a renamed key breaks every eval file that uses it.

The project, and the command line on it

import pathlib

from gvn.console.project import Project
from gvn.runtime.spending import Rates
from gvn.testing.eval_fakes import MemoryResults
from gvn.testing.fakes import ManualClock, MemoryJournal


def build(root, journal, results, model, judge, clock):
    """The refund desk's project over these stores and models."""
    return Project(
        root,
        versions=VERSIONS,
        environments={"shop": Shops()},
        journal=journal,
        results=results,
        model=model,
        clock=clock,
        criteria=CRITERIA,
        model_roles={"judge": judge},
        rates=Rates({None: {"input": 0.10, "output": 0.50}}),  # USD per million tokens
        currency="USD",
    )


project = build(
    pathlib.Path.cwd(),
    MemoryJournal(),
    MemoryResults(),
    FunctionModel(desk_model, name="scripted-desk"),
    FunctionModel(judge_model, name="scripted-judge"),
    ManualClock(),
)

build(...) takes the stores and models as arguments, as the support desk's project does: production calls it with SQLite stores and vendor models, tests with fakes. Now the files a product manager would write, and the commands they would type. main(argv, project=...) is the gvn command line with the project handed in, which is how a test runs it:

pathlib.Path("refunds.cases.csv").write_text(
    "case_id,tags,brief.order,brief.message,expect.refund\n"
    "broken-mug,damaged smoke,A1,My mug arrived broken.,true\n"
    "cracked-vase,damaged,A2,The vase is broken.,true\n"
    "changed-mind,smoke,B1,I changed my mind.,false\n"
    "too-big,,B2,The coat is too big.,false\n"
    "late,,B3,It came a day late.,false\n"
    "wrong-colour,,B4,I wanted blue.,false\n"
)
pathlib.Path("refunds.eval.toml").write_text(
    """
cases = "refunds.cases.csv"
trials = 2
environment = "shop"

[[criteria]]
use = "refunds"

[[criteria]]
use = "names_order"

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

[[criteria]]
spends = { calls = 3 }
measured = true
"""
)

from gvn.console.cli import main

for version in ("eager", "careful"):
    main(["eval", "run", "refunds.eval.toml", "--version", version], project=project)
status = main(["eval", "compare", "refunds.careful", "refunds.eager"], project=project)
print(status)  # 0

It prints the two reports and the comparison:

refunds on eager: 4 of 12 trials passed, 33% (likely between 0% and 67%)
Cases: 2 solid (passed every time), 0 flaky (passed some of the time), 4 failing (never passed)
...
refunds on careful: 12 of 12 trials passed, 100% (likely between 61% and 100%)
...
'refunds.careful' is better than 'refunds.eager'.
'refunds.careful' is a run of the version careful and cost 0.00052 USD.
'refunds.eager' is a run of the version eager and cost 0.0006 USD.
  passed overall: +67 percentage points (likely between +33 and +100) over 6 cases; 4 did better, 0 did worse
  ...

main returns the exit status rather than leaving the process, and takes out= and err= streams, so a test can check both what was printed and the status. The support desk's tests (examples/support_evals/tests/) run every command of its README this way.

The production project

The same build, over durable stores and a vendor model. This is the support desk's project(), shortened:

import anthropic
from gvn.adapters.anthropic import AnthropicModel
from gvn.adapters.clock import SystemClock
from gvn.adapters.eval_store import SqliteResults
from gvn.adapters.sqlite import SqliteJournal

ROOT = pathlib.Path(__file__).parent


def project():
    store = ROOT / ".gvn"
    store.mkdir(exist_ok=True)
    client = anthropic.AsyncAnthropic()  # the key is read when the first call is made
    return build(
        ROOT,
        SqliteJournal(store / "journal.sqlite"),
        SqliteResults(store / "results.sqlite"),
        AnthropicModel(client, MODEL_ID, max_tokens=600),
        AnthropicModel(client, MODEL_ID, max_tokens=2000),
        SystemClock(),
    )

The model passed as judge may be another model than the harness's; it is recorded in every eval run's manifest under its role, and a comparison between runs judged by different models says so.

Harnesses, for the Workbench

A project can also offer its harnesses: harnesses=[...], each a gvn.runtime.harnesses.Harness (see Harnesses). The evals do not need them: an eval runs versions. The Workbench does. It lists the harnesses the project offers, draws each from its entry actor down, and reads a recorded run as a run of the harness whose actor class rebuilds it (or, failing that, of the first version that does). To answer or continue a run it builds a Launcher over the harness with the project's own model(), model_role(...) and clock().

The release review example offers one harness over a fixed CI server, and two versions of its workflow:

def build(root, journal, results, model, clock):
    return Project(
        root,
        versions={
            "baseline": ReleaseVersion("baseline", ReleaseReview),
            "candidate": ReleaseVersion("candidate", ReleaseReviewCandidate),
        },
        environments={"fixed_ci": FixedCiWorlds()},
        journal=journal,
        results=results,
        model=model,
        clock=clock,
        criteria={"ends_as_expected": EndsAsExpected(), "no_rejections": NoRejections()},
        stand_ins={"release_manager": ReleaseManager()},
        harnesses=[ReleaseReviewHarness(FixedCi(CI_BUILDS))],
    )

The Workbench's guide answers with the project's model under the role "guide" when the project offers one (model_roles={"guide": ...}), and with its default model otherwise.

Where runs are stored

Everything about an eval run is in the two stores; nothing lives only in memory, which is why a run continues after a crash.

  • The results store holds each eval run's manifest, what the run is of: the eval's name, the version and its fingerprint, the cases' fingerprint and ids, each criterion's identity (its fingerprint and the model that judges it; for a criterion written in Python, the fingerprint covers what its code does, not its hints, comments or layout: gvn.evals.criteria.code_identity), the number of trials, the environment, the stand-in, the models by role and the currency. Next to it, one record per trial: its status (finished, parked or errored), what the environment reported, the judgements, each criterion's score and the identity it was given under, whether it passed, its usage and its cost (every attempt included). While a runner works on a trial it holds a claim on it there, so two runners of the same eval run never run one trial twice; a claim left by a runner that died runs out by itself.
  • The journal holds every run: each trial is an ordinary run under the id <eval run>.<case_id>.<trial> (refunds.eager.late.0; a second attempt adds .r1), and each judge's or reviewer's question is a run of its own under the trial's id, a dot, the criterion's name and a short fingerprint.

So a trial can be read back like any run, with replay, forked, or opened in the web page, and stepped through in the Workbench. Point both stores at files in a folder of the project (the support desk uses .gvn/ beside its eval file) and keep that folder out of version control.

Versions from a gvn-domains harness

A harness from gvn-domains is built over its ports (SupportDesk(knowledge, tickets)), so a version and a trial's world are two builds of it. gvn_domains.evaluating has both adapters:

  • HarnessSubject(name, harness, settings): the harness whose start begins each run. Its tools are not used. settings is plain JSON saying what distinguishes the version beyond its machine, typically its instructions; it goes into the fingerprint.
  • HarnessEnvironment(harness, observe, close=None): the harness built over THIS trial's ports, supplying the toolbox, policy and extra fulfillers, and observe, a function returning what the trial's world holds.
  • final_reply(payload, stages): the last text a finished workflow sent the person, for criteria about the reply.

From the support desk's project:

class Shops(Environments):
    """A fresh shop for each trial: the articles and an empty ticket system."""

    def name(self):
        return "shop"

    async def open(self, case, trial):
        knowledge, tickets = ShopKnowledge(), ShopTickets()

        def observe():
            return {"tickets": tickets.opened(), "searches": knowledge.searches()}

        return HarnessEnvironment(SupportDesk(knowledge, tickets), observe)


def versions():
    nowhere = (ShopKnowledge(()), ShopTickets())
    return {
        "baseline": HarnessSubject(
            "baseline",
            SupportDesk(*nowhere),
            {"triage": TRIAGE, "answer": ANSWER, "escalate": ESCALATE},
        ),
        "plain_spoken": HarnessSubject(
            "plain_spoken",
            SupportDesk(*nowhere, run=PlainSpokenRun),
            {"triage": PLAIN_TRIAGE, "answer": PLAIN_ANSWER, "escalate": ESCALATE},
        ),
    }

Stand-ins

A harness that asks a person (an approval, a question) waits in production. In a trial the stand-in answers instead, and its answers are journaled like any answer. Approving() approves every approval and answers nothing else; a question nobody answers leaves the trial parked, which a criterion may accept as the right end (Parks in gvn.runtime.evaluation). A stand-in of your own implements name() and answer(request, case), returning the answering Event or None; it sees the case, so the answer can depend on the case's expect (a customer who replies "yes" in one case and "no" in another).

Using gvn.evals from Python

The command line is a thin layer over four objects:

  • Eval(name, dataset, criteria, environments, stand_in=None, trials=1): what to measure. It names no version: the same eval runs against each.
  • Runner(journal, results, model, clock, model_roles=..., rates=..., budget=..., ...): runs evals and keeps their results. run(eval, subject, run_name=None) runs or continues one and returns its report; regrade(...) scores a recorded run again; report(run_name) reads one; review(...) gives a pending review its verdict.
  • Report: summary(), rate(criterion="passed") (with mean(), interval(), always(), ever()), stabilities(), coverage() (trials asked for, ran, could not run, not run yet and judged), complete(), pending(), cost(), gate(at_least, could_not_run=0), compare(baseline, margin=0.0, min_cases=6) and to_plain().
  • Comparison: verdict() ("better", "no_better", "worse" or "inconclusive"; in_words() gives what people are shown: better, about the same, worse, not enough data to tell), reason() (why there is not enough data to tell, when a case was not judged in a run or fewer than min_cases cases were judged in both), difference(criterion) with its mean(), interval(), improved() and worsened() cases, and summary().

Project.eval(eval_file) and Project.runner() build the first two from the files, so code and people work on the same runs:

import asyncio

from gvn.adapters.eval_files import read_eval
from gvn.evals.comparison import Verdict
from gvn.runtime.replay import Replay

refunds = project.eval(read_eval(pathlib.Path("refunds.eval.toml")))
runner = project.runner()


async def compared():
    eager = await runner.report("refunds.eager")
    careful = await runner.run(refunds, project.version("careful"), "refunds.careful.again")
    return eager, careful


eager, careful = asyncio.run(compared())
print(careful.rate().mean(), careful.stabilities()["late"])  # 1.0 solid
comparison = careful.compare(eager)
print(comparison.verdict(), Verdict().judge(comparison).name())  # better better
print(comparison.difference().improved())  # ('changed-mind', 'late', 'too-big', 'wrong-colour')
print(careful.gate({"passed": 0.9}), eager.gate({"passed": 0.9}))
# () ('passed: 33% passed, below the required 90%',)

trace = asyncio.run(Replay(project.journal()).recorded("refunds.eager.late.0", Agent))
print(trace.state(), [frame.event().name() for frame in trace])
# completed ['started', 'model_replied', 'cleared', 'tools_returned', 'model_replied']

Verdict is a kernel Decision over a Comparison, with the four verdicts as its outcomes, so a workflow routes on it like on any decision: an improving harness proposes a version, runs the eval, and adopts the version only on better (see Self-improvement). The last lines replay the eager desk's trial of the late case: it refunded an order that arrived late, and the trace shows the tool call that did it.

Reviews and agreement from Python

A Review parks its question until someone answers. The web page answers through Runner.review(...), which takes the verdict, the person (a Principal, which your own entry point vouches for) and a note; the trial is scored again at once. Here one judge and one review ask the same thing about two cases, a person answers, and Agreement counts how often the judge agreed:

from gvn.evals.cases import Dataset
from gvn.evals.criteria import Criteria
from gvn.evals.judging import Agreement, Judge, Review
from gvn.evals.running import Eval
from gvn.harness.events import Principal

polite = Eval(
    "polite",
    Dataset("refunds", refunds.dataset().cases()[:2]),
    Criteria(
        "polite",
        must_pass=[CRITERIA["refunds"]],
        measured=[
            Judge("polite", "The reply is polite and does not blame the customer."),
            Review("polite, says a person", "Is the reply polite, without blaming the customer?"),
        ],
    ),
    Shops(),
)
careful_desk = project.version("careful")


async def reviewed():
    report = await runner.run(polite, careful_desk)
    for case_id, trial, criterion, _ in report.pending():
        verdict = "pass" if case_id == "broken-mug" else "fail"
        person = Principal("ana@example.com")
        await runner.review(polite, careful_desk, report.run_name(), case_id, trial,
                            criterion, verdict, by=person, note="read by hand")  # fmt: skip
    return await runner.report(report.run_name())


report = asyncio.run(reviewed())
print(report.complete())  # True
pairs = [
    (record["judgements"]["polite"]["verdict"],
     record["judgements"]["polite, says a person"]["verdict"])
    for record in report.trials()
]  # fmt: skip
agreement = Agreement(pairs)
print(pairs, agreement.rate())  # [('pass', 'pass'), ('pass', 'fail')] 0.5

Judge and Review take more than an eval file gives them: verdicts (your own scale, such as {"good": 1.0, "acceptable": 0.5, "poor": 0.0, "unsure": None}), passing (the least value that counts as a pass) and shows (a function choosing what the judge or reviewer reads instead of the default account, gvn.evals.judging.shown).

Recap

  • A Project maps the names of eval files to versions (Subject), environments, stand-ins and criteria, and holds the journal, results store, models by role, rates and currency. It can also offer harnesses, which the Workbench draws and runs. gvn eval finds it through --project, GVN_PROJECT or [tool.gvn].
  • Each trial is an ordinary journaled run in a fresh Environment; criteria read what was recorded, so runs continue, regrade and replay.
  • From Python: Eval, Runner, Report, Comparison, and Verdict to route on the result.