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
16 changes: 8 additions & 8 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1431,14 +1431,14 @@ 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.
An agent that knows each call's model gives a turn's counts by model in
`Usage.models`, on every turn: 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. That prices a
subagent on a smaller model, a side call for a title, or a whole turn a CLI
ran on another model at that model's own rate. The rows cover every call the
turn counted; a call the agent can't name goes under the model it was
configured with. A turn without rows 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
extension,
)
from .framework import AgentEnvAgent, AgentIdentity, a2a_agent
from .tasks.v1 import AgentConfig, TaskRequest, TaskResult, TextPart, TrajectoryLog, Usage
from .tasks.v1 import AgentConfig, ModelUsage, TaskRequest, TaskResult, TextPart, TrajectoryLog, Usage
from ..tool_client import ToolResult, ToolSession, ToolSessionError
from ..transfers import download
from ..types import EnvironmentTool
Expand Down Expand Up @@ -112,7 +112,8 @@ class _Turn:
pending: list[tuple[str, str]] = field(default_factory=list) # (tool, its canonical arguments) not yet run
last_event: str = field(default_factory=lambda: _now())
model: str | None = None
model_usage: list[Usage] = field(default_factory=list) # each recorded model call's, its input counting the cache
# Each recorded model call's model, as it named it, and usage, its input counting the cache.
model_calls: list[tuple[str | None, Usage]] = field(default_factory=list)


@contextlib.asynccontextmanager
Expand Down Expand Up @@ -250,7 +251,7 @@ async def record(self, request: ProxyRecordRequest) -> None:
turn.recorded = True
turn.model = request.model or turn.model
span = _span("chat", "chat", turn.last_event, turn.model, completion={"content": content})
turn.model_usage.append(usage)
turn.model_calls.append((request.model, usage))
for key in ("input_tokens", "output_tokens"):
if (count := getattr(usage, key)) is not None:
span["attributes"][f"gen_ai.usage.{key}"] = count
Expand Down Expand Up @@ -560,7 +561,7 @@ def _turn_usage(turn: _Turn) -> Usage:
(``cache_unsettled``), which leaves the turn's flag unknown; how many usages were in a shape none of the readers
know (``unrecognized``); and each provider's split of the cache writes, summed, a reported ``Usage``'s split
counted only where it holds counts, as its ``provider_details`` may hold anything."""
calls = turn.model_usage
calls = [usage for _, usage in turn.model_calls]
sums, unreported = {}, {}
for name in _USAGE_SUMS:
values = [value for call in calls if (value := getattr(call, name)) is not None]
Expand All @@ -581,7 +582,18 @@ def _turn_usage(turn: _Turn) -> Usage:
**({"unrecognized": unrecognized} if unrecognized else {}), **splits}
return Usage(tool_call_count=len(turn.actions), **sums,
input_includes_cache=True if sums["input_tokens"] is not None and not unsettled else None,
provider_details=details if calls else {})
models=_by_model(turn), provider_details=details if calls else {})


def _by_model(turn: _Turn) -> tuple[ModelUsage, ...]:
"""The turn's recorded calls by the model each named (``ModelUsage.of``); none when a call named none, since the
proxy has no configured model to count it under."""
by_model: dict[str, list[Usage]] = {}
for named, usage in turn.model_calls:
if named is None:
return ()
by_model.setdefault(named, []).append(usage)
return tuple(ModelUsage.of(name, of) for name, of in by_model.items())


def _span(name: str, operation: str, started: str, model: str | None, *, prompt: Any = None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,23 @@ def __post_init__(self) -> None:
raise ValueError("a model's usage must name the model")
_check_counts(self, _MODEL_COUNTERS)

@classmethod
def of(cls, model: str, usages: Iterable["Usage"]) -> "ModelUsage":
"""``model``'s row from the usages of its calls, one each: each count summed over the calls that gave it, None
when none did; their cost only when every call reported one, since a sum of some isn't the model's cost; and
the includes-cache flag the calls that gave input counts agree on, else None."""
usages = list(usages)

def total(name: str) -> Any:
values = [value for usage in usages if (value := getattr(usage, name)) is not None]
return sum(values) if values else None

costs = [usage.cost_usd for usage in usages]
flags = {usage.input_includes_cache for usage in usages if usage.input_tokens is not None}
return cls(model=model, calls=len(usages), **{name: total(name) for name in _MODEL_COUNTERS[1:]},
input_includes_cache=flags.pop() if len(flags) == 1 else None,
cost_usd=sum(costs) if costs and None not in costs else None)

@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."""
Expand All @@ -436,8 +453,8 @@ 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. ``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
(None), which a price needs to read the counts. ``models`` is the counts by model, from an agent that knows each
call's model: 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
Expand Down
39 changes: 39 additions & 0 deletions packages/agentenv-protocol/tests/test_a2a_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,33 @@ def test_a_turns_usage_sums_its_recorded_calls_with_input_counting_the_cache(cli
"input_tokens": 1, "output_tokens": 1, "total_tokens": 1, "cache_read_tokens": 1, "cache_write_tokens": 2}}}


