From d8e5432a38e410e46bdc796c933291d6dc65f04c Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 20:06:07 -0800 Subject: [PATCH 1/7] feat(cli): a run's usage and cost by role and model where runs end Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 7 +- src/agent_env/bundle/run.py | 21 +++- src/agent_env/cli/eval/run.py | 12 ++ src/agent_env/cli/run.py | 9 ++ src/agent_env/cli/task/run.py | 17 +++ src/agent_env/cli/usage_output.py | 64 ++++++++++ src/agent_env/task/usage/summary.py | 111 ++++++++++++++++++ .../cli/run_usage_by_model_test.py | 12 +- tst/unit/bundle/run_test.py | 60 +++++++++- tst/unit/cli/submit_runs_test.py | 36 ++++++ tst/unit/task/usage/summary_test.py | 106 +++++++++++++++++ 11 files changed, 448 insertions(+), 7 deletions(-) create mode 100644 src/agent_env/cli/usage_output.py create mode 100644 src/agent_env/task/usage/summary.py create mode 100644 tst/unit/task/usage/summary_test.py diff --git a/AGENTS.md b/AGENTS.md index 20a67ced5..099804269 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -399,9 +399,10 @@ orchestrators call it the same way. What callers rely on: spend and a worker that dies mid-step keeps it. Those entries are marked `running`, which makes `usage_total.partial` true, as the turn in flight isn't in them; such a write never takes an entry back (`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. 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. + 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. 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/bundle/run.py b/src/agent_env/bundle/run.py index df39f0f49..04998a4f8 100644 --- a/src/agent_env/bundle/run.py +++ b/src/agent_env/bundle/run.py @@ -30,12 +30,13 @@ from agent_env.providers import build_sandbox_provider from agent_env.store.base import NotFoundError from agent_env.store.routing import namespace_routing, run_scope -from agent_env.task.store import record_task_cancelled +from agent_env.task.store import find_task_instance, record_task_cancelled from agent_env.task.interrupts import Interrupts from agent_env.task.lint import said from agent_env.utils.progress import run_progress from agent_env.task.task import Task, recorded_scores from agent_env.task.teardown import TeardownReport, attempt_epoch, record_teardown, teardown_run +from agent_env.task.usage.summary import UsageSummary, summarize from agent_env.task_step.context import TaskStepContext, sandbox_overrides from .hub import SOURCE_KEY, HubSource @@ -75,6 +76,7 @@ class TaskRun: started: bool = True # False when it was cancelled before it started torn_down: TeardownReport | None = None # None while its sandboxes are kept up attempt_epoch: int | None = None # its instance's as its teardown began, which ``record_teardown`` is fenced by + usage: tuple[dict, ...] = () # its instance's ledger once the run ended, every attempt's entries @property def instance_id(self) -> str | None: @@ -97,6 +99,11 @@ def models(self) -> dict[str, dict[str, str | None]]: """The model each step asked for, by role then step id; None leaves it to the agent.""" return self.context.metadata.get("models") or {} + @property + def usage_summary(self) -> UsageSummary | None: + """The run's usage by role and model, from its ledger; None when it recorded none.""" + return summarize(self.usage) + @property def outcome(self) -> Outcome: if self.cancelled: @@ -276,6 +283,7 @@ def run_bundle( source)) _mark_cancelled(runs, interrupts.reason) _record_teardowns(runs) + runs = _with_usage(runs) result = _bundle_run(plan, prepared.materialization, runs, _skipped(plan, entries, every=not tasks and not evals)) if not interrupts.count: @@ -390,6 +398,17 @@ def _mark_cancelled(runs: tuple[TaskRun, ...], reason: str) -> None: record_task_cancelled(run.instance_id, reason, Task._utc_now_str()) +def _with_usage(runs: tuple[TaskRun, ...]) -> tuple[TaskRun, ...]: + """Each run with its instance's ledger, read once the run's last write has landed.""" + def read(run: TaskRun) -> TaskRun: + if not run.instance_id: + return run + with run_scope(run.task.id): + instance = find_task_instance(run.instance_id) + return replace(run, usage=tuple(instance.usage)) if instance is not None else run + return tuple(read(run) for run in runs) + + def _record_teardowns(runs: Sequence[TaskRun]) -> None: """Keep on each run's instance the context its teardown ended with, so ``agent-env task teardown`` finds what it left up, those a step a signal cut short had recorded included, and nothing once all is down. Like diff --git a/src/agent_env/cli/eval/run.py b/src/agent_env/cli/eval/run.py index 56de0569d..39040355f 100644 --- a/src/agent_env/cli/eval/run.py +++ b/src/agent_env/cli/eval/run.py @@ -10,8 +10,10 @@ from agent_env.cli import submitted_runs from agent_env.cli.banner import print_banner from agent_env.cli.identity import get_agent_env_client_id +from agent_env.cli.usage_output import cost_line, sources_line from agent_env.store.ids import fs_safe from agent_env.task.interrupts import Interrupts +from agent_env.task.usage.summary import combine, summarize from agent_env.task_step.context import TaskStepContext @@ -97,10 +99,12 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, # Summarize results failures = [] successes = [] + usage = {} for run in runs: context = run.instance.context if run.instance else None if output_dir and context is not None: _write_context(TaskStepContext.from_dict(context), run.task.id, output_dir, prefix=f"{run.tag} ") + usage[run.tag] = summarize(run.instance.usage) if run.instance else None if run.completed: successes.append((run.tag, (context or {}).get("metadata", {}).get("score"))) else: @@ -111,16 +115,24 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, for tag, score in successes: score_str = f" score={score}" if score is not None else "" click.echo(click.style(f" {tag} PASSED{score_str}", fg="green")) + if cost := cost_line(usage[tag]): + click.echo(f" {cost}") if len(successes) < total_runs: for tag, outcome in failures: click.echo(click.style(f" {tag} {outcome}", fg="red")) + if cost := cost_line(usage[tag]): + click.echo(f" {cost}") click.echo(click.style( f"\n{len(successes)}/{total_runs} runs completed, {total_runs - len(successes)}/{total_runs} failed.", fg="red", )) else: click.echo(click.style(f"\nAll {total_runs} runs completed!", fg="blue")) + if cost := cost_line(combine(usage.values()), f"Cost over {len(runs)} runs", attempts=False): + click.echo(cost) + if sources := sources_line(usage.values()): + click.echo(sources) if interrupts.count: raise SystemExit(128 + interrupts.signum) if len(successes) < total_runs: diff --git a/src/agent_env/cli/run.py b/src/agent_env/cli/run.py index c69644fe6..6252a018d 100644 --- a/src/agent_env/cli/run.py +++ b/src/agent_env/cli/run.py @@ -17,11 +17,13 @@ from agent_env.bundle.requires import UnmetRequirements from agent_env.cli._install_prompt import offer_to_install from agent_env.cli.teardown_output import echo_finish_teardown, gone +from agent_env.cli.usage_output import cost_line, sources_line from agent_env.plugins._bundles import ALIAS_TABLES, installed_aliases from agent_env.plugins._discovery import discovery_error from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandbox from agent_env.task.interrupts import Interrupts from agent_env.task.teardown import TORN_DOWN_KEY, RecordedSandbox, TeardownReport, kind, recorded_sandboxes, sandbox_ids +from agent_env.task.usage.summary import combine from agent_env.task_step.context import TaskStepContext _COLORS = {Outcome.PASSED: "green", Outcome.BELOW_ONE: "yellow", Outcome.UNSCORED: "yellow", Outcome.FAILED: "red", @@ -202,6 +204,8 @@ def _summarize(result: BundleRun, verbose: bool) -> None: click.echo(click.style(f" {_described(result, run)}", fg=_COLORS[run.outcome])) if models := _models(run): click.echo(f" models: {models}") + if cost := cost_line(run.usage_summary): + click.echo(f" {cost}") if result.evals: click.echo("Evals:") for eval_run in result.evals: @@ -210,9 +214,14 @@ def _summarize(result: BundleRun, verbose: bool) -> None: line = f" {result.path(eval_run.entry)} v{eval_run.version}: {passed} of {len(eval_run.runs)} passed" rest = [f"{failed} failed" if failed else "", f"{cancelled} cancelled" if cancelled else ""] click.echo(", ".join([line, *filter(None, rest)])) + if cost := cost_line(combine(run.usage_summary for run in eval_run.runs), + f"cost over {len(eval_run.runs)} runs", attempts=False): + click.echo(f" {cost}") for entry in result.skipped: click.echo(f"{result.path(entry)} isn't named by any eval, so it didn't run; run it with " f"--task {shlex.quote(entry.name)}") + if sources := sources_line(run.usage_summary for run in result.runs): + click.echo(sources) if verbose: _print_tracebacks(result) diff --git a/src/agent_env/cli/task/run.py b/src/agent_env/cli/task/run.py index 64aff5183..b30f0e966 100644 --- a/src/agent_env/cli/task/run.py +++ b/src/agent_env/cli/task/run.py @@ -19,6 +19,7 @@ from agent_env.cli import submitted_runs from agent_env.cli.identity import get_agent_env_client_id from agent_env.cli.teardown_output import echo_finish_teardown, echo_teardown, gone +from agent_env.cli.usage_output import cost_line, sources_line from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandbox from agent_env.runner.runner import KEEP_KEY, RunStatus from agent_env.store.ids import derive_id, fs_safe, is_local_id, validate_local_id @@ -26,6 +27,7 @@ from agent_env.task.interrupts import Interrupts from agent_env.task.store import get_task_instance_store, new_instance_id from agent_env.task.teardown import TeardownReport, attempt_epoch, kind, record_teardown, teardown_run +from agent_env.task.usage.summary import combine, summarize from agent_env.task_step.context import TaskStepContext, read_dual_keyed from agent_env.task_step.task_steps.deploy_agent import DeployAgentTaskStep from agent_env.task_step.context_ops import build_context_update_ops @@ -480,6 +482,7 @@ def run(task_id: str, task_version: int | None, output_dir: str | None, k: int, click.echo(click.style("Task completed!" if k == 1 else f"All {k} runs completed!", fg="blue")) elif k > 1: click.echo(click.style(f"{completed}/{k} runs completed, {k - completed}/{k} failed.", fg="red")) + _echo_usage(runs, k) if keep: _settle_kept(_ended(runs), interrupts, interrupted) if interrupted is not None: @@ -488,6 +491,20 @@ def run(task_id: str, task_version: int | None, output_dir: str | None, k: int, raise SystemExit(1) +def _echo_usage(runs, k: int) -> None: + """Each run's cost by role and model from its ledger, the runs' total when there were several, and where the costs + came from.""" + summaries = [(run.tag, summarize(run.instance.usage) if run.instance else None) for run in runs] + for tag, summary in summaries: + if cost := cost_line(summary): + click.echo(f"{tag} {cost}" if tag else cost) + if k > 1 and (cost := cost_line(combine(summary for _, summary in summaries), f"Cost over {k} runs", + attempts=False)): + click.echo(cost) + if sources := sources_line(summary for _, summary in summaries): + click.echo(sources) + + def _runnable(task_id: str, task_version: int | None, metadata: dict): """The stored task, checked before the first step a run with ``metadata`` runs (``runnable_task``); a refusal for what it requires offers, in a terminal, to install it and run the command again.""" diff --git a/src/agent_env/cli/usage_output.py b/src/agent_env/cli/usage_output.py new file mode 100644 index 000000000..a1156e272 --- /dev/null +++ b/src/agent_env/cli/usage_output.py @@ -0,0 +1,64 @@ +"""How the run summaries print a run's usage (``task.usage.summary``): one cost line per run and one closing line +naming where the costs came from.""" + +from __future__ import annotations + +from collections.abc import Iterable + +from agent_env.task.usage.summary import Share, UsageSummary + +_ROLE_NAMES = {"user_simulator": "user simulator"} +# The cost sources that aren't the price map, as ``cost_source`` names them, in the order they're named. +_REPORTED = (("provider", "the endpoint's bills"), ("harness", "agents' own figures")) + + +def cost_line(summary: UsageSummary | None, label: str = "cost", attempts: bool = True) -> str | None: + """``cost: $0.0532 (solver gpt-4.1-mini $0.0412, 115k in, 1.2k out; judge ...)``, ``at least`` when the cost is a + lower bound and, with ``attempts``, the attempts named when there were more than one; None for no usage.""" + if summary is None: + return None + total = "unpriced" if summary.cost_usd is None else _dollars(summary.cost_usd) + if summary.lower_bound and summary.cost_usd is not None: + total = f"at least {total}" + parts = [f"{summary.attempts} attempts"] if attempts and summary.attempts > 1 else [] + return f"{label}: {total} ({'; '.join([*parts, *map(_share, summary.shares)])})" + + +def sources_line(summaries: Iterable[UsageSummary | None]) -> str | None: + """Where the summaries' costs came from, as ``Costs priced from LiteLLM's price map, litellm@1.80.0.``; None when + none was priced.""" + sources = {source for summary in summaries if summary is not None for source in summary.sources} + if not sources: + return None + named = [f"LiteLLM's price map, {source}" for source in sorted(sources) if source.startswith("litellm@")] + named += [name for source, name in _REPORTED if source in sources] + named += sorted(source for source in sources if not source.startswith("litellm@") and source not in dict(_REPORTED)) + return f"Costs priced from {'; '.join(named)}." + + +def _share(share: Share) -> str: + cost = "unpriced" if share.cost_usd is None else _dollars(share.cost_usd) + if share.unpriced and share.cost_usd is not None: + cost = f"at least {cost}" + words = [f"{_ROLE_NAMES.get(share.role, share.role)} {share.model or 'an unnamed model'} {cost}"] + if share.input_tokens is not None: + words.append(f"{_count(share.input_tokens)} in") + if share.output_tokens is not None: + words.append(f"{_count(share.output_tokens)} out") + if share.partial: + words.append("partial") + return ", ".join(words) + + +def _dollars(usd: float) -> str: + return "$0" if usd == 0 else f"${usd:.4f}" if usd >= 0.0001 else "under $0.0001" + + +def _count(n: int) -> str: + if n < 1000: + return str(n) + if n < 10_000: + return f"{n / 1000:.1f}k" + if n < 1_000_000: + return f"{round(n / 1000)}k" + return f"{n / 1_000_000:.1f}M" diff --git a/src/agent_env/task/usage/summary.py b/src/agent_env/task/usage/summary.py new file mode 100644 index 000000000..9f99afa6c --- /dev/null +++ b/src/agent_env/task/usage/summary.py @@ -0,0 +1,111 @@ +"""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 total a lower bound, as a partial or a still running entry does.""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass + +# The order roles are shown in; any other comes after them. +ROLES = ("solver", "user_simulator", "judge") + + +@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 + priced, with ``unpriced`` when some part had no cost and ``partial`` when its counts are a lower bound (a partial or + a still running entry).""" + + role: str + model: str | None + input_tokens: int | None = None + output_tokens: int | None = None + cost_usd: float | None = None + unpriced: bool = False + partial: bool = False + + def add(self, part: Mapping) -> None: + self.input_tokens = _plus(self.input_tokens, part.get("input_tokens")) + self.output_tokens = _plus(self.output_tokens, part.get("output_tokens")) + cost = part.get("cost_usd") + if _number(cost): + self.cost_usd = (self.cost_usd or 0.0) + cost + else: + self.unpriced = True + + +@dataclass(frozen=True) +class UsageSummary: + """A ledger summed: its shares in role order, the cost of everything priced (None when nothing was), whether that + cost is a lower bound, how many attempts the ledger holds, and where its costs came from (``cost_source``).""" + + shares: tuple[Share, ...] + cost_usd: float | None + lower_bound: bool + attempts: int + sources: tuple[str, ...] + + +def summarize(ledger: Iterable[Mapping]) -> UsageSummary | None: + """``ledger``'s entries, a task instance's ``usage``, summed by role and model; None when it has none.""" + entries = [entry for entry in ledger if isinstance(entry, Mapping)] + if not entries: + return None + shares: dict[tuple[str, str | None], Share] = {} + sources: set[str] = set() + for entry in entries: + role = str(entry.get("role") or "unknown") + for model, part in _parts(entry): + share = shares.setdefault((role, model), Share(role, model)) + share.add(part) + share.partial = share.partial or bool(entry.get("partial") or entry.get("running")) + if _number(part.get("cost_usd")) and part.get("cost_source"): + sources.add(part["cost_source"]) + ordered = sorted(shares.values(), key=lambda share: (_rank(share.role), share.role, share.model or "")) + priced = [share.cost_usd for share in ordered if share.cost_usd is not None] + lower_bound = any(share.unpriced or share.partial for share in ordered) + return UsageSummary(shares=tuple(ordered), cost_usd=sum(priced) if priced else None, lower_bound=lower_bound, + attempts=len({entry.get("attempt") for entry in entries}), sources=tuple(sorted(sources))) + + +def combine(summaries: Iterable[UsageSummary | None]) -> UsageSummary | None: + """Several runs' summaries as one, as an eval's total: their shares summed by role and model.""" + present = [summary for summary in summaries if summary is not None] + if not present: + return None + shares: dict[tuple[str, str | None], Share] = {} + for summary in present: + for share in summary.shares: + total = shares.setdefault((share.role, share.model), Share(share.role, share.model)) + total.input_tokens = _plus(total.input_tokens, share.input_tokens) + total.output_tokens = _plus(total.output_tokens, share.output_tokens) + if share.cost_usd is not None: + total.cost_usd = (total.cost_usd or 0.0) + share.cost_usd + total.unpriced = total.unpriced or share.unpriced + total.partial = total.partial or share.partial + ordered = sorted(shares.values(), key=lambda share: (_rank(share.role), share.role, share.model or "")) + priced = [summary.cost_usd for summary in present if summary.cost_usd is not None] + return UsageSummary(shares=tuple(ordered), cost_usd=sum(priced) if priced else None, + lower_bound=any(summary.lower_bound for summary in present), + attempts=sum(summary.attempts for summary in present), + sources=tuple(sorted({source for summary in present for source in summary.sources}))) + + +def _parts(entry: Mapping) -> list[tuple[str | None, Mapping]]: + rows = entry.get("models") + if isinstance(rows, list) and rows: + return [(row.get("model") or entry.get("model"), row) for row in rows if isinstance(row, Mapping)] + return [(entry.get("model"), entry)] + + +def _rank(role: str) -> int: + return ROLES.index(role) if role in ROLES else len(ROLES) + + +def _number(value: object) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) + + +def _plus(total: int | None, value: object) -> int | None: + return total if not _number(value) else (total or 0) + int(value) diff --git a/tst/integration/cli/run_usage_by_model_test.py b/tst/integration/cli/run_usage_by_model_test.py index f1f2d378d..b6347ebe1 100644 --- a/tst/integration/cli/run_usage_by_model_test.py +++ b/tst/integration/cli/run_usage_by_model_test.py @@ -1,7 +1,7 @@ """A turn whose agent reports its counts by model (``Usage.models``) is priced model by model, each at its own rate from LiteLLM's price map, end to end: the echo agent (tst/data/a2a_agent) sends the breakdown over A2A, the host reads -it, the prompt step's entry keeps a row per model, and the task instance's ledger totals what the rows cost. Builds -the echo agent; needs Docker.""" +it, the prompt step's entry keeps a row per model, the task instance's ledger totals what the rows cost, and the run's +summary splits it by model as ``agent-env run`` prints it. Builds the echo agent; needs Docker.""" import json import logging @@ -13,6 +13,7 @@ from agent_env.artifact.store import reset_artifact_store from agent_env.bundle import run_bundle +from agent_env.cli.usage_output import cost_line from agent_env.config import configure, reset_config from agent_env.config.model_pricing import ReportedBy, Tokens, litellm_prices, price from agent_env.providers.sandbox_providers.sandbox_provider import ( @@ -91,3 +92,10 @@ def test_a_turns_counts_by_model_are_priced_at_each_models_rate_and_reach_the_le with namespace_routing(): instance = get_task_instance_store().get(run.context.instance_id) assert instance.usage_total["cost_usd"] == pytest.approx(sum(expected)) + summary = run.usage_summary + assert [(share.role, share.model) for share in summary.shares] == [("solver", "gpt-4.1-mini"), + ("solver", "gpt-4o-mini")] + assert summary.cost_usd == pytest.approx(sum(expected)) and not summary.lower_bound + line = cost_line(summary) + assert line.startswith("cost: $") and "solver gpt-4.1-mini $" in line and "9.0k in, 400 out" in line + assert "solver gpt-4o-mini $" in line and "3.0k in, 90 out" in line diff --git a/tst/unit/bundle/run_test.py b/tst/unit/bundle/run_test.py index fec9aa31e..94e677656 100644 --- a/tst/unit/bundle/run_test.py +++ b/tst/unit/bundle/run_test.py @@ -7,6 +7,7 @@ import re import pytest +from agentenv_protocol.a2a_agent import Usage from click.testing import CliRunner import agent_env.bundle.run as run_module @@ -24,9 +25,14 @@ from agent_env.entity.refs import EntityRef from agent_env.store import Filter from agent_env.store.routing import namespace_routing +from agent_env.a2a_agent.protocol import TerminalResponse +from agent_env.config.model import ModelRole +from agent_env.config.model_pricing import ModelPrice, PriceTable from agent_env.task import Task from agent_env.task_step.context import TaskStepContext from agent_env.task_step.task_step import TaskStep +from agent_env.task_step import usage as usage_module +from agent_env.task_step.usage import StepUsage from tst.unit.bundle._support import fake_plugins, layout, local_store, plan_of ROOT = "@local/~/triage" @@ -80,6 +86,22 @@ async def execute(self, context): raise asyncio.CancelledError +class _Spends(_Scored): + """Records a solver turn of 1,000 input and 10 output tokens on gpt-4.1-mini and a judge call of 500 and 20 on + judge-1, as a prompt step and a judge record theirs.""" + + type = "spends_run_test" + + async def execute(self, context): + usage = StepUsage(context, self.id) + usage.start(ModelRole.SOLVER, "gpt-4.1-mini", None) + usage.turn(ModelRole.SOLVER, TerminalResponse(response_text="", usage=Usage( + input_tokens=1000, output_tokens=10, input_includes_cache=True))) + usage.call(ModelRole.JUDGE, Usage(input_tokens=500, output_tokens=20, input_includes_cache=True), + model="judge-1", endpoint_host=None) + return context + + class _RecordsModels(_Scored): """Records the models its solver, user simulator and judge ask for, as the real steps do.""" @@ -137,7 +159,7 @@ def _scored(score): @pytest.fixture(autouse=True) def registries(monkeypatch): steps = {**Config().task_step_registry(), - **{cls.type: cls for cls in (_Scored, _Failing, _Cancelled, _NamesAgent, _RecordsModels)}} + **{cls.type: cls for cls in (_Scored, _Failing, _Cancelled, _NamesAgent, _RecordsModels, _Spends)}} monkeypatch.setattr(Config, "task_step_registry", lambda self: steps) fake_plugins(monkeypatch) # no installed package ships these classes monkeypatch.setattr(_Scored, "seen", []) @@ -483,6 +505,42 @@ def test_the_cli_runs_each_role_on_its_model_names_them_and_a_rerun_on_others_wr assert (bundle_dir / "tasks" / "models.json").read_text() == written +@pytest.fixture +def prices(monkeypatch): + """gpt-4.1-mini at $0.40 and $1.60 per million input and output tokens, judge-1 at $3 and $15.""" + monkeypatch.setattr(usage_module, "litellm_prices", lambda: PriceTable({ + "gpt-4.1-mini": ModelPrice(input=0.4, output=1.6), "judge-1": ModelPrice(input=3.0, output=15.0)}, + "litellm@test")) + + +def test_a_runs_usage_is_its_ledger_split_by_role_and_model(bundle_dir, prices): + layout(bundle_dir, {"tasks/spends.json": json.dumps([{"id": "spend", "type": "spends_run_test"}])}) + + (run,) = run_bundle(bundle_dir, tasks=["spends"]).runs + + assert {(entry["role"], entry["model"]) for entry in run.usage} == { + ("solver", "gpt-4.1-mini"), ("judge", "judge-1")} + summary = run.usage_summary + assert [(share.role, share.model, share.input_tokens, share.output_tokens) for share in summary.shares] == [ + ("solver", "gpt-4.1-mini", 1000, 10), ("judge", "judge-1", 500, 20)] + assert summary.cost_usd == pytest.approx(0.000416 + 0.0018) and not summary.lower_bound + assert summary.sources == ("litellm@test",) + + +def test_the_cli_prints_each_runs_cost_by_role_and_model_and_an_evals_total(bundle_dir, prices, quiet_logs): + layout(bundle_dir, {"tasks/spends.json": json.dumps([{"id": "spend", "type": "spends_run_test"}]), + "evals/spending.toml": 'tasks = ["spends", "a"]\n'}) + + result = CliRunner().invoke(cli, ["run", str(bundle_dir), "--eval", "spending"]) + + assert result.exit_code == 0, result.output + lines = result.output.splitlines() + cost = ("cost: $0.0022 (solver gpt-4.1-mini $0.0004, 1.0k in, 10 out; judge judge-1 $0.0018, 500 in, 20 out)") + assert f" {cost}" in lines + assert f" {cost.replace('cost:', 'cost over 2 runs:')}" in lines + assert lines[-1] == "Costs priced from LiteLLM's price map, litellm@test." + + def test_the_cli_exits_0_when_no_run_failed_even_if_one_scored_below_1(bundle_dir, quiet_logs): result = CliRunner().invoke(cli, ["run", str(bundle_dir), "--eval", "smoke"]) diff --git a/tst/unit/cli/submit_runs_test.py b/tst/unit/cli/submit_runs_test.py index dd2bfa8b2..a9951d350 100644 --- a/tst/unit/cli/submit_runs_test.py +++ b/tst/unit/cli/submit_runs_test.py @@ -19,6 +19,7 @@ from agent_env.runner import store as run_store from agent_env.runner.runner import RunHandle, Runner, RunRecord, RunStatus from agent_env.task import Task +from agent_env.task.store import get_task_instance_store, register_task_instance from agent_env.task.teardown import TeardownReport from agent_env.task_step.context import TaskStepContext @@ -186,3 +187,38 @@ def test_an_error_cancelling_after_ctrl_c_still_stops_the_runner(monkeypatch, lo assert isinstance(result.exception, RuntimeError) assert runner.stopped + + +class _Spends(_Task): + """Leaves one solver entry in its run's ledger, as a running step's write does.""" + + async def run(self, context, **kwargs): + register_task_instance(self.id, self.version, 0, instance_id=kwargs["instance_id"]) + get_task_instance_store().record_running_usage_sync(kwargs["instance_id"], [{ + "attempt": 0, "step_id": "ask", "role": "solver", "model": "gpt-4.1-mini", "turns": 1, "input_tokens": 1000, + "output_tokens": 10, "cost_usd": 0.0004, "cost_status": "priced", "cost_source": "litellm@test"}]) + return await super().run(context, **kwargs) + + +SPENT = "at least $0.0004 (solver gpt-4.1-mini $0.0004, 1.0k in, 10 out, partial)" + + +def test_an_eval_prints_each_runs_cost_and_their_total_from_the_ledgers(monkeypatch, tmp_path, torn_down): + monkeypatch.setattr(Eval, "get", classmethod(lambda cls, id, version=None: types.SimpleNamespace( + id="e", version=1, tasks=[types.SimpleNamespace(task_id="t", task_version=1)]))) + + result = _invoke(monkeypatch, _Spends(), "eval", "run", "--id", "e", "--k", "2") + + assert result.exit_code == 0, result.output + lines = result.output.splitlines() + assert lines.count(f" cost: {SPENT}") == 2 + assert "Cost over 2 runs: at least $0.0008 (solver gpt-4.1-mini $0.0008, 2.0k in, 20 out, partial)" in lines + assert lines[-1] == "Costs priced from LiteLLM's price map, litellm@test." + + +def test_a_task_run_prints_its_cost_from_the_ledger(monkeypatch, tmp_path, torn_down): + result = _invoke(monkeypatch, _Spends(), "task", "run", "--id", "t", "--output-dir", str(tmp_path)) + + assert result.exit_code == 0, result.output + assert f"cost: {SPENT}" in result.output.splitlines() + assert result.output.splitlines()[-1] == "Costs priced from LiteLLM's price map, litellm@test." diff --git a/tst/unit/task/usage/summary_test.py b/tst/unit/task/usage/summary_test.py new file mode 100644 index 000000000..2bc6210eb --- /dev/null +++ b/tst/unit/task/usage/summary_test.py @@ -0,0 +1,106 @@ +"""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.""" + +import pytest + +from agent_env.cli.usage_output import cost_line, sources_line +from agent_env.task.usage.summary import combine, summarize + + +def _entry(role, model, input_tokens, output_tokens, cost, attempt=0, **more): + return {"role": role, "model": model, "attempt": attempt, "step_id": "ask", "input_tokens": input_tokens, + "output_tokens": output_tokens, "cost_usd": cost, "cost_status": "priced" if cost is not None else "unpriced", + "cost_source": "litellm@1.80.0" if cost is not None else None, **more} + + +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 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), + _entry("solver", "gpt-4.1-mini", 100_000, 1000, 0.04), + _entry("user_simulator", "gpt-4.1-nano", 16_000, 210, 0.0016), + _entry("solver", "gpt-4.1-mini", 15_000, 200, 0.0012, step_id="follow"), + ]) + + assert _shares(summary) == [ + ("solver", "gpt-4.1-mini", 115_000, 1200, pytest.approx(0.0412), False, False), + ("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 (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, " + "120 out)") + + +def test_an_entry_with_per_model_rows_splits_along_them(): + rows = [{"model": "claude-sonnet-4-6", "input_tokens": 9000, "output_tokens": 400, "cost_usd": 0.0118, + "cost_source": "litellm@1.80.0"}, + {"model": "claude-haiku-4-5", "input_tokens": 3000, "output_tokens": 90, "cost_usd": 0.0035, + "cost_source": "litellm@1.80.0"}] + summary = summarize([_entry("solver", "claude-sonnet-4-6", 12_000, 490, 0.0153, models=rows)]) + + 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) + + +def test_unpriced_usage_is_counted_apart_never_as_nothing_and_makes_the_total_a_lower_bound(): + summary = summarize([_entry("solver", "gpt-4.1-mini", 1000, 10, 0.0004), + _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 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)])) == ( + "cost: unpriced (judge mystery-1 unpriced, 3.1k in, 90 out)") + + +def test_a_partial_or_running_entry_makes_its_share_partial_and_the_total_a_lower_bound(): + 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 cost_line(summary) == "cost: at least $0.0004 (solver gpt-4.1-mini $0.0004, 1.0k in, 10 out, partial)" + + +def test_every_attempt_counts_and_is_named_when_there_were_more_than_one(): + summary = summarize([_entry("solver", "gpt-4.1-mini", 1000, 10, 0.0004, attempt=0), + _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 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) + + +def test_runs_combine_into_an_evals_total_by_role_and_model(): + first = summarize([_entry("solver", "gpt-4.1-mini", 1000, 10, 0.0004)]) + second = summarize([_entry("solver", "gpt-4.1-mini", 2000, 20, 0.0008), + _entry("judge", "mystery-1", 500, 5, None)]) + + total = combine([first, None, second]) + + 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 combine([None]) is None and summarize([]) is None and cost_line(None) is None + + +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)" + + +def test_the_closing_line_names_each_source_of_the_costs(): + priced = summarize([_entry("solver", "m", 1, 1, 0.1)]) + reported = summarize([{**_entry("judge", "j", 1, 1, 0.2), "cost_source": "harness"}, + {**_entry("user_simulator", "u", 1, 1, 0.3), "cost_source": "provider"}]) + + assert sources_line([priced]) == "Costs priced from LiteLLM's price map, litellm@1.80.0." + assert sources_line([priced, reported]) == ("Costs priced from LiteLLM's price map, litellm@1.80.0; the endpoint's " + "bills; agents' own figures.") + assert sources_line([summarize([_entry("judge", "x", 1, 1, None)]), None]) is None From af1f864adc352c332d8dd0588dcdace58cae5373 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 20:31:10 -0800 Subject: [PATCH 2/7] fix(cli): an eval counts each run's cost though runs share a tag, and a failed usage read keeps the run Co-Authored-By: Claude Opus 5.5 --- src/agent_env/bundle/run.py | 11 ++++++++--- src/agent_env/cli/eval/run.py | 21 +++++++++++---------- src/agent_env/cli/usage_output.py | 3 ++- src/agent_env/task/usage/summary.py | 4 +++- tst/unit/bundle/run_test.py | 10 ++++++++++ tst/unit/cli/submit_runs_test.py | 6 ++++-- 6 files changed, 38 insertions(+), 17 deletions(-) diff --git a/src/agent_env/bundle/run.py b/src/agent_env/bundle/run.py index 04998a4f8..d6c88008b 100644 --- a/src/agent_env/bundle/run.py +++ b/src/agent_env/bundle/run.py @@ -399,12 +399,17 @@ def _mark_cancelled(runs: tuple[TaskRun, ...], reason: str) -> None: def _with_usage(runs: tuple[TaskRun, ...]) -> tuple[TaskRun, ...]: - """Each run with its instance's ledger, read once the run's last write has landed.""" + """Each run with its instance's ledger, read once the run's last write has landed. A read that fails leaves the + run without it, logged, since the result and the teardown after it matter more than the cost line.""" def read(run: TaskRun) -> TaskRun: if not run.instance_id: return run - with run_scope(run.task.id): - instance = find_task_instance(run.instance_id) + try: + with run_scope(run.task.id): + instance = find_task_instance(run.instance_id) + except Exception as e: + logger.warning("usage of %s not read: %r", run.instance_id, e) + return run return replace(run, usage=tuple(instance.usage)) if instance is not None else run return tuple(read(run) for run in runs) diff --git a/src/agent_env/cli/eval/run.py b/src/agent_env/cli/eval/run.py index 39040355f..6a434b065 100644 --- a/src/agent_env/cli/eval/run.py +++ b/src/agent_env/cli/eval/run.py @@ -99,29 +99,30 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, # Summarize results failures = [] successes = [] - usage = {} + usage = [] for run in runs: context = run.instance.context if run.instance else None if output_dir and context is not None: _write_context(TaskStepContext.from_dict(context), run.task.id, output_dir, prefix=f"{run.tag} ") - usage[run.tag] = summarize(run.instance.usage) if run.instance else None + summary = summarize(run.instance.usage) if run.instance else None + usage.append(summary) if run.completed: - successes.append((run.tag, (context or {}).get("metadata", {}).get("score"))) + successes.append((run.tag, (context or {}).get("metadata", {}).get("score"), summary)) else: - failures.append((run.tag, run.outcome if run.done else "CANCELLED")) + failures.append((run.tag, run.outcome if run.done else "CANCELLED", summary)) if successes: click.echo(click.style("Results:", fg="blue")) - for tag, score in successes: + for tag, score, summary in successes: score_str = f" score={score}" if score is not None else "" click.echo(click.style(f" {tag} PASSED{score_str}", fg="green")) - if cost := cost_line(usage[tag]): + if cost := cost_line(summary): click.echo(f" {cost}") if len(successes) < total_runs: - for tag, outcome in failures: + for tag, outcome, summary in failures: click.echo(click.style(f" {tag} {outcome}", fg="red")) - if cost := cost_line(usage[tag]): + if cost := cost_line(summary): click.echo(f" {cost}") click.echo(click.style( f"\n{len(successes)}/{total_runs} runs completed, {total_runs - len(successes)}/{total_runs} failed.", @@ -129,9 +130,9 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, )) else: click.echo(click.style(f"\nAll {total_runs} runs completed!", fg="blue")) - if cost := cost_line(combine(usage.values()), f"Cost over {len(runs)} runs", attempts=False): + if cost := cost_line(combine(usage), f"Cost over {len(runs)} runs", attempts=False): click.echo(cost) - if sources := sources_line(usage.values()): + if sources := sources_line(usage): click.echo(sources) if interrupts.count: raise SystemExit(128 + interrupts.signum) diff --git a/src/agent_env/cli/usage_output.py b/src/agent_env/cli/usage_output.py index a1156e272..0c542e56f 100644 --- a/src/agent_env/cli/usage_output.py +++ b/src/agent_env/cli/usage_output.py @@ -5,9 +5,10 @@ from collections.abc import Iterable +from agent_env.config.model import ModelRole from agent_env.task.usage.summary import Share, UsageSummary -_ROLE_NAMES = {"user_simulator": "user simulator"} +_ROLE_NAMES = {role.value: role.record_key for role in ModelRole} # The cost sources that aren't the price map, as ``cost_source`` names them, in the order they're named. _REPORTED = (("provider", "the endpoint's bills"), ("harness", "agents' own figures")) diff --git a/src/agent_env/task/usage/summary.py b/src/agent_env/task/usage/summary.py index 9f99afa6c..7f62b85cf 100644 --- a/src/agent_env/task/usage/summary.py +++ b/src/agent_env/task/usage/summary.py @@ -7,8 +7,10 @@ from collections.abc import Iterable, Mapping from dataclasses import dataclass +from agent_env.config.model import ModelRole + # The order roles are shown in; any other comes after them. -ROLES = ("solver", "user_simulator", "judge") +ROLES = tuple(role.value for role in ModelRole) @dataclass diff --git a/tst/unit/bundle/run_test.py b/tst/unit/bundle/run_test.py index 94e677656..4af4a808c 100644 --- a/tst/unit/bundle/run_test.py +++ b/tst/unit/bundle/run_test.py @@ -527,6 +527,16 @@ def test_a_runs_usage_is_its_ledger_split_by_role_and_model(bundle_dir, prices): assert summary.sources == ("litellm@test",) +def test_a_usage_read_that_fails_leaves_the_run_and_its_result_without_a_cost(bundle_dir, prices, monkeypatch): + layout(bundle_dir, {"tasks/spends.json": json.dumps([{"id": "spend", "type": "spends_run_test"}])}) + monkeypatch.setattr(run_module, "find_task_instance", lambda instance_id: (_ for _ in ()).throw( + ConnectionError("store unreachable"))) + + (run,) = run_bundle(bundle_dir, tasks=["spends"]).runs + + assert run.error is None and not run.cancelled and run.usage == () and run.usage_summary is None + + def test_the_cli_prints_each_runs_cost_by_role_and_model_and_an_evals_total(bundle_dir, prices, quiet_logs): layout(bundle_dir, {"tasks/spends.json": json.dumps([{"id": "spend", "type": "spends_run_test"}]), "evals/spending.toml": 'tasks = ["spends", "a"]\n'}) diff --git a/tst/unit/cli/submit_runs_test.py b/tst/unit/cli/submit_runs_test.py index a9951d350..e2e3c38d4 100644 --- a/tst/unit/cli/submit_runs_test.py +++ b/tst/unit/cli/submit_runs_test.py @@ -204,10 +204,12 @@ async def run(self, context, **kwargs): def test_an_eval_prints_each_runs_cost_and_their_total_from_the_ledgers(monkeypatch, tmp_path, torn_down): + """Two versions of one task, whose runs share a tag, each count.""" monkeypatch.setattr(Eval, "get", classmethod(lambda cls, id, version=None: types.SimpleNamespace( - id="e", version=1, tasks=[types.SimpleNamespace(task_id="t", task_version=1)]))) + id="e", version=1, tasks=[types.SimpleNamespace(task_id="t", task_version=1), + types.SimpleNamespace(task_id="t", task_version=2)]))) - result = _invoke(monkeypatch, _Spends(), "eval", "run", "--id", "e", "--k", "2") + result = _invoke(monkeypatch, _Spends(), "eval", "run", "--id", "e") assert result.exit_code == 0, result.output lines = result.output.splitlines() From b01976f7741df4e0c058b21eeed51598ab4de5d2 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 20:57:44 -0800 Subject: [PATCH 3/7] fix(cli): a cost priced on an assumed rate prints as at most, and with uncounted usage as estimated Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 7 ++++--- src/agent_env/cli/usage_output.py | 20 ++++++++++++-------- src/agent_env/task/usage/summary.py | 16 ++++++++++++---- tst/unit/bundle/run_test.py | 27 ++++++++++++++++++++++++++- tst/unit/task/usage/summary_test.py | 25 +++++++++++++++++++++++++ 5 files changed, 79 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 099804269..6a311b0ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -400,9 +400,10 @@ orchestrators call it the same way. What callers rely on: `usage_total.partial` true, as the turn in flight isn't in them; such a write never takes an entry back (`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. 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. + (`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. - 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 0c542e56f..7fddfa76f 100644 --- a/src/agent_env/cli/usage_output.py +++ b/src/agent_env/cli/usage_output.py @@ -14,13 +14,12 @@ def cost_line(summary: UsageSummary | None, label: str = "cost", attempts: bool = True) -> str | None: - """``cost: $0.0532 (solver gpt-4.1-mini $0.0412, 115k in, 1.2k out; judge ...)``, ``at least`` when the cost is a - lower bound and, with ``attempts``, the attempts named when there were more than one; None for no usage.""" + """``cost: $0.0532 (solver gpt-4.1-mini $0.0412, 115k in, 1.2k out; judge ...)``, the cost bounded as ``_bounded`` + says and, with ``attempts``, the attempts named when there were more than one; None for no usage.""" if summary is None: return None - total = "unpriced" if summary.cost_usd is None else _dollars(summary.cost_usd) - if summary.lower_bound and summary.cost_usd is not None: - total = f"at least {total}" + total = "unpriced" if summary.cost_usd is None else _bounded(summary.cost_usd, summary.lower_bound, + summary.upper_bound) parts = [f"{summary.attempts} attempts"] if attempts and summary.attempts > 1 else [] return f"{label}: {total} ({'; '.join([*parts, *map(_share, summary.shares)])})" @@ -38,9 +37,7 @@ def sources_line(summaries: Iterable[UsageSummary | None]) -> str | None: def _share(share: Share) -> str: - cost = "unpriced" if share.cost_usd is None else _dollars(share.cost_usd) - if share.unpriced and share.cost_usd is not None: - cost = f"at least {cost}" + cost = "unpriced" if share.cost_usd is None else _bounded(share.cost_usd, share.unpriced, share.assumed) words = [f"{_ROLE_NAMES.get(share.role, share.role)} {share.model or 'an unnamed model'} {cost}"] if share.input_tokens is not None: words.append(f"{_count(share.input_tokens)} in") @@ -51,6 +48,13 @@ def _share(share: Share) -> str: return ", ".join(words) +def _bounded(usd: float, lower: bool, upper: bool) -> str: + """``usd`` with what it is: ``at least`` when some usage went uncounted, ``at most`` when some was priced on an + assumed rate, ``estimated`` when both.""" + word = "estimated " if lower and upper else "at least " if lower else "at most " if upper else "" + return f"{word}{_dollars(usd)}" + + def _dollars(usd: float) -> str: return "$0" if usd == 0 else f"${usd:.4f}" if usd >= 0.0001 else "under $0.0001" diff --git a/src/agent_env/task/usage/summary.py b/src/agent_env/task/usage/summary.py index 7f62b85cf..e55e207b0 100644 --- a/src/agent_env/task/usage/summary.py +++ b/src/agent_env/task/usage/summary.py @@ -1,6 +1,7 @@ """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 total a lower bound, as a partial or a still running entry does.""" +$0, and makes the total 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.""" from __future__ import annotations @@ -16,8 +17,8 @@ @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 - priced, with ``unpriced`` when some part had no cost and ``partial`` when its counts are a lower bound (a partial or - a still running entry).""" + priced, with ``unpriced`` when some part had no cost, ``assumed`` when some part's cost is an upper bound + (``cost_assumed``), and ``partial`` when its counts are a lower bound (a partial or a still running entry).""" role: str model: str | None @@ -25,6 +26,7 @@ class Share: output_tokens: int | None = None cost_usd: float | None = None unpriced: bool = False + assumed: bool = False partial: bool = False def add(self, part: Mapping) -> None: @@ -33,6 +35,7 @@ def add(self, part: Mapping) -> None: cost = part.get("cost_usd") if _number(cost): self.cost_usd = (self.cost_usd or 0.0) + cost + self.assumed = self.assumed or bool(part.get("cost_assumed")) else: self.unpriced = True @@ -40,11 +43,13 @@ def add(self, part: Mapping) -> None: @dataclass(frozen=True) class UsageSummary: """A ledger summed: its shares in role order, the cost of everything priced (None when nothing was), whether that - cost is a lower bound, how many attempts the ledger holds, and where its costs came from (``cost_source``).""" + cost is a lower bound, an upper bound or, both being true, an estimate, how many attempts the ledger holds, and + where its costs came from (``cost_source``).""" shares: tuple[Share, ...] cost_usd: float | None lower_bound: bool + upper_bound: bool attempts: int sources: tuple[str, ...] @@ -68,6 +73,7 @@ def summarize(ledger: Iterable[Mapping]) -> UsageSummary | None: priced = [share.cost_usd for share in ordered if share.cost_usd is not None] lower_bound = any(share.unpriced or share.partial for share in ordered) return UsageSummary(shares=tuple(ordered), cost_usd=sum(priced) if priced else None, lower_bound=lower_bound, + upper_bound=any(share.assumed for share in ordered), attempts=len({entry.get("attempt") for entry in entries}), sources=tuple(sorted(sources))) @@ -85,11 +91,13 @@ def combine(summaries: Iterable[UsageSummary | None]) -> UsageSummary | None: if share.cost_usd is not None: total.cost_usd = (total.cost_usd or 0.0) + share.cost_usd total.unpriced = total.unpriced or share.unpriced + total.assumed = total.assumed or share.assumed total.partial = total.partial or share.partial ordered = sorted(shares.values(), key=lambda share: (_rank(share.role), share.role, share.model or "")) priced = [summary.cost_usd for summary in present if summary.cost_usd is not None] return UsageSummary(shares=tuple(ordered), cost_usd=sum(priced) if priced else None, lower_bound=any(summary.lower_bound for summary in present), + upper_bound=any(summary.upper_bound for summary in present), attempts=sum(summary.attempts for summary in present), sources=tuple(sorted({source for summary in present for source in summary.sources}))) diff --git a/tst/unit/bundle/run_test.py b/tst/unit/bundle/run_test.py index 4af4a808c..f8a5aa98b 100644 --- a/tst/unit/bundle/run_test.py +++ b/tst/unit/bundle/run_test.py @@ -102,6 +102,20 @@ async def execute(self, context): return context +class _ReadsCache(_Scored): + """Records a solver turn of 1,000 input tokens, 600 of them read from the cache, on gpt-4.1-mini, whose price here + gives no cache read rate.""" + + type = "reads_cache_run_test" + + async def execute(self, context): + usage = StepUsage(context, self.id) + usage.start(ModelRole.SOLVER, "gpt-4.1-mini", None) + usage.turn(ModelRole.SOLVER, TerminalResponse(response_text="", usage=Usage( + input_tokens=1000, output_tokens=10, cache_read_tokens=600, input_includes_cache=True))) + return context + + class _RecordsModels(_Scored): """Records the models its solver, user simulator and judge ask for, as the real steps do.""" @@ -159,7 +173,8 @@ def _scored(score): @pytest.fixture(autouse=True) def registries(monkeypatch): steps = {**Config().task_step_registry(), - **{cls.type: cls for cls in (_Scored, _Failing, _Cancelled, _NamesAgent, _RecordsModels, _Spends)}} + **{cls.type: cls for cls in (_Scored, _Failing, _Cancelled, _NamesAgent, _RecordsModels, _Spends, + _ReadsCache)}} monkeypatch.setattr(Config, "task_step_registry", lambda self: steps) fake_plugins(monkeypatch) # no installed package ships these classes monkeypatch.setattr(_Scored, "seen", []) @@ -537,6 +552,16 @@ def test_a_usage_read_that_fails_leaves_the_run_and_its_result_without_a_cost(bu assert run.error is None and not run.cancelled and run.usage == () and run.usage_summary is None +def test_the_cli_prints_a_cost_priced_on_an_assumed_cache_rate_as_at_most(bundle_dir, prices, quiet_logs): + layout(bundle_dir, {"tasks/cached.json": json.dumps([{"id": "read", "type": "reads_cache_run_test"}])}) + + result = CliRunner().invoke(cli, ["run", str(bundle_dir), "--task", "cached"]) + + assert result.exit_code == 0, result.output + lines = result.output.splitlines() + assert " cost: at most $0.0004 (solver gpt-4.1-mini at most $0.0004, 1.0k in, 10 out)" in lines + + def test_the_cli_prints_each_runs_cost_by_role_and_model_and_an_evals_total(bundle_dir, prices, quiet_logs): layout(bundle_dir, {"tasks/spends.json": json.dumps([{"id": "spend", "type": "spends_run_test"}]), "evals/spending.toml": 'tasks = ["spends", "a"]\n'}) diff --git a/tst/unit/task/usage/summary_test.py b/tst/unit/task/usage/summary_test.py index 2bc6210eb..e2c5c6020 100644 --- a/tst/unit/task/usage/summary_test.py +++ b/tst/unit/task/usage/summary_test.py @@ -60,6 +60,31 @@ def test_unpriced_usage_is_counted_apart_never_as_nothing_and_makes_the_total_a_ "cost: unpriced (judge mystery-1 unpriced, 3.1k in, 90 out)") +def test_a_cost_priced_on_an_assumed_rate_is_at_most_and_with_uncounted_usage_an_estimate(): + assumed = _entry("solver", "gpt-4.1-mini", 1000, 10, 0.0004, cost_assumed=["cache_read_rate"]) + summary = summarize([assumed, _entry("judge", "j", 100, 1, 0.0001)]) + + assert summary.upper_bound and not summary.lower_bound + 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( + "cost: estimated $0.0004 (solver gpt-4.1-mini at most $0.0004") + assert cost_line(summarize([assumed, _entry("solver", "gpt-4.1-mini", 100, 1, None)])) == ( + "cost: estimated $0.0004 (solver gpt-4.1-mini estimated $0.0004, 1.1k in, 11 out)") + assert combine([summarize([_entry("judge", "j", 1, 1, 0.1)]), summarize([assumed])]).upper_bound + + +def test_a_per_model_row_priced_on_an_assumed_rate_bounds_its_own_share(): + rows = [{"model": "a", "input_tokens": 9, "output_tokens": 1, "cost_usd": 0.2, + "cost_assumed": ["cache_write_rate"]}, + {"model": "b", "input_tokens": 3, "output_tokens": 1, "cost_usd": 0.1}] + 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 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)") + + def test_a_partial_or_running_entry_makes_its_share_partial_and_the_total_a_lower_bound(): for mark in ({"partial": True}, {"running": True}): summary = summarize([_entry("solver", "gpt-4.1-mini", 1000, 10, 0.0004, **mark)]) From 93900456e9dd2a307e164911e17d7462fdd144e1 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 21:10:27 -0800 Subject: [PATCH 4/7] fix(cli): a share cut off mid-run prints its cost as at least, or estimated with an assumed rate Co-Authored-By: Claude Opus 5.5 --- src/agent_env/cli/usage_output.py | 3 ++- tst/unit/cli/submit_runs_test.py | 5 +++-- tst/unit/task/usage/summary_test.py | 5 ++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/agent_env/cli/usage_output.py b/src/agent_env/cli/usage_output.py index 7fddfa76f..63ba94018 100644 --- a/src/agent_env/cli/usage_output.py +++ b/src/agent_env/cli/usage_output.py @@ -37,7 +37,8 @@ def sources_line(summaries: Iterable[UsageSummary | None]) -> str | None: def _share(share: Share) -> str: - cost = "unpriced" if share.cost_usd is None else _bounded(share.cost_usd, share.unpriced, share.assumed) + cost = "unpriced" if share.cost_usd is None else _bounded(share.cost_usd, share.unpriced or share.partial, + share.assumed) words = [f"{_ROLE_NAMES.get(share.role, share.role)} {share.model or 'an unnamed model'} {cost}"] if share.input_tokens is not None: words.append(f"{_count(share.input_tokens)} in") diff --git a/tst/unit/cli/submit_runs_test.py b/tst/unit/cli/submit_runs_test.py index e2e3c38d4..30cc16c32 100644 --- a/tst/unit/cli/submit_runs_test.py +++ b/tst/unit/cli/submit_runs_test.py @@ -200,7 +200,7 @@ async def run(self, context, **kwargs): return await super().run(context, **kwargs) -SPENT = "at least $0.0004 (solver gpt-4.1-mini $0.0004, 1.0k in, 10 out, partial)" +SPENT = "at least $0.0004 (solver gpt-4.1-mini at least $0.0004, 1.0k in, 10 out, partial)" def test_an_eval_prints_each_runs_cost_and_their_total_from_the_ledgers(monkeypatch, tmp_path, torn_down): @@ -214,7 +214,8 @@ def test_an_eval_prints_each_runs_cost_and_their_total_from_the_ledgers(monkeypa assert result.exit_code == 0, result.output lines = result.output.splitlines() assert lines.count(f" cost: {SPENT}") == 2 - assert "Cost over 2 runs: at least $0.0008 (solver gpt-4.1-mini $0.0008, 2.0k in, 20 out, partial)" in lines + assert ("Cost over 2 runs: at least $0.0008 (solver gpt-4.1-mini at least $0.0008, 2.0k in, 20 out, partial)" + in lines) assert lines[-1] == "Costs priced from LiteLLM's price map, litellm@test." diff --git a/tst/unit/task/usage/summary_test.py b/tst/unit/task/usage/summary_test.py index e2c5c6020..7417d078c 100644 --- a/tst/unit/task/usage/summary_test.py +++ b/tst/unit/task/usage/summary_test.py @@ -72,6 +72,8 @@ def test_a_cost_priced_on_an_assumed_rate_is_at_most_and_with_uncounted_usage_an assert cost_line(summarize([assumed, _entry("solver", "gpt-4.1-mini", 100, 1, None)])) == ( "cost: estimated $0.0004 (solver gpt-4.1-mini estimated $0.0004, 1.1k in, 11 out)") assert combine([summarize([_entry("judge", "j", 1, 1, 0.1)]), summarize([assumed])]).upper_bound + assert cost_line(summarize([assumed, _entry("solver", "gpt-4.1-mini", 100, 1, 0.0001, running=True)])) == ( + "cost: estimated $0.0005 (solver gpt-4.1-mini estimated $0.0005, 1.1k in, 11 out, partial)") def test_a_per_model_row_priced_on_an_assumed_rate_bounds_its_own_share(): @@ -89,7 +91,8 @@ 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 cost_line(summary) == "cost: at least $0.0004 (solver gpt-4.1-mini $0.0004, 1.0k in, 10 out, partial)" + assert cost_line(summary) == ("cost: at least $0.0004 (solver gpt-4.1-mini at least $0.0004, 1.0k in, 10 out, " + "partial)") def test_every_attempt_counts_and_is_named_when_there_were_more_than_one(): From f5779fabf81912ed5406d7eca289532a4f78ff4a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 21:47:50 -0800 Subject: [PATCH 5/7] refactor(cli): one summary rule for a share's cost and the total's, eval totals summed from the runs' ledgers Co-Authored-By: Claude Opus 5.5 --- src/agent_env/cli/eval/run.py | 14 ++-- src/agent_env/cli/run.py | 6 +- src/agent_env/cli/task/run.py | 14 ++-- src/agent_env/cli/usage_output.py | 44 +++++------ src/agent_env/task/usage/summary.py | 118 +++++++++++++--------------- tst/unit/task/usage/summary_test.py | 30 ++++--- 6 files changed, 106 insertions(+), 120 deletions(-) diff --git a/src/agent_env/cli/eval/run.py b/src/agent_env/cli/eval/run.py index 6a434b065..3986fa7c0 100644 --- a/src/agent_env/cli/eval/run.py +++ b/src/agent_env/cli/eval/run.py @@ -13,7 +13,7 @@ from agent_env.cli.usage_output import cost_line, sources_line from agent_env.store.ids import fs_safe from agent_env.task.interrupts import Interrupts -from agent_env.task.usage.summary import combine, summarize +from agent_env.task.usage.summary import summarize from agent_env.task_step.context import TaskStepContext @@ -99,13 +99,14 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, # Summarize results failures = [] successes = [] - usage = [] + entries = [] for run in runs: context = run.instance.context if run.instance else None if output_dir and context is not None: _write_context(TaskStepContext.from_dict(context), run.task.id, output_dir, prefix=f"{run.tag} ") - summary = summarize(run.instance.usage) if run.instance else None - usage.append(summary) + ledger = run.instance.usage if run.instance else [] + summary = summarize(ledger) + entries += ledger if run.completed: successes.append((run.tag, (context or {}).get("metadata", {}).get("score"), summary)) else: @@ -130,9 +131,10 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, )) else: click.echo(click.style(f"\nAll {total_runs} runs completed!", fg="blue")) - if cost := cost_line(combine(usage), f"Cost over {len(runs)} runs", attempts=False): + total = summarize(entries) + if cost := cost_line(total, f"Cost over {len(runs)} runs", attempts=False): click.echo(cost) - if sources := sources_line(usage): + if sources := sources_line(total): click.echo(sources) if interrupts.count: raise SystemExit(128 + interrupts.signum) diff --git a/src/agent_env/cli/run.py b/src/agent_env/cli/run.py index 6252a018d..f3cd6db11 100644 --- a/src/agent_env/cli/run.py +++ b/src/agent_env/cli/run.py @@ -23,7 +23,7 @@ from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandbox from agent_env.task.interrupts import Interrupts from agent_env.task.teardown import TORN_DOWN_KEY, RecordedSandbox, TeardownReport, kind, recorded_sandboxes, sandbox_ids -from agent_env.task.usage.summary import combine +from agent_env.task.usage.summary import summarize from agent_env.task_step.context import TaskStepContext _COLORS = {Outcome.PASSED: "green", Outcome.BELOW_ONE: "yellow", Outcome.UNSCORED: "yellow", Outcome.FAILED: "red", @@ -214,13 +214,13 @@ def _summarize(result: BundleRun, verbose: bool) -> None: line = f" {result.path(eval_run.entry)} v{eval_run.version}: {passed} of {len(eval_run.runs)} passed" rest = [f"{failed} failed" if failed else "", f"{cancelled} cancelled" if cancelled else ""] click.echo(", ".join([line, *filter(None, rest)])) - if cost := cost_line(combine(run.usage_summary for run in eval_run.runs), + if cost := cost_line(summarize(entry for run in eval_run.runs for entry in run.usage), f"cost over {len(eval_run.runs)} runs", attempts=False): click.echo(f" {cost}") for entry in result.skipped: click.echo(f"{result.path(entry)} isn't named by any eval, so it didn't run; run it with " f"--task {shlex.quote(entry.name)}") - if sources := sources_line(run.usage_summary for run in result.runs): + if sources := sources_line(summarize(entry for run in result.runs for entry in run.usage)): click.echo(sources) if verbose: _print_tracebacks(result) diff --git a/src/agent_env/cli/task/run.py b/src/agent_env/cli/task/run.py index b30f0e966..e5b524223 100644 --- a/src/agent_env/cli/task/run.py +++ b/src/agent_env/cli/task/run.py @@ -27,7 +27,7 @@ from agent_env.task.interrupts import Interrupts from agent_env.task.store import get_task_instance_store, new_instance_id from agent_env.task.teardown import TeardownReport, attempt_epoch, kind, record_teardown, teardown_run -from agent_env.task.usage.summary import combine, summarize +from agent_env.task.usage.summary import summarize from agent_env.task_step.context import TaskStepContext, read_dual_keyed from agent_env.task_step.task_steps.deploy_agent import DeployAgentTaskStep from agent_env.task_step.context_ops import build_context_update_ops @@ -494,14 +494,14 @@ def run(task_id: str, task_version: int | None, output_dir: str | None, k: int, def _echo_usage(runs, k: int) -> None: """Each run's cost by role and model from its ledger, the runs' total when there were several, and where the costs came from.""" - summaries = [(run.tag, summarize(run.instance.usage) if run.instance else None) for run in runs] - for tag, summary in summaries: - if cost := cost_line(summary): + ledgers = [(run.tag, run.instance.usage if run.instance else []) for run in runs] + for tag, ledger in ledgers: + if cost := cost_line(summarize(ledger)): click.echo(f"{tag} {cost}" if tag else cost) - if k > 1 and (cost := cost_line(combine(summary for _, summary in summaries), f"Cost over {k} runs", - attempts=False)): + total = summarize(entry for _, ledger in ledgers for entry in ledger) + if k > 1 and (cost := cost_line(total, f"Cost over {k} runs", attempts=False)): click.echo(cost) - if sources := sources_line(summary for _, summary in summaries): + if sources := sources_line(total): click.echo(sources) diff --git a/src/agent_env/cli/usage_output.py b/src/agent_env/cli/usage_output.py index 63ba94018..50689d58a 100644 --- a/src/agent_env/cli/usage_output.py +++ b/src/agent_env/cli/usage_output.py @@ -3,43 +3,38 @@ from __future__ import annotations -from collections.abc import Iterable - from agent_env.config.model import ModelRole +from agent_env.config.model_pricing import ReportedBy from agent_env.task.usage.summary import Share, UsageSummary _ROLE_NAMES = {role.value: role.record_key for role in ModelRole} -# The cost sources that aren't the price map, as ``cost_source`` names them, in the order they're named. -_REPORTED = (("provider", "the endpoint's bills"), ("harness", "agents' own figures")) +# The cost sources that aren't the price map, in the order they're named. +_REPORTED = {ReportedBy.PROVIDER: "the endpoint's bills", ReportedBy.HARNESS: "agents' own figures"} def cost_line(summary: UsageSummary | None, label: str = "cost", attempts: bool = True) -> str | None: - """``cost: $0.0532 (solver gpt-4.1-mini $0.0412, 115k in, 1.2k out; judge ...)``, the cost bounded as ``_bounded`` - says and, with ``attempts``, the attempts named when there were more than one; None for no usage.""" + """``cost: $0.0532 (solver gpt-4.1-mini $0.0412, 115k in, 1.2k out; judge ...)``, each cost as ``_cost`` gives it + and, with ``attempts``, the attempts named when there were more than one; None for no usage.""" if summary is None: return None - total = "unpriced" if summary.cost_usd is None else _bounded(summary.cost_usd, summary.lower_bound, - summary.upper_bound) parts = [f"{summary.attempts} attempts"] if attempts and summary.attempts > 1 else [] - return f"{label}: {total} ({'; '.join([*parts, *map(_share, summary.shares)])})" + return f"{label}: {_cost(summary)} ({'; '.join([*parts, *map(_share, summary.shares)])})" -def sources_line(summaries: Iterable[UsageSummary | None]) -> str | None: - """Where the summaries' costs came from, as ``Costs priced from LiteLLM's price map, litellm@1.80.0.``; None when - none was priced.""" - sources = {source for summary in summaries if summary is not None for source in summary.sources} +def sources_line(summary: UsageSummary | None) -> str | None: + """Where ``summary``'s costs came from, as ``Costs priced from LiteLLM's price map, litellm@1.80.0.``; None when + nothing was priced.""" + sources = summary.sources if summary is not None else () if not sources: return None - named = [f"LiteLLM's price map, {source}" for source in sorted(sources) if source.startswith("litellm@")] - named += [name for source, name in _REPORTED if source in sources] - named += sorted(source for source in sources if not source.startswith("litellm@") and source not in dict(_REPORTED)) + named = [f"LiteLLM's price map, {source}" for source in sources if source.startswith("litellm@")] + named += [name for source, name in _REPORTED.items() if source in sources] + named += [source for source in sources if not source.startswith("litellm@") and source not in _REPORTED] return f"Costs priced from {'; '.join(named)}." def _share(share: Share) -> str: - cost = "unpriced" if share.cost_usd is None else _bounded(share.cost_usd, share.unpriced or share.partial, - share.assumed) - words = [f"{_ROLE_NAMES.get(share.role, share.role)} {share.model or 'an unnamed model'} {cost}"] + words = [f"{_ROLE_NAMES.get(share.role, share.role)} {share.model or 'an unnamed model'} {_cost(share)}"] if share.input_tokens is not None: words.append(f"{_count(share.input_tokens)} in") if share.output_tokens is not None: @@ -49,11 +44,14 @@ def _share(share: Share) -> str: return ", ".join(words) -def _bounded(usd: float, lower: bool, upper: bool) -> str: - """``usd`` with what it is: ``at least`` when some usage went uncounted, ``at most`` when some was priced on an - assumed rate, ``estimated`` when both.""" +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: + 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 "" - return f"{word}{_dollars(usd)}" + return f"{word}{_dollars(of.cost_usd)}" def _dollars(usd: float) -> str: diff --git a/src/agent_env/task/usage/summary.py b/src/agent_env/task/usage/summary.py index e55e207b0..492d6d4e2 100644 --- a/src/agent_env/task/usage/summary.py +++ b/src/agent_env/task/usage/summary.py @@ -1,24 +1,28 @@ """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 total a lower bound, as a partial or a still running entry does; a cost priced on an assumed rate +$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.""" from __future__ import annotations -from collections.abc import Iterable, Mapping +from collections.abc import Iterable from dataclasses import dataclass +from typing import TYPE_CHECKING from agent_env.config.model import ModelRole +if TYPE_CHECKING: + from agent_env.task_step.usage import ModelEntry, UsageEntry + # The order roles are shown in; any other comes after them. -ROLES = tuple(role.value for role in ModelRole) +_ROLES = tuple(role.value for role in ModelRole) @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 - priced, with ``unpriced`` when some part had no cost, ``assumed`` when some part's cost is an upper bound - (``cost_assumed``), and ``partial`` when its counts are a lower bound (a partial or a still running entry).""" + priced, with ``unpriced`` when some part had no cost, ``assumed`` when some part's cost was priced on an assumed + rate (``cost_assumed``), and ``partial`` when its counts fall short (a partial or a still running entry).""" role: str model: str | None @@ -29,93 +33,77 @@ class Share: assumed: bool = False partial: bool = False - def add(self, part: Mapping) -> None: + @property + def lower_bound(self) -> bool: + return self.unpriced or self.partial + + @property + def upper_bound(self) -> bool: + return self.assumed + + 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")) - cost = part.get("cost_usd") - if _number(cost): + if (cost := part.get("cost_usd")) is None: + self.unpriced = True + else: self.cost_usd = (self.cost_usd or 0.0) + cost self.assumed = self.assumed or bool(part.get("cost_assumed")) - else: - self.unpriced = True + self.partial = self.partial or partial @dataclass(frozen=True) class UsageSummary: - """A ledger summed: its shares in role order, the cost of everything priced (None when nothing was), whether that - cost is a lower bound, an upper bound or, both being true, an estimate, how many attempts the ledger holds, and - where its costs came from (``cost_source``).""" + """A ledger summed: its shares in role order, how many attempts it holds, and where its costs came from + (``cost_source``). Its cost and bounds are its shares'.""" shares: tuple[Share, ...] - cost_usd: float | None - lower_bound: bool - upper_bound: bool attempts: int sources: tuple[str, ...] + @property + def cost_usd(self) -> float | None: + """The cost of everything priced; None when nothing was.""" + priced = [share.cost_usd for share in self.shares if share.cost_usd is not None] + return sum(priced) if priced else None + + @property + def lower_bound(self) -> bool: + return any(share.lower_bound for share in self.shares) -def summarize(ledger: Iterable[Mapping]) -> UsageSummary | None: - """``ledger``'s entries, a task instance's ``usage``, summed by role and model; None when it has none.""" - entries = [entry for entry in ledger if isinstance(entry, Mapping)] + @property + def upper_bound(self) -> bool: + return any(share.upper_bound 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; + several runs' together give their total, whose ``attempts`` counts attempt numbers, not the runs' attempts.""" + entries = list(ledger) if not entries: return None shares: dict[tuple[str, str | None], Share] = {} sources: set[str] = set() for entry in entries: - role = str(entry.get("role") or "unknown") + partial = bool(entry.get("partial") or entry.get("running")) for model, part in _parts(entry): - share = shares.setdefault((role, model), Share(role, model)) - share.add(part) - share.partial = share.partial or bool(entry.get("partial") or entry.get("running")) - if _number(part.get("cost_usd")) and part.get("cost_source"): + shares.setdefault((entry["role"], model), Share(entry["role"], model)).add(part, partial) + if part.get("cost_usd") is not None and part.get("cost_source"): sources.add(part["cost_source"]) ordered = sorted(shares.values(), key=lambda share: (_rank(share.role), share.role, share.model or "")) - priced = [share.cost_usd for share in ordered if share.cost_usd is not None] - lower_bound = any(share.unpriced or share.partial for share in ordered) - return UsageSummary(shares=tuple(ordered), cost_usd=sum(priced) if priced else None, lower_bound=lower_bound, - upper_bound=any(share.assumed for share in ordered), - attempts=len({entry.get("attempt") for entry in entries}), sources=tuple(sorted(sources))) + return UsageSummary(shares=tuple(ordered), attempts=len({entry.get("attempt") for entry in entries}), + sources=tuple(sorted(sources))) -def combine(summaries: Iterable[UsageSummary | None]) -> UsageSummary | None: - """Several runs' summaries as one, as an eval's total: their shares summed by role and model.""" - present = [summary for summary in summaries if summary is not None] - if not present: - return None - shares: dict[tuple[str, str | None], Share] = {} - for summary in present: - for share in summary.shares: - total = shares.setdefault((share.role, share.model), Share(share.role, share.model)) - total.input_tokens = _plus(total.input_tokens, share.input_tokens) - total.output_tokens = _plus(total.output_tokens, share.output_tokens) - if share.cost_usd is not None: - total.cost_usd = (total.cost_usd or 0.0) + share.cost_usd - total.unpriced = total.unpriced or share.unpriced - total.assumed = total.assumed or share.assumed - total.partial = total.partial or share.partial - ordered = sorted(shares.values(), key=lambda share: (_rank(share.role), share.role, share.model or "")) - priced = [summary.cost_usd for summary in present if summary.cost_usd is not None] - return UsageSummary(shares=tuple(ordered), cost_usd=sum(priced) if priced else None, - lower_bound=any(summary.lower_bound for summary in present), - upper_bound=any(summary.upper_bound for summary in present), - attempts=sum(summary.attempts for summary in present), - sources=tuple(sorted({source for summary in present for source in summary.sources}))) - - -def _parts(entry: Mapping) -> list[tuple[str | None, Mapping]]: - rows = entry.get("models") - if isinstance(rows, list) and rows: - return [(row.get("model") or entry.get("model"), row) for row in rows if isinstance(row, Mapping)] +def _parts(entry: UsageEntry) -> list[tuple[str | None, UsageEntry | ModelEntry]]: + if rows := entry.get("models"): + return [(row.get("model") or entry.get("model"), row) for row in rows] return [(entry.get("model"), entry)] def _rank(role: str) -> int: - return ROLES.index(role) if role in ROLES else len(ROLES) - - -def _number(value: object) -> bool: - return isinstance(value, (int, float)) and not isinstance(value, bool) + return _ROLES.index(role) if role in _ROLES else len(_ROLES) -def _plus(total: int | None, value: object) -> int | None: - return total if not _number(value) else (total or 0) + int(value) +def _plus(total: int | None, value: int | None) -> int | None: + return total if value is None else (total or 0) + value diff --git a/tst/unit/task/usage/summary_test.py b/tst/unit/task/usage/summary_test.py index 7417d078c..8e7676431 100644 --- a/tst/unit/task/usage/summary_test.py +++ b/tst/unit/task/usage/summary_test.py @@ -5,7 +5,7 @@ import pytest from agent_env.cli.usage_output import cost_line, sources_line -from agent_env.task.usage.summary import combine, summarize +from agent_env.task.usage.summary import summarize def _entry(role, model, input_tokens, output_tokens, cost, attempt=0, **more): @@ -71,7 +71,6 @@ def test_a_cost_priced_on_an_assumed_rate_is_at_most_and_with_uncounted_usage_an "cost: estimated $0.0004 (solver gpt-4.1-mini at most $0.0004") assert cost_line(summarize([assumed, _entry("solver", "gpt-4.1-mini", 100, 1, None)])) == ( "cost: estimated $0.0004 (solver gpt-4.1-mini estimated $0.0004, 1.1k in, 11 out)") - assert combine([summarize([_entry("judge", "j", 1, 1, 0.1)]), summarize([assumed])]).upper_bound assert cost_line(summarize([assumed, _entry("solver", "gpt-4.1-mini", 100, 1, 0.0001, running=True)])) == ( "cost: estimated $0.0005 (solver gpt-4.1-mini estimated $0.0005, 1.1k in, 11 out, partial)") @@ -104,17 +103,16 @@ def test_every_attempt_counts_and_is_named_when_there_were_more_than_one(): assert "attempts" not in cost_line(summary, "cost over 1 run", attempts=False) -def test_runs_combine_into_an_evals_total_by_role_and_model(): - first = summarize([_entry("solver", "gpt-4.1-mini", 1000, 10, 0.0004)]) - second = summarize([_entry("solver", "gpt-4.1-mini", 2000, 20, 0.0008), - _entry("judge", "mystery-1", 500, 5, None)]) +def test_runs_ledgers_together_are_an_evals_total_by_role_and_model(): + first = [_entry("solver", "gpt-4.1-mini", 1000, 10, 0.0004)] + second = [_entry("solver", "gpt-4.1-mini", 2000, 20, 0.0008), _entry("judge", "mystery-1", 500, 5, None)] - total = combine([first, None, second]) + total = summarize([*first, *second]) 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 combine([None]) is None and summarize([]) is None and cost_line(None) is None + assert summarize([]) is None and cost_line(None) is None def test_counts_and_costs_read_at_a_glance(): @@ -124,11 +122,11 @@ def test_counts_and_costs_read_at_a_glance(): def test_the_closing_line_names_each_source_of_the_costs(): - priced = summarize([_entry("solver", "m", 1, 1, 0.1)]) - reported = summarize([{**_entry("judge", "j", 1, 1, 0.2), "cost_source": "harness"}, - {**_entry("user_simulator", "u", 1, 1, 0.3), "cost_source": "provider"}]) - - assert sources_line([priced]) == "Costs priced from LiteLLM's price map, litellm@1.80.0." - assert sources_line([priced, reported]) == ("Costs priced from LiteLLM's price map, litellm@1.80.0; the endpoint's " - "bills; agents' own figures.") - assert sources_line([summarize([_entry("judge", "x", 1, 1, None)]), None]) is None + priced = [_entry("solver", "m", 1, 1, 0.1)] + reported = [{**_entry("judge", "j", 1, 1, 0.2), "cost_source": "harness"}, + {**_entry("user_simulator", "u", 1, 1, 0.3), "cost_source": "provider"}] + + assert sources_line(summarize(priced)) == "Costs priced from LiteLLM's price map, litellm@1.80.0." + assert sources_line(summarize([*priced, *reported])) == ( + "Costs priced from LiteLLM's price map, litellm@1.80.0; the endpoint's bills; agents' own figures.") + assert sources_line(summarize([_entry("judge", "x", 1, 1, None)])) is None and sources_line(None) is None From d8dd53f372526da3e97b0c2016a92f3de006001a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 22:16:27 -0800 Subject: [PATCH 6/7] refactor(cli): name the cost lines' display limits Co-Authored-By: Claude Opus 5.5 --- src/agent_env/cli/usage_output.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/agent_env/cli/usage_output.py b/src/agent_env/cli/usage_output.py index 50689d58a..c69a3ca8d 100644 --- a/src/agent_env/cli/usage_output.py +++ b/src/agent_env/cli/usage_output.py @@ -10,6 +10,10 @@ _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. _REPORTED = {ReportedBy.PROVIDER: "the endpoint's bills", ReportedBy.HARNESS: "agents' own figures"} +_DOLLAR_PLACES = 4 +_SMALLEST_DOLLARS = 0.0001 # the least a cost shows at _DOLLAR_PLACES; a smaller one reads "under" it +_THOUSAND, _MILLION = 1_000, 1_000_000 +_TENTHS_OF_THOUSANDS_BELOW = 10 * _THOUSAND # a count under it shows one decimal: 1.2k, not 1k def cost_line(summary: UsageSummary | None, label: str = "cost", attempts: bool = True) -> str | None: @@ -55,14 +59,16 @@ def _cost(of: UsageSummary | Share) -> str: def _dollars(usd: float) -> str: - return "$0" if usd == 0 else f"${usd:.4f}" if usd >= 0.0001 else "under $0.0001" + if usd == 0: + return "$0" + return f"${usd:.{_DOLLAR_PLACES}f}" if usd >= _SMALLEST_DOLLARS else f"under ${_SMALLEST_DOLLARS:.{_DOLLAR_PLACES}f}" def _count(n: int) -> str: - if n < 1000: + if n < _THOUSAND: return str(n) - if n < 10_000: - return f"{n / 1000:.1f}k" - if n < 1_000_000: - return f"{round(n / 1000)}k" - return f"{n / 1_000_000:.1f}M" + if n < _TENTHS_OF_THOUSANDS_BELOW: + return f"{n / _THOUSAND:.1f}k" + if n < _MILLION: + return f"{round(n / _THOUSAND)}k" + return f"{n / _MILLION:.1f}M" From 2442826a0c186146bfbb18ba4e0d997fe4b18c74 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 22:16:44 -0800 Subject: [PATCH 7/7] refactor(cli): wrap the dollars format Co-Authored-By: Claude Opus 5.5 --- src/agent_env/cli/usage_output.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/agent_env/cli/usage_output.py b/src/agent_env/cli/usage_output.py index c69a3ca8d..cdbaa0788 100644 --- a/src/agent_env/cli/usage_output.py +++ b/src/agent_env/cli/usage_output.py @@ -61,7 +61,9 @@ def _cost(of: UsageSummary | Share) -> str: def _dollars(usd: float) -> str: if usd == 0: return "$0" - return f"${usd:.{_DOLLAR_PLACES}f}" if usd >= _SMALLEST_DOLLARS else f"under ${_SMALLEST_DOLLARS:.{_DOLLAR_PLACES}f}" + if usd < _SMALLEST_DOLLARS: + return f"under ${_SMALLEST_DOLLARS:.{_DOLLAR_PLACES}f}" + return f"${usd:.{_DOLLAR_PLACES}f}" def _count(n: int) -> str: