From 5529f8229c5a9384fdf761ca495aab6bc00dac28 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 08:44:57 -0800 Subject: [PATCH 1/5] feat(protocol): Usage gives a turn's counts by model, and the host prices each model at its own rate Usage.models holds a ModelUsage per model a turn's calls used (its calls, token and cache counts, and the agent's own cost for them), covering every call the turn counted. The host prices each model's counts at that model's map rate and the step's entry keeps a row per model, its cost_usd their sum; a turn without them is priced at the role's model, as before. The echo test agent reports a breakdown on a usage-models line, for the integration test. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- packages/agentenv-protocol/README.md | 9 ++ .../agentenv_protocol/a2a_agent/__init__.py | 2 + .../a2a_agent/tasks/__init__.py | 2 + .../agentenv_protocol/a2a_agent/tasks/v1.py | 84 ++++++++++++---- .../tests/test_usage_models.py | 58 +++++++++++ src/agent_env/task_step/usage.py | 77 ++++++++++++++- tst/data/a2a_agent/agent.py | 15 ++- .../cli/run_usage_by_model_test.py | 93 ++++++++++++++++++ tst/unit/task_step/usage_models_test.py | 98 +++++++++++++++++++ 10 files changed, 414 insertions(+), 28 deletions(-) create mode 100644 packages/agentenv-protocol/tests/test_usage_models.py create mode 100644 tst/integration/cli/run_usage_by_model_test.py create mode 100644 tst/unit/task_step/usage_models_test.py diff --git a/AGENTS.md b/AGENTS.md index b0128b647..e3501ba1c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,7 +89,9 @@ or one of them only where it is used. name as called or without its routing prefix, wherever its calls went. A prompt step prices each role's usage entry as it records it: `cost_usd` with its `cost_status` (`priced`, `reported`, `unpriced`) and `cost_source` (`litellm@`, `harness` or `provider`), the `uncached_input_tokens` and `unit_prices` it was charged at, any - `cost_assumed` that makes it an upper bound, and the agent's own figure, always, in `reported_cost_usd`. + `cost_assumed` that makes it an upper bound, and the agent's own figure, always, in `reported_cost_usd`. A turn + that gives its counts by model (`Usage.models`) is priced model by model, each at its own rate, and its entry keeps + a row per model (`models`), its `cost_usd` their sum. - Core's own model calls, the judges', go through `config/model_call.py` (`resolve_route`, `complete`), the only module in core that imports LiteLLM (`tst/unit/config/test_one_model_call_path.py`). Each call returns the model it called, the host it reached and its cost: what the endpoint billed, a LiteLLM proxy's `x-litellm-response-cost`, as diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 358b6dd40..2d3f360aa 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -1431,6 +1431,15 @@ reads what `to_dict` wrote under any protocol version, a field it leaves out being `None` and a key it doesn't know ignored, and `TaskResult.failure(..., usage=...)` carries usage on a failure as `success` does. +A turn whose calls used more than one model, such as a subagent on a smaller +model or a side call for a title, gives its counts by model in `Usage.models`: +one `ModelUsage` per model, with the model's name as called, its `calls`, its +token and cache counts read as `Usage`'s are, and the agent's own `cost_usd` +for them when it has one. The rows cover every call the turn counted; a call +the agent can't name goes under the model it was configured with. The host +prices each row at its own model's rate. A turn on one model leaves `models` +empty, and is priced at its role's model. + Whoever makes a model call knows what its counts hold, so an agent builds its own `Usage`. `Usage.from_model_response(usage)` is the default reader for a model response's own usage, with `input_tokens` counting the cache diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/__init__.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/__init__.py index abefb4f10..9ff177a39 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/__init__.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/__init__.py @@ -131,6 +131,7 @@ TaskStreamItem, TextPart, TrajectoryLog, + ModelUsage, Usage, WriteOnly, ) @@ -272,6 +273,7 @@ "TriggerDecideRequest", "TriggerRegisterRequest", "Uploaded", + "ModelUsage", "Usage", "WriteNamespaceGrant", "WriteObject", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/__init__.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/__init__.py index 2eae8ae67..486010cae 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/__init__.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/__init__.py @@ -16,6 +16,7 @@ TaskStreamItem, TextPart, TrajectoryLog, + ModelUsage, Usage, WriteOnly, ) @@ -36,6 +37,7 @@ "TaskStreamItem", "TextPart", "TrajectoryLog", + "ModelUsage", "Usage", "WriteOnly", ] diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py index 2006a5b82..e7f0edf9d 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py @@ -385,12 +385,59 @@ def _count(value: Any) -> int | None: return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None +def _check_counts(record: Any, names: Iterable[str]) -> None: + for name in names: + value = getattr(record, name) + if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value < 0): + raise ValueError(f"{name} must be a non-negative integer") + if record.input_includes_cache is not None and not isinstance(record.input_includes_cache, bool): + raise ValueError("input_includes_cache must be true, false or null") + if record.cost_usd is not None and ( + isinstance(record.cost_usd, bool) or not isinstance(record.cost_usd, (int, float)) or record.cost_usd < 0 + ): + raise ValueError("cost_usd cannot be negative") + + +_MODEL_COUNTERS = ("calls", "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens") + + +@dataclass(frozen=True, slots=True, kw_only=True) +class ModelUsage: + """One model's share of a turn's usage: the calls the turn made to ``model``, as it was called, and their counts, + read as ``Usage``'s are, with the agent's own cost for them when it has one.""" + + model: str + calls: int | None = None + input_tokens: int | None = None + output_tokens: int | None = None + cache_read_tokens: int | None = None + cache_write_tokens: int | None = None + input_includes_cache: bool | None = None + cost_usd: float | None = None + + def __post_init__(self) -> None: + if not isinstance(self.model, str) or not self.model: + raise ValueError("a model's usage must name the model") + _check_counts(self, _MODEL_COUNTERS) + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "ModelUsage": + """The model's usage ``to_dict`` wrote; a key this version doesn't know is ignored.""" + if not isinstance(data, Mapping): + raise TypeError("a model's usage must be a mapping") + return cls(**{f.name: data[f.name] for f in fields(cls) if data.get(f.name) is not None}) + + def to_dict(self) -> dict[str, Any]: + return {f.name: value for f in fields(self) if (value := getattr(self, f.name)) is not None} + + @dataclass(frozen=True, slots=True, kw_only=True) class Usage: """Common execution metrics plus runtime-specific, JSON-shaped details. ``cache_read_tokens`` and ``cache_write_tokens`` count the prompt tokens read from and written to the provider's prompt cache; ``input_includes_cache`` says whether ``input_tokens`` counts both of them (True), neither (False), or is unknown - (None), which a price needs to read the counts.""" + (None), which a price needs to read the counts. ``models`` is the counts by model, for a turn whose calls used + more than one: it covers every call the turn counted, so a price can charge each model at its own rate.""" tool_call_count: int | None = None input_tokens: int | None = None @@ -400,25 +447,15 @@ class Usage: cache_write_tokens: int | None = None input_includes_cache: bool | None = None cost_usd: float | None = None + models: tuple[ModelUsage, ...] = () provider_details: Mapping[str, Any] = field(default_factory=dict) def __post_init__(self) -> None: - for name in _USAGE_COUNTERS: - value = getattr(self, name) - if value is not None and ( - isinstance(value, bool) or not isinstance(value, int) or value < 0 - ): - raise ValueError(f"{name} must be a non-negative integer") - if self.input_includes_cache is not None and not isinstance( - self.input_includes_cache, bool - ): - raise ValueError("input_includes_cache must be true, false or null") - if self.cost_usd is not None and ( - isinstance(self.cost_usd, bool) - or not isinstance(self.cost_usd, (int, float)) - or self.cost_usd < 0 - ): - raise ValueError("cost_usd cannot be negative") + _check_counts(self, _USAGE_COUNTERS) + if isinstance(self.models, (str, bytes, Mapping)) or not isinstance(self.models, Iterable): + raise TypeError("models must be a list of each model's usage") + object.__setattr__(self, "models", tuple( + model if isinstance(model, ModelUsage) else ModelUsage.from_dict(model) for model in self.models)) if not isinstance(self.provider_details, Mapping): raise TypeError("provider_details must be a mapping") object.__setattr__( @@ -434,8 +471,10 @@ def from_dict(cls, data: Mapping[str, Any]) -> "Usage": known = { f.name: data[f.name] for f in fields(cls) - if f.name != "provider_details" and data.get(f.name) is not None + if f.name not in ("provider_details", "models") and data.get(f.name) is not None } + if data.get("models"): + known["models"] = data["models"] details = data.get("provider_details") return cls(**known, provider_details={} if details is None else details) @@ -481,17 +520,20 @@ def from_model_response(cls, usage: Mapping[str, Any]) -> "Usage": @property def is_empty(self) -> bool: - return all(value is None for value in self._values().values()) and not self.provider_details + return (all(value is None for value in self._values().values()) and not self.models + and not self.provider_details) def to_dict(self) -> dict[str, Any]: result = {name: value for name, value in self._values().items() if value is not None} + if self.models: + result["models"] = [model.to_dict() for model in self.models] if self.provider_details: result["provider_details"] = _thaw(self.provider_details) return result def _values(self) -> dict[str, Any]: - """Every field but ``provider_details``, by name, in declaration order.""" - return {f.name: getattr(self, f.name) for f in fields(self) if f.name != "provider_details"} + """Every field but ``models`` and ``provider_details``, by name, in declaration order.""" + return {f.name: getattr(self, f.name) for f in fields(self) if f.name not in ("models", "provider_details")} @dataclass(frozen=True, slots=True, kw_only=True) diff --git a/packages/agentenv-protocol/tests/test_usage_models.py b/packages/agentenv-protocol/tests/test_usage_models.py new file mode 100644 index 000000000..55dc5930c --- /dev/null +++ b/packages/agentenv-protocol/tests/test_usage_models.py @@ -0,0 +1,58 @@ +"""``Usage.models``, a turn's counts by model: each ``ModelUsage`` validated like ``Usage``'s own counts, written by +``to_dict`` only when there are some, read back by ``from_dict`` from mappings, and ignored by an older reader.""" + +import pytest + +from agentenv_protocol.a2a_agent import ModelUsage, Usage + +SONNET = ModelUsage(model="claude-sonnet-4-6", calls=2, input_tokens=9000, output_tokens=400, cache_read_tokens=8000, + cache_write_tokens=500, input_includes_cache=True, cost_usd=0.012) +HAIKU = ModelUsage(model="claude-haiku-4-5", calls=1, input_tokens=3000, output_tokens=90, input_includes_cache=True) +TURN = Usage(tool_call_count=3, input_tokens=12000, output_tokens=490, cache_read_tokens=8000, cache_write_tokens=500, + input_includes_cache=True, models=(SONNET, HAIKU)) + + +def test_a_turns_models_round_trip_and_are_written_only_when_there_are_some(): + assert Usage.from_dict(TURN.to_dict()) == TURN + assert TURN.to_dict()["models"] == [ + {"model": "claude-sonnet-4-6", "calls": 2, "input_tokens": 9000, "output_tokens": 400, + "cache_read_tokens": 8000, "cache_write_tokens": 500, "input_includes_cache": True, "cost_usd": 0.012}, + {"model": "claude-haiku-4-5", "calls": 1, "input_tokens": 3000, "output_tokens": 90, + "input_includes_cache": True}] + assert "models" not in Usage(input_tokens=5).to_dict() + assert not Usage(models=()).to_dict() and Usage(models=()).is_empty + assert not Usage(models=(HAIKU,)).is_empty + + +def test_models_given_as_mappings_are_read_as_each_models_usage_and_an_unknown_key_is_ignored(): + usage = Usage(models=[{"model": "gpt-4.1-mini", "input_tokens": 10, "output_tokens": 2, "reasoning_tokens": 1}]) + assert usage.models == (ModelUsage(model="gpt-4.1-mini", input_tokens=10, output_tokens=2),) + assert Usage.from_dict({"input_tokens": 10, "models": None}) == Usage(input_tokens=10) + + +@pytest.mark.parametrize("field", ["calls", "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"]) +@pytest.mark.parametrize("value", [-1, 1.5, "3", True]) +def test_a_models_count_that_isnt_a_non_negative_integer_is_refused(field, value): + with pytest.raises(ValueError, match=f"{field} must be a non-negative integer"): + ModelUsage(model="m", **{field: value}) + with pytest.raises(ValueError, match=field): + Usage.from_dict({"models": [{"model": "m", field: value}]}) + + +@pytest.mark.parametrize("row", [{"input_tokens": 1}, {"model": ""}, {"model": 7}]) +def test_a_models_usage_must_name_its_model(row): + with pytest.raises((ValueError, TypeError)): + Usage(models=[row]) + + +@pytest.mark.parametrize("models", [{"model": "m"}, "m", 3]) +def test_models_must_be_a_list(models): + with pytest.raises(TypeError, match="models must be a list"): + Usage(models=models) + + +def test_a_models_own_cost_and_flag_are_checked_as_usages_are(): + with pytest.raises(ValueError, match="cost_usd cannot be negative"): + ModelUsage(model="m", cost_usd=-1) + with pytest.raises(ValueError, match="input_includes_cache must be true, false or null"): + ModelUsage(model="m", input_includes_cache="yes") diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 0710d0b92..4c6e88798 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -12,7 +12,9 @@ from agentenv_protocol.a2a_agent import Usage from agent_env.config.model import ModelRole -from agent_env.config.model_pricing import PriceTable, ReportedBy, Tokens, litellm_prices, price +from agent_env.config.model_pricing import ( + Cost, CostStatus, PriceTable, ReportedBy, Tokens, litellm_prices, price, +) from agent_env.task_step.context import ATTEMPT_EPOCH, DeployedAgent, TaskStepContext if TYPE_CHECKING: @@ -22,16 +24,40 @@ _COUNTERS = ("tool_call_count", "input_tokens", "output_tokens", "total_tokens", "cache_read_tokens", "cache_write_tokens") _TOKEN_COUNTS = _COUNTERS[1:] +_MODEL_COUNTS = ("calls", "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens") # How many turns' unreadable values an entry keeps; ``unparsed_turns`` counts them all. _UNPARSED_TURNS_KEPT = 5 +class ModelEntry(TypedDict): + """One model's share of a usage entry: its counts summed over the role's turns, and its cost at that model's own + rate, keyed as an entry's cost is.""" + + model: Optional[str] + calls: Optional[int] + input_tokens: Optional[int] + output_tokens: Optional[int] + cache_read_tokens: Optional[int] + cache_write_tokens: Optional[int] + input_includes_cache: Optional[bool] + cost_usd: Optional[float] + cost_status: str + cost_source: Optional[str] + reported_cost_usd: Optional[float] + uncached_input_tokens: NotRequired[int] + unit_prices: NotRequired[dict[str, float]] + cost_assumed: NotRequired[list[str]] + unpriced_reason: NotRequired[str] + + class UsageEntry(TypedDict): """One role's usage in one step, as ``PromptResponse.usage`` and ``metadata["step_usage"]`` hold it. A count or a cost is None when nothing reported it, never 0. ``cost_usd`` is the cost ``cost_status`` and ``cost_source`` describe: priced from LiteLLM's price map, the ``uncached_input_tokens`` and the cache and output counts each at its ``unit_prices`` rate, the agent's own figure, or None when unpriced, with the agent's figure always in - ``reported_cost_usd``.""" + ``reported_cost_usd``. When a turn's calls used several models (``Usage.models``), ``models`` holds each model's + counts and cost at its own rate, ``cost_usd`` is their sum, and the entry has no ``unit_prices`` or + ``uncached_input_tokens`` of its own.""" role: str model: Optional[str] @@ -53,6 +79,7 @@ class UsageEntry(TypedDict): unit_prices: NotRequired[dict[str, float]] cost_assumed: NotRequired[list[str]] unpriced_reason: NotRequired[str] + models: NotRequired[list[ModelEntry]] partial: bool unreported_calls: NotRequired[int] unparsed: NotRequired[list[dict]] @@ -89,7 +116,8 @@ def entry(self, prices: PriceTable = PriceTable()) -> UsageEntry: ``input_includes_cache`` is the turns' flag when they agree, else None. ``partial`` says the sum is a lower bound: some turns reported a token count and others none, or a turn said some of its calls reported none (``unreported_calls``, which the entry sums, or a proxy's ``unreported``), or a turn was cut off - (``StepUsage.cut_off``).""" + (``StepUsage.cut_off``). When a turn says its counts by model (``Usage.models``), each model is priced at its own + rate (``_by_model``).""" reported = [usage for usage in self.turns if usage is not None] def total(name: str) -> Any: @@ -105,11 +133,17 @@ def total(name: str) -> Any: includes = flags.pop() if len(flags) == 1 else None charged = [Tokens.of(usage.to_dict()) for usage in counted] tokens = reduce(operator.add, charged) if charged and None not in charged else None - cost = price(tokens, self._reported(total("cost_usd")), model=self.model, - prices=prices, reported_by=self.reported_by) + reported_usd = self._reported(total("cost_usd")) + models = self._by_model(counted, prices) if any(usage.models for usage in counted) else None + cost = (price(tokens, reported_usd, model=self.model, prices=prices, reported_by=self.reported_by) + if models is None else _summed([cost for _, cost in models], reported_usd)) entry = UsageEntry(role=self.role, model=self.model, endpoint_host=self.endpoint_host, attempt=self.attempt, turns=len(self.turns), **counts, input_includes_cache=includes, **cost.fields(), partial=partial) + if models is not None: + entry.pop("uncached_input_tokens", None) + entry.pop("unit_prices", None) + entry["models"] = [row for row, _ in models] if unreported: entry["unreported_calls"] = sum(unreported) if self.unparsed: @@ -117,6 +151,28 @@ def total(name: str) -> Any: entry["unparsed_turns"] = len(self.unparsed) return entry + def _by_model(self, counted: list[Usage], prices: PriceTable) -> list[tuple[ModelEntry, Cost]]: + """The turns' counts by model, each priced at its own model's rate: a turn's ``models``, and a turn without + them counted as the role's model's.""" + shares: dict[Optional[str], list[Any]] = {} + for usage in counted: + for share in usage.models or (usage,): + shares.setdefault(share.model if usage.models else self.model, []).append(share) + rows = [] + for model, of in shares.items(): + def total(name: str) -> Any: + values = [value for share in of if (value := getattr(share, name, None)) is not None] + return sum(values) if values else None + + charged = [Tokens.of(share.to_dict()) for share in of] + tokens = reduce(operator.add, charged) if charged and None not in charged else None + cost = price(tokens, total("cost_usd"), model=model, prices=prices, reported_by=self.reported_by) + flags = {share.input_includes_cache for share in of} + row = ModelEntry(model=model, **{name: total(name) for name in _MODEL_COUNTS}, + input_includes_cache=flags.pop() if len(flags) == 1 else None, **cost.fields()) + rows.append((row, cost)) + return rows + def _reported(self, summed: Optional[float]) -> Optional[float]: """The turns' summed figure, as ``price`` takes it: an endpoint's bills only when every call carried one, since a sum of some calls' bills isn't the role's cost; without, the map prices all of them.""" @@ -125,6 +181,17 @@ def _reported(self, summed: Optional[float]) -> Optional[float]: return summed +def _summed(costs: list[Cost], reported_usd: Optional[float]) -> Cost: + """An entry's cost from its models' costs: their sum, as sure as the least sure of them. Unpriced when one is, so + a sum short of a model is never shown; reported, with its source, when one is the agent's figure; else priced.""" + unpriced = next((cost for cost in costs if cost.status is CostStatus.UNPRICED), None) + if unpriced is not None: + return Cost(None, CostStatus.UNPRICED, None, reported_usd, unpriced=unpriced.unpriced) + least = next((cost for cost in costs if cost.status is not CostStatus.PRICED), costs[0]) + assumed = tuple(dict.fromkeys(assumed for cost in costs for assumed in cost.assumed)) + return Cost(sum(cost.usd for cost in costs), least.status, least.source, reported_usd, assumed=assumed) + + def _unreported() -> Usage: """A turn or call whose usage never came back.""" return Usage(provider_details={"unreported": True}) diff --git a/tst/data/a2a_agent/agent.py b/tst/data/a2a_agent/agent.py index 194bfb0f2..84d1757e4 100644 --- a/tst/data/a2a_agent/agent.py +++ b/tst/data/a2a_agent/agent.py @@ -57,6 +57,7 @@ ObjectSnapshotSaveResponse, SnapshotUploadedObjects, TaskRequest, + ModelUsage, TaskResult, TextPart, Usage, @@ -74,6 +75,8 @@ LIST_SKILLS = "list-skills" RUN = "run " CDP = "cdp " +# "usage-models ": the turn reports those counts by model, as an agent whose calls used several models does. +USAGE_MODELS = "usage-models " CDP_LOAD_SECONDS = 30 RUN_TIMEOUT_SECONDS = 60 SKILLS_DIR = Path.home() / "skills" @@ -94,6 +97,16 @@ class EchoAgentConfig(AgentConfig): model_params: WriteOnly[dict[str, Any] | None] = None +def _usage(prompt: str, reply: str) -> Usage: + """The prompt's and reply's lengths as the turn's tokens, or the counts by model a ``usage-models`` line gives.""" + given = [line.removeprefix(USAGE_MODELS) for line in prompt.splitlines() if line.startswith(USAGE_MODELS)] + if not given: + return Usage(tool_call_count=0, input_tokens=len(prompt), output_tokens=len(reply)) + models = [ModelUsage.from_dict(row) for row in json.loads(given[0])] + return Usage(tool_call_count=0, input_tokens=sum(row.input_tokens or 0 for row in models), + output_tokens=sum(row.output_tokens or 0 for row in models), input_includes_cache=True, models=models) + + async def _read(part: FilePart) -> str: """What a file part holds, inline or at an HTTP(S) URL.""" scheme = "bytes" if part.bytes is not None else urlsplit(part.uri).scheme @@ -226,7 +239,7 @@ async def run(self, request: TaskRequest[EchoAgentConfig]) -> TaskResult: TaskResult.builder() .succeeded() .parts([TextPart(text=reply), *files]) - .usage(Usage(tool_call_count=0, input_tokens=len(prompt), output_tokens=len(reply))) + .usage(_usage(prompt, reply)) .build() ) diff --git a/tst/integration/cli/run_usage_by_model_test.py b/tst/integration/cli/run_usage_by_model_test.py new file mode 100644 index 000000000..f1f2d378d --- /dev/null +++ b/tst/integration/cli/run_usage_by_model_test.py @@ -0,0 +1,93 @@ +"""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.""" + +import json +import logging +import shutil +import subprocess +import uuid + +import pytest + +from agent_env.artifact.store import reset_artifact_store +from agent_env.bundle import run_bundle +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 ( + reset_agent_sandbox_provider, + reset_env_sandbox_provider, + reset_sandbox_provider, +) +from agent_env.store.routing import namespace_routing +from agent_env.task.store import get_task_instance_store +from tst.util.a2a_test_agent import put_test_agent +from tst.util.capabilities import missing_capability_reason + +pytestmark = [pytest.mark.integration, pytest.mark.int_test_slow] + +ROWS = [{"model": "gpt-4.1-mini", "calls": 2, "input_tokens": 9000, "output_tokens": 400, "cache_read_tokens": 8000, + "input_includes_cache": True}, + {"model": "gpt-4o-mini", "calls": 1, "input_tokens": 3000, "output_tokens": 90, "input_includes_cache": True}] + + +@pytest.fixture +def bundle(monkeypatch, tmp_path): + """A bundle whose one task prompts the echo agent to report ``ROWS`` as its turn's counts by model, in local + stores. Whatever ran, no sandbox work folder may be left behind.""" + if shutil.which("docker") is None or subprocess.run(["docker", "info"], capture_output=True).returncode != 0: + pytest.skip(missing_capability_reason("docker_daemon")) + sandboxes = tmp_path / "sandboxes" + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "state")) + monkeypatch.setenv("AGENT_ENV_DOCUMENT_STORE", "local") + monkeypatch.setenv("AGENT_ENV_OBJECT_STORE", "local") + monkeypatch.setenv("AGENT_ENV_LOCAL_SANDBOX_DIR", str(sandboxes)) + monkeypatch.delenv("LITELLM_BASE_URL", raising=False) + monkeypatch.delenv("LITELLM_API_KEY", raising=False) + config = tmp_path / "config.toml" + config.write_text('[model]\nbase_url = "http://127.0.0.1:9/v1"\napi_key = "unused"\n') + monkeypatch.setenv("AGENT_ENV_CONFIG", str(config)) + _reset() + configure() + agent = put_test_agent(f"usage-models-{uuid.uuid4().hex[:8]}") + root = tmp_path / "by-model" + (root / "tasks").mkdir(parents=True) + (root / "tasks" / "by-model.json").write_text(json.dumps([ + {"id": "solver", "type": "deploy_agent", "agent_name": "solver", "env_ids": [], "a2a_agent_id": agent.id}, + {"id": "prompt", "type": "prompt_agent", "agent_name": "solver", "prompt_id": "p", "model": "gpt-4.1-mini", + "prompt": "usage-models " + json.dumps(ROWS), "depends_on": [{"task_step_id": "solver"}]}, + ], indent=2)) + logging.disable(logging.CRITICAL) + try: + yield root + assert not sandboxes.exists() or not any(sandboxes.iterdir()), "a run left a sandbox work folder" + finally: + logging.disable(logging.NOTSET) + _reset() + + +def _reset(): + for reset in (reset_config, reset_artifact_store, reset_sandbox_provider, reset_env_sandbox_provider, + reset_agent_sandbox_provider): + reset() + + +def test_a_turns_counts_by_model_are_priced_at_each_models_rate_and_reach_the_ledger(bundle): + result = run_bundle(bundle) + [run] = result.runs + assert run.error is None, run.error or run.failed_steps + + [entry] = run.context.metadata["step_usage"]["prompt"] + prices = litellm_prices() + expected = [price(Tokens.of(row), None, model=row["model"], prices=prices, reported_by=ReportedBy.HARNESS).usd + for row in ROWS] + assert [(row["model"], row["calls"], row["cost_status"]) for row in entry["models"]] == [ + ("gpt-4.1-mini", 2, "priced"), ("gpt-4o-mini", 1, "priced")] + assert [row["cost_usd"] for row in entry["models"]] == pytest.approx(expected) + assert entry["cost_usd"] == pytest.approx(sum(expected)) and "unit_prices" not in entry + assert (entry["model"], entry["input_tokens"], entry["output_tokens"]) == ("gpt-4.1-mini", 12000, 490) + with namespace_routing(): + instance = get_task_instance_store().get(run.context.instance_id) + assert instance.usage_total["cost_usd"] == pytest.approx(sum(expected)) diff --git a/tst/unit/task_step/usage_models_test.py b/tst/unit/task_step/usage_models_test.py new file mode 100644 index 000000000..c1098d5d4 --- /dev/null +++ b/tst/unit/task_step/usage_models_test.py @@ -0,0 +1,98 @@ +"""A turn whose calls used several models (``Usage.models``) is priced model by model, each at its own rate from the +price map, its step's entry keeping a row per model; a turn without them is priced at the role's model, as before.""" + +import pytest +from agentenv_protocol.a2a_agent import ModelUsage, Usage + +from agent_env.a2a_agent.protocol import TerminalResponse, read_usage +from agent_env.config.model import ModelRole +from agent_env.config.model_pricing import ModelPrice, PriceTable +from agent_env.task_step import usage as usage_module +from agent_env.task_step.context import TaskStepContext +from agent_env.task_step.usage import StepUsage + +SONNET, HAIKU = "claude-sonnet-4-6", "claude-haiku-4-5" +PRICES = PriceTable({SONNET: ModelPrice(input=3.0, output=15.0, cache_read=0.3, cache_write=3.75), + HAIKU: ModelPrice(input=1.0, output=5.0, cache_read=0.1, cache_write=1.25)}, "litellm@test") +# A Sonnet solver's turn whose subagent ran on Haiku: Sonnet's 500 uncached input, 400 output, 8,000 cache reads and +# 500 cache writes cost $0.011775; Haiku's 3,000 input and 90 output, $0.00345. +SONNET_SHARE = ModelUsage(model=SONNET, calls=2, input_tokens=9000, output_tokens=400, cache_read_tokens=8000, + cache_write_tokens=500, input_includes_cache=True) +HAIKU_SHARE = ModelUsage(model=HAIKU, calls=1, input_tokens=3000, output_tokens=90, input_includes_cache=True) +TURN = Usage(input_tokens=12000, output_tokens=490, total_tokens=12490, cache_read_tokens=8000, cache_write_tokens=500, + input_includes_cache=True, models=(SONNET_SHARE, HAIKU_SHARE)) + + +def _entry(monkeypatch, *turns: Usage) -> dict: + monkeypatch.setattr(usage_module, "litellm_prices", lambda: PRICES) + context = TaskStepContext() + usage = StepUsage(context, "solve") + usage.start(ModelRole.SOLVER, SONNET, None) + for turn in turns: + usage.turn(ModelRole.SOLVER, TerminalResponse(response_text="", usage=turn)) + [entry] = context.metadata["step_usage"]["solve"] + return entry + + +def test_a_turns_models_are_each_priced_at_their_own_rate(monkeypatch): + entry = _entry(monkeypatch, TURN) + + sonnet, haiku = entry["models"] + assert (sonnet["model"], sonnet["calls"], sonnet["cost_status"]) == (SONNET, 2, "priced") + assert sonnet["cost_usd"] == pytest.approx(0.011775) and sonnet["uncached_input_tokens"] == 500 + assert (haiku["model"], haiku["cost_usd"], haiku["unit_prices"]["input"]) == (HAIKU, pytest.approx(0.00345), 1.0) + assert (entry["cost_status"], entry["cost_source"]) == ("priced", "litellm@test") + assert entry["cost_usd"] == pytest.approx(0.015225) + assert "unit_prices" not in entry and "uncached_input_tokens" not in entry + assert (entry["model"], entry["input_tokens"], entry["output_tokens"]) == (SONNET, 12000, 490) + + +def test_a_turn_without_models_beside_one_with_them_counts_as_the_roles_model(monkeypatch): + plain = Usage(input_tokens=1000, output_tokens=10, input_includes_cache=True) + + entry = _entry(monkeypatch, TURN, plain) + + sonnet, haiku = entry["models"] + assert (sonnet["model"], sonnet["calls"], sonnet["input_tokens"], sonnet["output_tokens"]) == (SONNET, 2, 10000, 410) + assert sonnet["cost_usd"] == pytest.approx(0.011775 + (1000 * 3.0 + 10 * 15.0) / 1e6) + assert entry["cost_usd"] == pytest.approx(sonnet["cost_usd"] + haiku["cost_usd"]) + + +def test_a_model_the_map_lacks_leaves_the_entry_unpriced_and_each_models_cost_is_kept(monkeypatch): + turn = Usage(input_tokens=9100, output_tokens=410, input_includes_cache=True, models=( + SONNET_SHARE, ModelUsage(model="mystery-1", input_tokens=100, output_tokens=10, input_includes_cache=True))) + + entry = _entry(monkeypatch, turn) + + assert (entry["cost_usd"], entry["cost_status"], entry["unpriced_reason"]) == (None, "unpriced", "no_price") + sonnet, mystery = entry["models"] + assert sonnet["cost_status"] == "priced" and sonnet["cost_usd"] == pytest.approx(0.011775) + assert (mystery["cost_usd"], mystery["unpriced_reason"]) == (None, "no_price") + + +def test_a_models_own_cost_stands_in_where_the_map_lacks_the_model(monkeypatch): + turn = Usage(input_tokens=9100, output_tokens=410, input_includes_cache=True, cost_usd=0.02, models=( + SONNET_SHARE, ModelUsage(model="mystery-1", input_tokens=100, output_tokens=10, input_includes_cache=True, + cost_usd=0.002))) + + entry = _entry(monkeypatch, turn) + + assert (entry["cost_status"], entry["cost_source"]) == ("reported", "harness") + assert entry["cost_usd"] == pytest.approx(0.011775 + 0.002) + assert entry["reported_cost_usd"] == 0.02 + + +def test_an_entry_whose_turns_have_no_models_keeps_its_shape(monkeypatch): + entry = _entry(monkeypatch, Usage(input_tokens=1000, output_tokens=10, input_includes_cache=True)) + + assert "models" not in entry and entry["unit_prices"]["input"] == 3.0 + assert entry["cost_usd"] == pytest.approx((1000 * 3.0 + 10 * 15.0) / 1e6) + + +def test_the_host_reads_a_turns_models_and_keeps_a_bad_one_aside(): + usage, unparsed = read_usage({"input_tokens": 3000, "output_tokens": 90, + "models": [{"model": HAIKU, "input_tokens": 3000, "output_tokens": 90}]}) + assert usage.models == (ModelUsage(model=HAIKU, input_tokens=3000, output_tokens=90),) and unparsed is None + + usage, unparsed = read_usage({"input_tokens": 3000, "models": [{"input_tokens": 3000}]}) + assert usage.models == () and usage.input_tokens == 3000 and "models" in unparsed From 09f796d299f720802b9e4e70a0bda6297968f0ed Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:17:42 -0800 Subject: [PATCH 2/5] fix(protocol): a turn that gives only its rows takes their sums, an agent's figure stands in only when complete, and from_dict refuses a falsy models value - Usage: a count a turn with models leaves out, that every row gives, is the rows' sum; so is the includes-cache flag the rows agree on. A model-only turn is priced from its rows. - RoleUsage: the agent's or endpoint's figure stands in for the map only when every turn, or every share of a model, carried one; a sum of some isn't the cost, so a model the map lacks is unpriced instead. - Usage.from_dict passes any non-null models value to the constructor, which refuses one that isn't a list. Co-Authored-By: Claude Opus 5.5 --- .../agentenv_protocol/a2a_agent/tasks/v1.py | 12 +++++-- .../tests/test_usage_models.py | 13 ++++++++ src/agent_env/task_step/usage.py | 10 +++--- tst/unit/task_step/usage_models_test.py | 32 +++++++++++++++++++ 4 files changed, 61 insertions(+), 6 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py index e7f0edf9d..47593d402 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/tasks/v1.py @@ -437,7 +437,8 @@ class Usage: ``cache_write_tokens`` count the prompt tokens read from and written to the provider's prompt cache; ``input_includes_cache`` says whether ``input_tokens`` counts both of them (True), neither (False), or is unknown (None), which a price needs to read the counts. ``models`` is the counts by model, for a turn whose calls used - more than one: it covers every call the turn counted, so a price can charge each model at its own rate.""" + more than one: it covers every call the turn counted, so a price can charge each model at its own rate. A count + the turn leaves out that every row gives is the rows' sum, and so is the includes-cache flag the rows agree on.""" tool_call_count: int | None = None input_tokens: int | None = None @@ -456,6 +457,13 @@ def __post_init__(self) -> None: raise TypeError("models must be a list of each model's usage") object.__setattr__(self, "models", tuple( model if isinstance(model, ModelUsage) else ModelUsage.from_dict(model) for model in self.models)) + for name in _MODEL_COUNTERS[1:]: + values = [getattr(model, name) for model in self.models] + if getattr(self, name) is None and values and None not in values: + object.__setattr__(self, name, sum(values)) + flags = {model.input_includes_cache for model in self.models} + if self.input_includes_cache is None and len(flags) == 1: + object.__setattr__(self, "input_includes_cache", flags.pop()) if not isinstance(self.provider_details, Mapping): raise TypeError("provider_details must be a mapping") object.__setattr__( @@ -473,7 +481,7 @@ def from_dict(cls, data: Mapping[str, Any]) -> "Usage": for f in fields(cls) if f.name not in ("provider_details", "models") and data.get(f.name) is not None } - if data.get("models"): + if data.get("models") is not None: known["models"] = data["models"] details = data.get("provider_details") return cls(**known, provider_details={} if details is None else details) diff --git a/packages/agentenv-protocol/tests/test_usage_models.py b/packages/agentenv-protocol/tests/test_usage_models.py index 55dc5930c..642a8344b 100644 --- a/packages/agentenv-protocol/tests/test_usage_models.py +++ b/packages/agentenv-protocol/tests/test_usage_models.py @@ -56,3 +56,16 @@ def test_a_models_own_cost_and_flag_are_checked_as_usages_are(): ModelUsage(model="m", cost_usd=-1) with pytest.raises(ValueError, match="input_includes_cache must be true, false or null"): ModelUsage(model="m", input_includes_cache="yes") + + +def test_a_turn_that_gives_only_its_rows_takes_their_sums_as_its_counts(): + usage = Usage(models=(SONNET, HAIKU)) + assert (usage.input_tokens, usage.output_tokens, usage.input_includes_cache) == (12000, 490, True) + assert (usage.cache_read_tokens, usage.cache_write_tokens) == (None, None) + assert Usage(input_tokens=5, models=(HAIKU,)).input_tokens == 5 + + +@pytest.mark.parametrize("models", [{}, "", 0, False]) +def test_from_dict_refuses_a_models_value_that_isnt_a_list_even_when_empty(models): + with pytest.raises(TypeError, match="models must be a list"): + Usage.from_dict({"input_tokens": 1, "models": models}) diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index 4c6e88798..b3a7f06ce 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -166,7 +166,8 @@ def total(name: str) -> Any: charged = [Tokens.of(share.to_dict()) for share in of] tokens = reduce(operator.add, charged) if charged and None not in charged else None - cost = price(tokens, total("cost_usd"), model=model, prices=prices, reported_by=self.reported_by) + reported = total("cost_usd") if all(share.cost_usd is not None for share in of) else None + cost = price(tokens, reported, model=model, prices=prices, reported_by=self.reported_by) flags = {share.input_includes_cache for share in of} row = ModelEntry(model=model, **{name: total(name) for name in _MODEL_COUNTS}, input_includes_cache=flags.pop() if len(flags) == 1 else None, **cost.fields()) @@ -174,9 +175,10 @@ def total(name: str) -> Any: return rows def _reported(self, summed: Optional[float]) -> Optional[float]: - """The turns' summed figure, as ``price`` takes it: an endpoint's bills only when every call carried one, since - a sum of some calls' bills isn't the role's cost; without, the map prices all of them.""" - if self.reported_by is ReportedBy.PROVIDER and any(u is None or u.cost_usd is None for u in self.turns): + """The turns' summed figure, as ``price`` takes it: the agent's or endpoint's figures only when every turn + carried one, since a sum of some turns' isn't the role's cost; without, the map prices all of them, and a + model the map lacks is unpriced.""" + if any(u is None or u.cost_usd is None for u in self.turns): return None return summed diff --git a/tst/unit/task_step/usage_models_test.py b/tst/unit/task_step/usage_models_test.py index c1098d5d4..a3dc0c312 100644 --- a/tst/unit/task_step/usage_models_test.py +++ b/tst/unit/task_step/usage_models_test.py @@ -96,3 +96,35 @@ def test_the_host_reads_a_turns_models_and_keeps_a_bad_one_aside(): usage, unparsed = read_usage({"input_tokens": 3000, "models": [{"input_tokens": 3000}]}) assert usage.models == () and usage.input_tokens == 3000 and "models" in unparsed + + +def test_a_turn_that_gives_only_its_rows_is_priced_from_them(monkeypatch): + entry = _entry(monkeypatch, Usage(models=(SONNET_SHARE, HAIKU_SHARE))) + + assert entry["cost_usd"] == pytest.approx(0.015225) and entry["input_tokens"] == 12000 + + +def test_an_agents_figure_for_a_model_the_map_lacks_stands_in_only_when_every_turn_gave_one(monkeypatch): + def mystery(cost): + return Usage(models=(ModelUsage(model="mystery-1", input_tokens=100, output_tokens=10, + input_includes_cache=True, cost_usd=cost),)) + + entry = _entry(monkeypatch, mystery(0.002), mystery(None)) + [row] = entry["models"] + assert (row["cost_usd"], row["cost_status"]) == (None, "unpriced") + assert (entry["cost_usd"], entry["cost_status"]) == (None, "unpriced") + + entry = _entry(monkeypatch, mystery(0.002), mystery(0.003)) + assert (entry["cost_status"], entry["cost_usd"]) == ("reported", pytest.approx(0.005)) + + +def test_a_role_on_one_model_the_map_lacks_takes_the_agents_figure_only_when_every_turn_gave_one(monkeypatch): + monkeypatch.setattr(usage_module, "litellm_prices", lambda: PRICES) + context = TaskStepContext() + usage = StepUsage(context, "solve") + usage.start(ModelRole.SOLVER, "mystery-1", None) + for cost in (0.002, None): + usage.turn(ModelRole.SOLVER, TerminalResponse(response_text="", usage=Usage( + input_tokens=100, output_tokens=10, input_includes_cache=True, cost_usd=cost))) + [entry] = context.metadata["step_usage"]["solve"] + assert (entry["cost_usd"], entry["cost_status"], entry["reported_cost_usd"]) == (None, "unpriced", None) From 85deac2c24e5f7676b601ecd70e43e75e721944a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:24:58 -0800 Subject: [PATCH 3/5] fix(usage): a turn with model rows is counted even when its rows don't share a count A row that can't be priced, one missing its output say, leaves the entry unpriced instead of the turn being left out. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task_step/usage.py | 3 ++- tst/unit/task_step/usage_models_test.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index b3a7f06ce..bcc2b38a3 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -124,7 +124,8 @@ def total(name: str) -> Any: values = [getattr(usage, name) for usage in reported if getattr(usage, name) is not None] return sum(values) if values else None - counted = [usage for usage in reported if any(getattr(usage, name) is not None for name in _TOKEN_COUNTS)] + counted = [usage for usage in reported + if usage.models or any(getattr(usage, name) is not None for name in _TOKEN_COUNTS)] flags = {usage.input_includes_cache for usage in counted} unreported = [n for usage in reported if (n := _unreported_calls(usage))] partial = (0 < len(counted) < len(self.turns) or bool(unreported) diff --git a/tst/unit/task_step/usage_models_test.py b/tst/unit/task_step/usage_models_test.py index a3dc0c312..d2c0c75f9 100644 --- a/tst/unit/task_step/usage_models_test.py +++ b/tst/unit/task_step/usage_models_test.py @@ -128,3 +128,15 @@ def test_a_role_on_one_model_the_map_lacks_takes_the_agents_figure_only_when_eve input_tokens=100, output_tokens=10, input_includes_cache=True, cost_usd=cost))) [entry] = context.metadata["step_usage"]["solve"] assert (entry["cost_usd"], entry["cost_status"], entry["reported_cost_usd"]) == (None, "unpriced", None) + + +def test_a_turn_whose_rows_cant_all_be_priced_leaves_the_entry_unpriced_rather_than_dropping(monkeypatch): + rows = (ModelUsage(model=SONNET, input_tokens=1000, output_tokens=10, input_includes_cache=True), + ModelUsage(model=HAIKU, output_tokens=5)) + priced = Usage(input_tokens=1000, output_tokens=10, input_includes_cache=True) + + entry = _entry(monkeypatch, priced, Usage(models=rows)) + + sonnet, haiku = entry["models"] + assert (haiku["cost_usd"], haiku["unpriced_reason"]) == (None, "no_tokens") + assert (entry["cost_usd"], entry["cost_status"]) == (None, "unpriced") and entry["turns"] == 2 From a912aa31df809e6441a6a7b240e9df854b7ee805 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:37:16 -0800 Subject: [PATCH 4/5] fix(usage): reported_cost_usd keeps the figures that came, though only complete ones stand in for the map The agent's or endpoint's figures stand in for a price only when every turn, or every share of a model, gave one; their sum is kept beside the cost either way, as before, so an entry with a cut-off turn keeps the agent's figure. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/task_step/usage.py | 31 ++++++++++++++----------- tst/unit/task_step/usage_models_test.py | 15 +++++++++++- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index bcc2b38a3..b719c1366 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -5,7 +5,7 @@ from __future__ import annotations import operator -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from functools import reduce from typing import TYPE_CHECKING, Any, NotRequired, Optional, TypedDict @@ -134,10 +134,10 @@ def total(name: str) -> Any: includes = flags.pop() if len(flags) == 1 else None charged = [Tokens.of(usage.to_dict()) for usage in counted] tokens = reduce(operator.add, charged) if charged and None not in charged else None - reported_usd = self._reported(total("cost_usd")) + figures = [usage.cost_usd if usage is not None else None for usage in self.turns] models = self._by_model(counted, prices) if any(usage.models for usage in counted) else None - cost = (price(tokens, reported_usd, model=self.model, prices=prices, reported_by=self.reported_by) - if models is None else _summed([cost for _, cost in models], reported_usd)) + cost = (_priced(tokens, figures, model=self.model, prices=prices, reported_by=self.reported_by) + if models is None else _summed([cost for _, cost in models], total("cost_usd"))) entry = UsageEntry(role=self.role, model=self.model, endpoint_host=self.endpoint_host, attempt=self.attempt, turns=len(self.turns), **counts, input_includes_cache=includes, **cost.fields(), partial=partial) @@ -167,21 +167,26 @@ def total(name: str) -> Any: charged = [Tokens.of(share.to_dict()) for share in of] tokens = reduce(operator.add, charged) if charged and None not in charged else None - reported = total("cost_usd") if all(share.cost_usd is not None for share in of) else None - cost = price(tokens, reported, model=model, prices=prices, reported_by=self.reported_by) + cost = _priced(tokens, [share.cost_usd for share in of], model=model, prices=prices, + reported_by=self.reported_by) flags = {share.input_includes_cache for share in of} row = ModelEntry(model=model, **{name: total(name) for name in _MODEL_COUNTS}, input_includes_cache=flags.pop() if len(flags) == 1 else None, **cost.fields()) rows.append((row, cost)) return rows - def _reported(self, summed: Optional[float]) -> Optional[float]: - """The turns' summed figure, as ``price`` takes it: the agent's or endpoint's figures only when every turn - carried one, since a sum of some turns' isn't the role's cost; without, the map prices all of them, and a - model the map lacks is unpriced.""" - if any(u is None or u.cost_usd is None for u in self.turns): - return None - return summed + + +def _priced(tokens: Optional[Tokens], figures: list[Optional[float]], *, model: Optional[str], prices: PriceTable, + reported_by: ReportedBy) -> Cost: + """``price`` given the turns' (or a model's shares') own figures: they stand in for the map only when every one + came, since a sum of some isn't the cost, so a model the map lacks is then unpriced; their sum is kept beside the + cost as ``reported_usd`` either way.""" + given = [figure for figure in figures if figure is not None] + summed = sum(given) if given else None + cost = price(tokens, summed if len(given) == len(figures) else None, model=model, prices=prices, + reported_by=reported_by) + return cost if cost.reported_usd == summed else replace(cost, reported_usd=summed) def _summed(costs: list[Cost], reported_usd: Optional[float]) -> Cost: diff --git a/tst/unit/task_step/usage_models_test.py b/tst/unit/task_step/usage_models_test.py index d2c0c75f9..a8ae41d83 100644 --- a/tst/unit/task_step/usage_models_test.py +++ b/tst/unit/task_step/usage_models_test.py @@ -127,7 +127,20 @@ def test_a_role_on_one_model_the_map_lacks_takes_the_agents_figure_only_when_eve usage.turn(ModelRole.SOLVER, TerminalResponse(response_text="", usage=Usage( input_tokens=100, output_tokens=10, input_includes_cache=True, cost_usd=cost))) [entry] = context.metadata["step_usage"]["solve"] - assert (entry["cost_usd"], entry["cost_status"], entry["reported_cost_usd"]) == (None, "unpriced", None) + assert (entry["cost_usd"], entry["cost_status"], entry["reported_cost_usd"]) == (None, "unpriced", 0.002) + + +def test_a_cut_off_turn_beside_a_reported_one_keeps_the_agents_figure_beside_the_maps_price(monkeypatch): + monkeypatch.setattr(usage_module, "litellm_prices", lambda: PRICES) + context = TaskStepContext() + usage = StepUsage(context, "solve") + usage.start(ModelRole.SOLVER, SONNET, None) + usage.turn(ModelRole.SOLVER, TerminalResponse(response_text="", usage=Usage( + input_tokens=1000, output_tokens=10, input_includes_cache=True, cost_usd=0.004))) + usage.cut_off(ModelRole.SOLVER) + [entry] = context.metadata["step_usage"]["solve"] + assert (entry["cost_status"], entry["reported_cost_usd"], entry["partial"]) == ("priced", 0.004, True) + assert entry["cost_usd"] == pytest.approx((1000 * 3.0 + 10 * 15.0) / 1e6) def test_a_turn_whose_rows_cant_all_be_priced_leaves_the_entry_unpriced_rather_than_dropping(monkeypatch): From 7ace06f7a8c2d963f512b2c9162fcb66c19a016a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:44:40 -0800 Subject: [PATCH 5/5] refactor(usage): one set of summing helpers for an entry and its models' rows, and a shared cost-fields type - _total, _tokens and _agreed sum a role's turns and a model's shares alike; _priced is _cost_of, so it isn't mistaken for model_pricing's own _priced. - Cost.fields writes the uncached input and unit prices only when the cost has them, so an entry priced per model needs no keys popped. - CostFields holds the cost keys ModelEntry and UsageEntry share. - _by_model files a turn's rows under their models, and a turn without them under the role's, in plain if/else. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/config/model_pricing.py | 6 +- src/agent_env/task_step/usage.py | 100 +++++++++++++------------- 2 files changed, 54 insertions(+), 52 deletions(-) diff --git a/src/agent_env/config/model_pricing.py b/src/agent_env/config/model_pricing.py index a37584313..ea781d942 100644 --- a/src/agent_env/config/model_pricing.py +++ b/src/agent_env/config/model_pricing.py @@ -166,11 +166,13 @@ class Cost: unpriced: Optional[Unpriced] = None def fields(self) -> dict[str, Any]: - """The cost as a usage entry's keys.""" + """The cost as a usage entry's keys; the uncached input and unit prices only when it has them, as a price from + the map does and a sum of several models' costs doesn't.""" record: dict[str, Any] = {"cost_usd": self.usd, "cost_status": self.status.value, "cost_source": self.source, "reported_cost_usd": self.reported_usd} - if self.status is CostStatus.PRICED: + if self.uncached_input is not None: record["uncached_input_tokens"] = self.uncached_input + if self.unit_prices is not None: record["unit_prices"] = self.unit_prices if self.assumed: record["cost_assumed"] = [assumed.value for assumed in self.assumed] diff --git a/src/agent_env/task_step/usage.py b/src/agent_env/task_step/usage.py index b719c1366..6c15ece85 100644 --- a/src/agent_env/task_step/usage.py +++ b/src/agent_env/task_step/usage.py @@ -5,6 +5,7 @@ from __future__ import annotations import operator +from collections.abc import Iterable from dataclasses import dataclass, field, replace from functools import reduce from typing import TYPE_CHECKING, Any, NotRequired, Optional, TypedDict @@ -29,17 +30,9 @@ _UNPARSED_TURNS_KEPT = 5 -class ModelEntry(TypedDict): - """One model's share of a usage entry: its counts summed over the role's turns, and its cost at that model's own - rate, keyed as an entry's cost is.""" +class CostFields(TypedDict): + """A cost as an entry or a model's row keeps it (``Cost.fields``).""" - model: Optional[str] - calls: Optional[int] - input_tokens: Optional[int] - output_tokens: Optional[int] - cache_read_tokens: Optional[int] - cache_write_tokens: Optional[int] - input_includes_cache: Optional[bool] cost_usd: Optional[float] cost_status: str cost_source: Optional[str] @@ -50,7 +43,20 @@ class ModelEntry(TypedDict): unpriced_reason: NotRequired[str] -class UsageEntry(TypedDict): +class ModelEntry(CostFields): + """One model's share of a usage entry: its counts summed over the role's turns, and its cost at that model's own + rate.""" + + model: Optional[str] + calls: Optional[int] + input_tokens: Optional[int] + output_tokens: Optional[int] + cache_read_tokens: Optional[int] + cache_write_tokens: Optional[int] + input_includes_cache: Optional[bool] + + +class UsageEntry(CostFields): """One role's usage in one step, as ``PromptResponse.usage`` and ``metadata["step_usage"]`` hold it. A count or a cost is None when nothing reported it, never 0. ``cost_usd`` is the cost ``cost_status`` and ``cost_source`` describe: priced from LiteLLM's price map, the ``uncached_input_tokens`` and the cache and output counts each at @@ -71,14 +77,6 @@ class UsageEntry(TypedDict): cache_read_tokens: Optional[int] cache_write_tokens: Optional[int] input_includes_cache: Optional[bool] - cost_usd: Optional[float] - cost_status: str - cost_source: Optional[str] - reported_cost_usd: Optional[float] - uncached_input_tokens: NotRequired[int] - unit_prices: NotRequired[dict[str, float]] - cost_assumed: NotRequired[list[str]] - unpriced_reason: NotRequired[str] models: NotRequired[list[ModelEntry]] partial: bool unreported_calls: NotRequired[int] @@ -119,31 +117,19 @@ def entry(self, prices: PriceTable = PriceTable()) -> UsageEntry: (``StepUsage.cut_off``). When a turn says its counts by model (``Usage.models``), each model is priced at its own rate (``_by_model``).""" reported = [usage for usage in self.turns if usage is not None] - - def total(name: str) -> Any: - values = [getattr(usage, name) for usage in reported if getattr(usage, name) is not None] - return sum(values) if values else None - counted = [usage for usage in reported if usage.models or any(getattr(usage, name) is not None for name in _TOKEN_COUNTS)] - flags = {usage.input_includes_cache for usage in counted} unreported = [n for usage in reported if (n := _unreported_calls(usage))] partial = (0 < len(counted) < len(self.turns) or bool(unreported) or any(usage.provider_details.get("unreported") for usage in reported)) - counts = {name: total(name) for name in _COUNTERS} - includes = flags.pop() if len(flags) == 1 else None - charged = [Tokens.of(usage.to_dict()) for usage in counted] - tokens = reduce(operator.add, charged) if charged and None not in charged else None figures = [usage.cost_usd if usage is not None else None for usage in self.turns] models = self._by_model(counted, prices) if any(usage.models for usage in counted) else None - cost = (_priced(tokens, figures, model=self.model, prices=prices, reported_by=self.reported_by) - if models is None else _summed([cost for _, cost in models], total("cost_usd"))) + cost = (_cost_of(_tokens(counted), figures, model=self.model, prices=prices, reported_by=self.reported_by) + if models is None else _summed([cost for _, cost in models], _total(reported, "cost_usd"))) entry = UsageEntry(role=self.role, model=self.model, endpoint_host=self.endpoint_host, attempt=self.attempt, - turns=len(self.turns), **counts, input_includes_cache=includes, **cost.fields(), - partial=partial) + turns=len(self.turns), **{name: _total(reported, name) for name in _COUNTERS}, + input_includes_cache=_agreed(counted), **cost.fields(), partial=partial) if models is not None: - entry.pop("uncached_input_tokens", None) - entry.pop("unit_prices", None) entry["models"] = [row for row, _ in models] if unreported: entry["unreported_calls"] = sum(unreported) @@ -157,28 +143,42 @@ def _by_model(self, counted: list[Usage], prices: PriceTable) -> list[tuple[Mode them counted as the role's model's.""" shares: dict[Optional[str], list[Any]] = {} for usage in counted: - for share in usage.models or (usage,): - shares.setdefault(share.model if usage.models else self.model, []).append(share) + if usage.models: + for share in usage.models: + shares.setdefault(share.model, []).append(share) + else: + shares.setdefault(self.model, []).append(usage) rows = [] for model, of in shares.items(): - def total(name: str) -> Any: - values = [value for share in of if (value := getattr(share, name, None)) is not None] - return sum(values) if values else None - - charged = [Tokens.of(share.to_dict()) for share in of] - tokens = reduce(operator.add, charged) if charged and None not in charged else None - cost = _priced(tokens, [share.cost_usd for share in of], model=model, prices=prices, - reported_by=self.reported_by) - flags = {share.input_includes_cache for share in of} - row = ModelEntry(model=model, **{name: total(name) for name in _MODEL_COUNTS}, - input_includes_cache=flags.pop() if len(flags) == 1 else None, **cost.fields()) + cost = _cost_of(_tokens(of), [share.cost_usd for share in of], model=model, prices=prices, + reported_by=self.reported_by) + row = ModelEntry(model=model, **{name: _total(of, name) for name in _MODEL_COUNTS}, + input_includes_cache=_agreed(of), **cost.fields()) rows.append((row, cost)) return rows +def _total(records: Iterable[Any], name: str) -> Any: + """The sum of ``name`` over the records that give it, None when none does, never 0.""" + values = [value for record in records if (value := getattr(record, name, None)) is not None] + return sum(values) if values else None + + +def _tokens(records: list[Any]) -> Optional[Tokens]: + """The records' tokens summed, each read by its own ``input_includes_cache``; None when one lacks its input or + output, so a sum that can't be charged in full isn't priced short.""" + charged = [Tokens.of(record.to_dict()) for record in records] + return reduce(operator.add, charged) if charged and None not in charged else None + + +def _agreed(records: list[Any]) -> Optional[bool]: + """The records' ``input_includes_cache`` when they all agree on it, else None.""" + flags = {record.input_includes_cache for record in records} + return flags.pop() if len(flags) == 1 else None + -def _priced(tokens: Optional[Tokens], figures: list[Optional[float]], *, model: Optional[str], prices: PriceTable, - reported_by: ReportedBy) -> Cost: +def _cost_of(tokens: Optional[Tokens], figures: list[Optional[float]], *, model: Optional[str], prices: PriceTable, + reported_by: ReportedBy) -> Cost: """``price`` given the turns' (or a model's shares') own figures: they stand in for the map only when every one came, since a sum of some isn't the cost, so a model the map lacks is then unpriced; their sum is kept beside the cost as ``reported_usd`` either way."""