diff --git a/AGENTS.md b/AGENTS.md index 20a67ced5..6a311b0ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -399,9 +399,11 @@ 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, 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/bundle/run.py b/src/agent_env/bundle/run.py index df39f0f49..d6c88008b 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,22 @@ 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. 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 + 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) + + 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..3986fa7c0 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 summarize from agent_env.task_step.context import TaskStepContext @@ -97,30 +99,43 @@ def run(eval_id: str, eval_version: int | None, output_dir: str | None, k: int, # Summarize results failures = [] successes = [] + 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} ") + 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"))) + 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(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(summary): + 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")) + total = summarize(entries) + if cost := cost_line(total, f"Cost over {len(runs)} runs", attempts=False): + click.echo(cost) + if sources := sources_line(total): + 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..f3cd6db11 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 summarize 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(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(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 64aff5183..e5b524223 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 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.""" + 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) + 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(total): + 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..cdbaa0788 --- /dev/null +++ b/src/agent_env/cli/usage_output.py @@ -0,0 +1,76 @@ +"""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 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, 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: + """``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 + parts = [f"{summary.attempts} attempts"] if attempts and summary.attempts > 1 else [] + return f"{label}: {_cost(summary)} ({'; '.join([*parts, *map(_share, summary.shares)])})" + + +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 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: + 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: + words.append(f"{_count(share.output_tokens)} out") + if share.partial: + words.append("partial") + return ", ".join(words) + + +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(of.cost_usd)}" + + +def _dollars(usd: float) -> str: + if usd == 0: + return "$0" + if usd < _SMALLEST_DOLLARS: + return f"under ${_SMALLEST_DOLLARS:.{_DOLLAR_PLACES}f}" + return f"${usd:.{_DOLLAR_PLACES}f}" + + +def _count(n: int) -> str: + if n < _THOUSAND: + return str(n) + 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" diff --git a/src/agent_env/task/usage/summary.py b/src/agent_env/task/usage/summary.py new file mode 100644 index 000000000..492d6d4e2 --- /dev/null +++ b/src/agent_env/task/usage/summary.py @@ -0,0 +1,109 @@ +"""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.""" + +from __future__ import annotations + +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) + + +@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 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 + input_tokens: int | None = None + output_tokens: int | None = None + cost_usd: float | None = None + unpriced: bool = False + assumed: bool = False + partial: bool = False + + @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")) + 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")) + self.partial = self.partial or partial + + +@dataclass(frozen=True) +class UsageSummary: + """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, ...] + 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) + + @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: + partial = bool(entry.get("partial") or entry.get("running")) + for model, part in _parts(entry): + 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 "")) + return UsageSummary(shares=tuple(ordered), attempts=len({entry.get("attempt") for entry in entries}), + sources=tuple(sorted(sources))) + + +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 _plus(total: int | None, value: int | None) -> int | None: + return total if value is None else (total or 0) + 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..f8a5aa98b 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,36 @@ 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 _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.""" @@ -137,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)}} + **{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", []) @@ -483,6 +520,62 @@ 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_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_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'}) + + 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..30cc16c32 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,41 @@ 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 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): + """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), + types.SimpleNamespace(task_id="t", task_version=2)]))) + + result = _invoke(monkeypatch, _Spends(), "eval", "run", "--id", "e") + + 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 at least $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..8e7676431 --- /dev/null +++ b/tst/unit/task/usage/summary_test.py @@ -0,0 +1,132 @@ +"""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 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_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 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(): + 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)]) + assert summary.lower_bound and summary.shares[0].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(): + 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_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 = 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 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 = [_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