def _recorded_turn(client, calls) -> dict:
"""The usage of a turn whose recorded calls are ``calls``, each a model name (or None) and its usage."""
task_id = _send(client, "go")
for model, usage in calls:
assert _proxy(client, "record", task_id=task_id, message="Thinking.", usage=usage,
**({"model": model} if model else {})).status_code == 200
_proxy(client, "reply", task_id=task_id, parts=[{"kind": "text", "text": "Done."}])
return _usage(_settled(client, task_id))


def test_a_turns_recorded_calls_are_given_by_the_model_each_named(client):
usage = _recorded_turn(client, [("gpt-4.1-mini", {"prompt_tokens": 1000, "completion_tokens": 10}),
("gpt-4o-mini", {"prompt_tokens": 300, "completion_tokens": 5}),
("gpt-4o-mini", None)])

assert usage["models"] == [
{"model": "gpt-4.1-mini", "calls": 1, "input_tokens": 1000, "output_tokens": 10, "input_includes_cache": True},
{"model": "gpt-4o-mini", "calls": 2, "input_tokens": 300, "output_tokens": 5, "input_includes_cache": True}]


def test_a_turn_with_a_call_that_named_no_model_gives_no_rows(client):
usage = _recorded_turn(client, [("gpt-4.1-mini", {"prompt_tokens": 1000, "completion_tokens": 10}),
(None, {"prompt_tokens": 200, "completion_tokens": 2})])

assert "models" not in usage and usage["input_tokens"] == 1200


def test_counts_a_recorded_call_doesnt_give_or_cant_be_read_are_left_out(client):
task_id = _send(client, "go")
for usage in ({"prompt_tokens": "9", "completion_tokens": True, "prompt_tokens_details": "none"},
Expand Down Expand Up @@ -837,3 +864,15 @@ def test_what_a_turn_still_runs_is_stopped_when_the_app_stops(monkeypatch, tmp_p
time.sleep(0.02)

_stopped(int((tmp_path / "child").read_text()))


def test_a_models_cost_is_its_calls_only_when_every_one_reported_one(client):
task_id = _send(client, "go")
for usage in ({"agentenv_usage": {"input_tokens": 10, "output_tokens": 1, "cost_usd": 0.01}},
{"prompt_tokens": 20, "completion_tokens": 2}):
assert _proxy(client, "record", task_id=task_id, message="Thinking.", usage=usage,
model="policy-model").status_code == 200
_proxy(client, "reply", task_id=task_id, parts=[{"kind": "text", "text": "Done."}])

[row] = _usage(_settled(client, task_id))["models"]
assert (row["calls"], row["input_tokens"], "cost_usd" in row) == (2, 30, False)
18 changes: 18 additions & 0 deletions packages/agentenv-protocol/tests/test_usage_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,21 @@ def test_a_turn_that_gives_only_its_rows_takes_their_sums_as_its_counts():
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})


