diff --git a/.github/scripts/check_plugin_api.py b/.github/scripts/check_plugin_api.py index c68125112..c62a348be 100644 --- a/.github/scripts/check_plugin_api.py +++ b/.github/scripts/check_plugin_api.py @@ -41,6 +41,9 @@ # What a plugin reads of recorded runs. "agent_env.task.store.task_instances", "agent_env.task.store.count_task_instances", "agent_env.task.store.find_task_instance", "agent_env.task.store.TaskInstance", + # What a reader of a run's usage sums its ledger with and shows. + "agent_env.task.usage.summary.summarize", "agent_env.task.usage.summary.UsageSummary", + "agent_env.task.usage.summary.Share", "agent_env.task.usage.summary.Bound", # What a runner calls and returns, and the run index it records each run in. "agent_env.task.task.Task.get", "agent_env.task.task.Task.run", "agent_env.task.teardown.teardown_run", "agent_env.runner.runner.run_outcome", diff --git a/AGENTS.md b/AGENTS.md index d2356bb3d..1175a0da6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -403,9 +403,11 @@ orchestrators call it the same way. What callers rely on: (`usage.ledger.ahead`), and the step's completion replaces them with its final entries. A re-register keeps it, so it holds every attempt and generation. `task/usage/summary.py` sums it by role, then by model, for the run summaries (`agent-env run`, `eval run`, `task run`), unpriced usage counted apart, never as $0, and a cost priced on an - assumed rate (`cost_assumed`) shown as at most. A runner that doesn't set `ATTEMPT_EPOCH` writes entries with no - attempt, kept by step and role alone: exact for a run without retries, a lower bound for one with. A runner that - writes the instance some other way loses that spend from the ledger. + assumed rate (`cost_assumed`) shown as at most. Its `to_dict` is the summary's one JSON shape, with the `Bound` the + CLI prints (`exact`, `at_least`, `at_most`, `estimated`, `unpriced`), for any reader that shows a run's cost. A + runner that doesn't set `ATTEMPT_EPOCH` writes entries with no attempt, kept by step and role alone: exact for a run + without retries, a lower bound for one with. A runner that writes the instance some other way loses that spend + from the ledger. - The runner writes its run identifier to `context.metadata["workflow_id"]` before calling `run()`; core stores it opaquely with the instance. - Each step runs under `protocol_v1.authorized` for the deployed envs in its context: a protocol-client diff --git a/src/agent_env/cli/usage_output.py b/src/agent_env/cli/usage_output.py index cdbaa0788..1333776ef 100644 --- a/src/agent_env/cli/usage_output.py +++ b/src/agent_env/cli/usage_output.py @@ -5,7 +5,7 @@ from agent_env.config.model import ModelRole from agent_env.config.model_pricing import ReportedBy -from agent_env.task.usage.summary import Share, UsageSummary +from agent_env.task.usage.summary import Bound, Share, UsageSummary _ROLE_NAMES = {role.value: role.record_key for role in ModelRole} # The cost sources that aren't the price map, in the order they're named. @@ -49,12 +49,10 @@ def _share(share: Share) -> str: def _cost(of: UsageSummary | Share) -> str: - """``of``'s cost with what it is: ``at least`` when some usage went unpriced or uncounted, ``at most`` when some - was priced on an assumed rate, ``estimated`` when both, and ``unpriced`` when nothing was priced.""" - if of.cost_usd is None: + """``of``'s cost after the word its ``bound`` gives, none when exact; ``unpriced`` when nothing was priced.""" + if of.bound is Bound.UNPRICED: return "unpriced" - lower, upper = of.lower_bound, of.upper_bound - word = "estimated " if lower and upper else "at least " if lower else "at most " if upper else "" + word = "" if of.bound is Bound.EXACT else f"{of.bound.value.replace('_', ' ')} " return f"{word}{_dollars(of.cost_usd)}" diff --git a/src/agent_env/task/usage/summary.py b/src/agent_env/task/usage/summary.py index 492d6d4e2..2fac394f3 100644 --- a/src/agent_env/task/usage/summary.py +++ b/src/agent_env/task/usage/summary.py @@ -1,13 +1,16 @@ """A run's usage for people to read: its ledger (``ledger``) summed by role, then by model. An entry with per-model rows (``models``) splits along them; one without counts under its own model. Usage the map couldn't price is unpriced, never $0, and makes the cost a lower bound, as a partial or a still running entry does; a cost priced on an assumed rate -(``cost_assumed``) makes it an upper bound.""" +(``cost_assumed``) makes it an upper bound. ``to_dict`` gives a summary as JSON, the one shape every reader takes, with +the ``bound`` word the CLI prints.""" from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass -from typing import TYPE_CHECKING +from enum import StrEnum +from functools import reduce +from typing import TYPE_CHECKING, Any from agent_env.config.model import ModelRole @@ -18,6 +21,17 @@ _ROLES = tuple(role.value for role in ModelRole) +class Bound(StrEnum): + """What a cost figure is: the whole cost, a lower bound (some usage unpriced, partial or still running), an upper + bound (some cost priced on an assumed rate), an estimate (both), or nothing priced.""" + + EXACT = "exact" + AT_LEAST = "at_least" + AT_MOST = "at_most" + ESTIMATED = "estimated" + UNPRICED = "unpriced" + + @dataclass class Share: """One role's usage on one model: its tokens, each None when nothing counted it, and the cost of the part that was @@ -41,6 +55,15 @@ def lower_bound(self) -> bool: def upper_bound(self) -> bool: return self.assumed + @property + def bound(self) -> Bound: + return _bound(self.cost_usd, self.lower_bound, self.upper_bound) + + def to_dict(self) -> dict[str, Any]: + return {"role": self.role, "model": self.model, "cost_usd": self.cost_usd, "bound": self.bound.value, + "input_tokens": self.input_tokens, "output_tokens": self.output_tokens, "unpriced": self.unpriced, + "assumed": self.assumed, "partial": self.partial} + def add(self, part: UsageEntry | ModelEntry, partial: bool) -> None: self.input_tokens = _plus(self.input_tokens, part.get("input_tokens")) self.output_tokens = _plus(self.output_tokens, part.get("output_tokens")) @@ -75,6 +98,26 @@ def lower_bound(self) -> bool: def upper_bound(self) -> bool: return any(share.upper_bound for share in self.shares) + @property + def bound(self) -> Bound: + return _bound(self.cost_usd, self.lower_bound, self.upper_bound) + + @property + def input_tokens(self) -> int | None: + return reduce(_plus, (share.input_tokens for share in self.shares), None) + + @property + def output_tokens(self) -> int | None: + return reduce(_plus, (share.output_tokens for share in self.shares), None) + + def to_dict(self, attempts: bool = True) -> dict[str, Any]: + """The summary as JSON: its cost and bound, token counts, attempts (null with ``attempts=False``, for a total + over several runs), sources and shares in role order. Every key is always there; a figure nothing gave is + null, never 0.""" + return {"cost_usd": self.cost_usd, "bound": self.bound.value, "input_tokens": self.input_tokens, + "output_tokens": self.output_tokens, "attempts": self.attempts if attempts else None, + "sources": list(self.sources), "shares": [share.to_dict() for share in self.shares]} + def summarize(ledger: Iterable[UsageEntry]) -> UsageSummary | None: """``ledger``'s entries summed by role and model; None when it has none. A task instance's ``usage`` gives a run's; @@ -101,6 +144,16 @@ def _parts(entry: UsageEntry) -> list[tuple[str | None, UsageEntry | ModelEntry] return [(entry.get("model"), entry)] +def _bound(cost_usd: float | None, lower: bool, upper: bool) -> Bound: + if cost_usd is None: + return Bound.UNPRICED + if lower and upper: + return Bound.ESTIMATED + if lower: + return Bound.AT_LEAST + return Bound.AT_MOST if upper else Bound.EXACT + + def _rank(role: str) -> int: return _ROLES.index(role) if role in _ROLES else len(_ROLES) diff --git a/tst/unit/task/usage/summary_test.py b/tst/unit/task/usage/summary_test.py index 8e7676431..095b1d321 100644 --- a/tst/unit/task/usage/summary_test.py +++ b/tst/unit/task/usage/summary_test.py @@ -1,11 +1,13 @@ """A run's ledger summed for people: by role, then by model, an entry's per-model rows split along their models, -unpriced usage counted apart and never as $0, and a partial or running entry making the total a lower bound; and the -lines the run summaries print from it.""" +unpriced usage counted apart and never as $0, and a partial or running entry making the total a lower bound; its +bound word and JSON shape; and the lines the run summaries print from it.""" + +import json import pytest from agent_env.cli.usage_output import cost_line, sources_line -from agent_env.task.usage.summary import summarize +from agent_env.task.usage.summary import Bound, summarize def _entry(role, model, input_tokens, output_tokens, cost, attempt=0, **more): @@ -18,6 +20,10 @@ def _shares(summary): return [(s.role, s.model, s.input_tokens, s.output_tokens, s.cost_usd, s.unpriced, s.partial) for s in summary.shares] +def _bounds(summary): + return summary.bound, [share.bound for share in summary.shares] + + def test_a_ledger_is_split_by_role_in_order_then_by_model_and_summed_across_steps(): summary = summarize([ _entry("judge", "claude-sonnet-4-6", 2900, 120, 0.0104), @@ -31,6 +37,8 @@ def test_a_ledger_is_split_by_role_in_order_then_by_model_and_summed_across_step ("user_simulator", "gpt-4.1-nano", 16_000, 210, 0.0016, False, False), ("judge", "claude-sonnet-4-6", 2900, 120, 0.0104, False, False)] assert summary.cost_usd == pytest.approx(0.0532) and not summary.lower_bound + assert _bounds(summary) == (Bound.EXACT, [Bound.EXACT] * 3) + assert (summary.input_tokens, summary.output_tokens) == (133_900, 1530) assert (summary.attempts, summary.sources) == (1, ("litellm@1.80.0",)) assert cost_line(summary) == ("cost: $0.0532 (solver gpt-4.1-mini $0.0412, 115k in, 1.2k out; user simulator " "gpt-4.1-nano $0.0016, 16k in, 210 out; judge claude-sonnet-4-6 $0.0104, 2.9k in, " @@ -47,6 +55,7 @@ def test_an_entry_with_per_model_rows_splits_along_them(): assert [(s.model, s.input_tokens, s.cost_usd) for s in summary.shares] == [ ("claude-haiku-4-5", 3000, 0.0035), ("claude-sonnet-4-6", 9000, 0.0118)] assert summary.cost_usd == pytest.approx(0.0153) + assert _bounds(summary) == (Bound.EXACT, [Bound.EXACT, Bound.EXACT]) def test_unpriced_usage_is_counted_apart_never_as_nothing_and_makes_the_total_a_lower_bound(): @@ -54,6 +63,8 @@ def test_unpriced_usage_is_counted_apart_never_as_nothing_and_makes_the_total_a_ _entry("judge", "mystery-1", 3100, 90, None, unpriced_reason="no_price")]) assert summary.cost_usd == 0.0004 and summary.lower_bound and summary.sources == ("litellm@1.80.0",) + assert _bounds(summary) == (Bound.AT_LEAST, [Bound.EXACT, Bound.UNPRICED]) + assert _bounds(summarize([_entry("judge", "mystery-1", 3100, 90, None)])) == (Bound.UNPRICED, [Bound.UNPRICED]) assert cost_line(summary) == ("cost: at least $0.0004 (solver gpt-4.1-mini $0.0004, 1.0k in, 10 out; judge " "mystery-1 unpriced, 3.1k in, 90 out)") assert cost_line(summarize([_entry("judge", "mystery-1", 3100, 90, None)])) == ( @@ -65,6 +76,9 @@ def test_a_cost_priced_on_an_assumed_rate_is_at_most_and_with_uncounted_usage_an summary = summarize([assumed, _entry("judge", "j", 100, 1, 0.0001)]) assert summary.upper_bound and not summary.lower_bound + assert _bounds(summary) == (Bound.AT_MOST, [Bound.AT_MOST, Bound.EXACT]) + assert _bounds(summarize([assumed, _entry("solver", "gpt-4.1-mini", 100, 1, None)])) == ( + Bound.ESTIMATED, [Bound.ESTIMATED]) assert cost_line(summary) == ("cost: at most $0.0005 (solver gpt-4.1-mini at most $0.0004, 1.0k in, 10 out; judge " "j $0.0001, 100 in, 1 out)") assert cost_line(summarize([assumed, _entry("judge", "mystery-1", 100, 1, None)])).startswith( @@ -82,6 +96,7 @@ def test_a_per_model_row_priced_on_an_assumed_rate_bounds_its_own_share(): summary = summarize([_entry("solver", "a", 12, 2, 0.3, cost_assumed=["cache_write_rate"], models=rows)]) assert [(share.model, share.assumed) for share in summary.shares] == [("a", True), ("b", False)] + assert _bounds(summary) == (Bound.AT_MOST, [Bound.AT_MOST, Bound.EXACT]) assert cost_line(summary) == ("cost: at most $0.3000 (solver a at most $0.2000, 9 in, 1 out; solver b $0.1000, 3 in, " "1 out)") @@ -90,6 +105,7 @@ def test_a_partial_or_running_entry_makes_its_share_partial_and_the_total_a_lowe for mark in ({"partial": True}, {"running": True}): summary = summarize([_entry("solver", "gpt-4.1-mini", 1000, 10, 0.0004, **mark)]) assert summary.lower_bound and summary.shares[0].partial + assert _bounds(summary) == (Bound.AT_LEAST, [Bound.AT_LEAST]) assert cost_line(summary) == ("cost: at least $0.0004 (solver gpt-4.1-mini at least $0.0004, 1.0k in, 10 out, " "partial)") @@ -99,6 +115,7 @@ def test_every_attempt_counts_and_is_named_when_there_were_more_than_one(): _entry("solver", "gpt-4.1-mini", 2000, 20, 0.0008, attempt=1)]) assert (summary.attempts, summary.shares[0].input_tokens, summary.cost_usd) == (2, 3000, pytest.approx(0.0012)) + assert _bounds(summary) == (Bound.EXACT, [Bound.EXACT]) assert cost_line(summary).startswith("cost: $0.0012 (2 attempts; solver gpt-4.1-mini $0.0012, 3.0k in, 30 out") assert "attempts" not in cost_line(summary, "cost over 1 run", attempts=False) @@ -112,6 +129,7 @@ def test_runs_ledgers_together_are_an_evals_total_by_role_and_model(): assert [(s.role, s.model, s.input_tokens, s.cost_usd, s.unpriced) for s in total.shares] == [ ("solver", "gpt-4.1-mini", 3000, pytest.approx(0.0012), False), ("judge", "mystery-1", 500, None, True)] assert total.cost_usd == pytest.approx(0.0012) and total.lower_bound + assert _bounds(total) == (Bound.AT_LEAST, [Bound.EXACT, Bound.UNPRICED]) assert summarize([]) is None and cost_line(None) is None @@ -119,6 +137,32 @@ def test_counts_and_costs_read_at_a_glance(): summary = summarize([_entry("solver", "m", 2_500_000, 999, 12.5), _entry("judge", "j", None, None, 0.00002)]) assert cost_line(summary) == "cost: $12.5000 (solver m $12.5000, 2.5M in, 999 out; judge j under $0.0001)" + assert _bounds(summary) == (Bound.EXACT, [Bound.EXACT, Bound.EXACT]) + assert (summary.input_tokens, summary.output_tokens) == (2_500_000, 999) + + +def test_a_summary_is_one_json_shape_with_the_bound_word_on_its_total_and_each_share(): + summary = summarize([ + _entry("solver", "gpt-4.1-mini", 1000, 10, 0.0004, cost_assumed=["cache_read_rate"]), + _entry("solver", "gpt-4.1-mini", 200, 2, 0.0001, running=True, attempt=1), + _entry("judge", "mystery-1", 300, 3, None, unpriced_reason="no_price"), + {**_entry("user_simulator", "gpt-4.1-nano", None, None, 0.0002), "cost_source": "harness"}, + ]) + + shape = summary.to_dict() + + assert shape == { + "cost_usd": pytest.approx(0.0007), "bound": "estimated", "input_tokens": 1500, "output_tokens": 15, + "attempts": 2, "sources": ["harness", "litellm@1.80.0"], + "shares": [ + {"role": "solver", "model": "gpt-4.1-mini", "cost_usd": pytest.approx(0.0005), "bound": "estimated", + "input_tokens": 1200, "output_tokens": 12, "unpriced": False, "assumed": True, "partial": True}, + {"role": "user_simulator", "model": "gpt-4.1-nano", "cost_usd": 0.0002, "bound": "exact", + "input_tokens": None, "output_tokens": None, "unpriced": False, "assumed": False, "partial": False}, + {"role": "judge", "model": "mystery-1", "cost_usd": None, "bound": "unpriced", "input_tokens": 300, + "output_tokens": 3, "unpriced": True, "assumed": False, "partial": False}]} + assert json.loads(json.dumps(shape)) == shape + assert summary.to_dict(attempts=False)["attempts"] is None def test_the_closing_line_names_each_source_of_the_costs():