Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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@<version>`, `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
Expand Down
9 changes: 9 additions & 0 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@
TaskStreamItem,
TextPart,
TrajectoryLog,
ModelUsage,
Usage,
WriteOnly,
)
Expand Down Expand Up @@ -272,6 +273,7 @@
"TriggerDecideRequest",
"TriggerRegisterRequest",
"Uploaded",
"ModelUsage",
"Usage",
"WriteNamespaceGrant",
"WriteObject",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
TaskStreamItem,
TextPart,
TrajectoryLog,
ModelUsage,
Usage,
WriteOnly,
)
Expand All @@ -36,6 +37,7 @@
"TaskStreamItem",
"TextPart",
"TrajectoryLog",
"ModelUsage",
"Usage",
"WriteOnly",
]
Original file line number Diff line number Diff line change
Expand Up @@ -385,12 +385,60 @@ 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. 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
Expand All @@ -400,25 +448,22 @@ 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))
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__(
Expand All @@ -434,8 +479,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") is not None:
known["models"] = data["models"]
details = data.get("provider_details")
return cls(**known, provider_details={} if details is None else details)

Expand Down Expand Up @@ -481,17 +528,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)
Expand Down
71 changes: 71 additions & 0 deletions packages/agentenv-protocol/tests/test_usage_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""``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")


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})
6 changes: 4 additions & 2 deletions src/agent_env/config/model_pricing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading
Loading