def test_a_models_row_of_its_calls_sums_what_they_gave_and_counts_each_call():
row = ModelUsage.of("m", [Usage(input_tokens=100, output_tokens=10, cache_read_tokens=80, input_includes_cache=True),
Usage(input_tokens=50, output_tokens=5, input_includes_cache=True), Usage()])
assert row == ModelUsage(model="m", calls=3, input_tokens=150, output_tokens=15, cache_read_tokens=80,
input_includes_cache=True)


def test_a_models_row_takes_its_calls_cost_only_when_every_call_reported_one():
assert ModelUsage.of("m", [Usage(input_tokens=1, cost_usd=0.25), Usage(input_tokens=1, cost_usd=0.5)]).cost_usd == 0.75
assert ModelUsage.of("m", [Usage(input_tokens=1, cost_usd=0.25), Usage(input_tokens=1)]).cost_usd is None


def test_a_models_row_takes_the_flag_its_counted_calls_agree_on():
assert ModelUsage.of("m", [Usage(input_tokens=1, input_includes_cache=True), Usage()]).input_includes_cache is True
assert ModelUsage.of("m", [Usage(input_tokens=1, input_includes_cache=True),
Usage(input_tokens=1, input_includes_cache=False)]).input_includes_cache is None
7 changes: 5 additions & 2 deletions src/agent_env/agents/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,11 @@ terminal state, `completed`, `failed` or `canceled`. Your `run()` is one turn.
report the session's totals, as Claude Code's `modelUsage` and `total_cost_usd` do, so count the turn as the
difference from the session's totals before it, and check that it covers every call the turn made, subagents'
included (Claude Code's `result` events count only the main agent's). A cost the runtime couldn't price is unset,
never 0. Code that sets these fields needs a
`requirements.txt` protocol floor at the first release that has them.
never 0. When the runtime knows each call's model, give the turn's counts by model in `Usage.models` on every turn
(Claude Code from `modelUsage`, Gemini from its proxy's calls, OpenCode and Letta Code from the shared relay, which
reads each request's model): one `ModelUsage` per model, covering every call the turn counted, a call it can't name
under the configured model, so the host prices a subagent or side call on another model at that model's rate. Code
that sets these fields needs a `requirements.txt` protocol floor at the first release that has them.
- **Errors:** `agent_error`, the default, means the agent tried and failed; `infra_error` means the run couldn't
happen, and agent-env may retry it. An exception that escapes `run()` becomes an opaque `infra_error`, its text
never sent.
Expand Down
36 changes: 21 additions & 15 deletions src/agent_env/agents/agents/claude-code/a2a_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
TaskRequest,
TaskResult,
TextPart,
ModelUsage,
Usage,
a2a_agent,
enable,
Expand Down Expand Up @@ -415,6 +416,16 @@ def _turn_tally(result: ClaudeResult) -> dict[str, dict[str, float]] | None:
return turn


def _model_usage(model: str, counts: dict[str, float]) -> ModelUsage:
"""One model's share of the turn's tally, with ``input_tokens`` counting the cache, and its cost."""
return ModelUsage(model=model, input_tokens=int(counts["input_tokens"] + counts["cache_read_input_tokens"]
+ counts["cache_creation_input_tokens"]),
output_tokens=int(counts["output_tokens"]),
cache_read_tokens=int(counts["cache_read_input_tokens"]),
cache_write_tokens=int(counts["cache_creation_input_tokens"]), input_includes_cache=True,
cost_usd=counts["cost_usd"] or None)


def _builds_atif(request: TaskRequest[ClaudeCodeConfig]) -> bool:
"""Whether the task feeds an atif/1 copy; a protocol from before ``builds_atif`` is taken to, and its copy is built
only when the run prescribed it."""
Expand All @@ -424,11 +435,12 @@ def _builds_atif(request: TaskRequest[ClaudeCodeConfig]) -> bool:
def _usage(result: ClaudeResult) -> Usage:
"""The turn's tool calls and token counts, with ``input_tokens`` counting the cache. The counts are the CLI's own
tally for the turn (``_turn_tally``), which covers every call, its subagents' too, and its cost; the turn's
`result` events count only the main agent's calls, so the tally is used only when it covers at least those. When it
can't be (a resumed session this process hasn't run before), the counts are the `result` events', and the
subagents' calls are counted in ``unreported_calls``, which makes the turn a lower bound. A run cut off before its
`result` counts its model calls there too. The cache writes' 5-minute and 1-hour split, the thinking tokens and
each model's own counts are kept in ``provider_details``."""
`result` events count only the main agent's calls, so the tally is used only when it covers at least those, and
then each model's own counts and cost are the turn's ``models``, so a subagent on another model is priced at its
rate. When it can't be (a resumed session this process hasn't run before), the counts are the `result` events',
and the subagents' calls are counted in ``unreported_calls``, which makes the turn a lower bound. A run cut off
before its `result` counts its model calls there too. The cache writes' 5-minute and 1-hour split and the
thinking tokens are kept in ``provider_details``."""
unreported = result.unreported_calls
if not result.run_usage and not result.model_usage:
details = {"unreported_calls": unreported + result.subagent_calls} if unreported + result.subagent_calls else {}
Expand All @@ -440,28 +452,22 @@ def total(read: Any) -> int:
main = {key: total(lambda run, key=key: run.get(key)) for key in _RUN_COUNTS}
turn = _turn_tally(result)
tally = {key: sum(model[key] for model in turn.values()) for key in _TALLY} if turn is not None else None
cost, models = None, None
cost, models = None, ()
if tally is not None and all(tally[key] >= main[key] for key in _RUN_COUNTS) and min(tally.values()) >= 0:
counted = {key: int(tally[key]) for key in _RUN_COUNTS}
counted["cache_creation"] = {key: int(tally[key]) for key in _CACHE_WRITE_SPLIT}
thinking, cost = int(tally["thinking_tokens"]), tally["cost_usd"] or None
models = {model: {"input_tokens": int(counts["input_tokens"] + counts["cache_read_input_tokens"]
+ counts["cache_creation_input_tokens"]),
"output_tokens": int(counts["output_tokens"]),
"cache_read_tokens": int(counts["cache_read_input_tokens"]),
"cache_write_tokens": int(counts["cache_creation_input_tokens"]),
**({"cost_usd": counts["cost_usd"]} if counts["cost_usd"] else {})}
for model, counts in turn.items()}
models = tuple(_model_usage(model, counts) for model, counts in turn.items())
else:
counted = dict(main)
counted["cache_creation"] = {key: total(lambda run, key=key: (run.get("cache_creation") or {}).get(key))
for key in _CACHE_WRITE_SPLIT}
thinking = total(lambda run: (run.get("output_tokens_details") or {}).get("thinking_tokens"))
unreported += result.subagent_calls
usage = Usage.from_model_response(counted)
return replace(usage, tool_call_count=result.tool_call_count, cost_usd=cost, provider_details={
return replace(usage, tool_call_count=result.tool_call_count, cost_usd=cost, models=models, provider_details={
**usage.provider_details, **({"unreported_calls": unreported} if unreported else {}),
**({"reasoning_tokens": thinking} if thinking else {}), **({"models": models} if models else {})})
**({"reasoning_tokens": thinking} if thinking else {})})


@a2a_agent(
Expand Down
6 changes: 3 additions & 3 deletions src/agent_env/agents/agents/claude-code/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# The image installs the newest agentenv-framework-protocol at or above this floor; a release doesn't pin it, so the
# image is built again only when this folder changes. The floor is the first that builds an ATIF adapter's atif/1 copy
# only for a run that prescribes it (TRAJECTORY_V1.prescribe); raise it when the agent needs a newer protocol.
agentenv-framework-protocol[agent]>=0.1.623
# image is built again only when this folder changes. The floor is the first whose Usage gives a turn's counts by
# model (Usage.models); raise it when the agent needs a newer protocol.
agentenv-framework-protocol[agent]>=0.1.640
Loading
Loading