From 328ece0b10756f5b4a9f0e7eb5ac7925173f83ac Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 10:17:55 -0800 Subject: [PATCH 1/4] feat(agents): Claude Code, Gemini, OpenCode, Letta Code and the proxy give each turn's counts by model Usage.models from what each already counts: Claude Code from the CLI's modelUsage tally (with the CLI's own cost per model), Gemini from its proxy's per-call records, OpenCode and Letta Code from the shared model relay, which now reads each request's model, and the proxy from the model each recorded call names. A call that named no model counts as the turn's configured one. Claude Code's and Gemini's per-model counts leave provider_details. The four agents' protocol floor is 0.1.640, the first with Usage.models; the sandboxed proxy takes it from the next release. Co-Authored-By: Claude Opus 5.5 --- packages/agentenv-protocol/README.md | 16 +++--- .../src/agentenv_protocol/a2a_agent/proxy.py | 29 +++++++++- .../agentenv_protocol/a2a_agent/tasks/v1.py | 4 +- .../agentenv-protocol/tests/test_a2a_proxy.py | 14 +++++ src/agent_env/agents/AGENTS.md | 7 ++- .../agents/agents/claude-code/a2a_server.py | 36 +++++++------ .../agents/claude-code/requirements.txt | 6 +-- .../agents/agents/gemini/a2a_server.py | 28 +++++----- .../agents/agents/gemini/requirements.txt | 6 +-- .../agents/letta-code/letta_code_bridge.py | 2 +- .../agents/agents/letta-code/requirements.txt | 6 +-- .../agents/agents/opencode/opencode_bridge.py | 2 +- .../agents/agents/opencode/requirements.txt | 6 +-- .../utils/model_relay/model_relay.py | 54 +++++++++++++++---- tst/unit/agents/claude_code/test_usage.py | 22 +++++++- tst/unit/agents/gemini/test_usage.py | 20 +++++-- tst/unit/agents/letta_code/test_bridge.py | 5 +- .../opencode/test_opencode_bridge_config.py | 2 + tst/unit/utils/model_relay_models_test.py | 40 ++++++++++++++ 19 files changed, 233 insertions(+), 72 deletions(-) create mode 100644 tst/unit/utils/model_relay_models_test.py diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 2d3f360aa..fa2a66cbd 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -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 diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py index 1b0a42ba9..a09ea4a7f 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py @@ -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 @@ -113,6 +113,7 @@ class _Turn: 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 + call_models: list[str | None] = field(default_factory=list) # the model each recorded call named @contextlib.asynccontextmanager @@ -251,6 +252,7 @@ async def record(self, request: ProxyRecordRequest) -> None: 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.call_models.append(request.model) for key in ("input_tokens", "output_tokens"): if (count := getattr(usage, key)) is not None: span["attributes"][f"gen_ai.usage.{key}"] = count @@ -581,7 +583,30 @@ 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 {}) + + +_MODEL_COUNTS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "cost_usd") + + +def _by_model(turn: _Turn) -> tuple[ModelUsage, ...]: + """The turn's recorded calls by the model each named, a call that named none counted as the turn's last named + model's; none when no call named one.""" + by_model: dict[str, list[Usage]] = {} + for named, usage in zip(turn.call_models, turn.model_usage): + if (name := named or turn.model) is None: + return () + by_model.setdefault(name, []).append(usage) + rows = [] + for name, of in by_model.items(): + sums = {} + for count in _MODEL_COUNTS: + values = [value for usage in of if (value := getattr(usage, count)) is not None] + sums[count] = sum(values) if values else None + flags = {usage.input_includes_cache for usage in of} + rows.append(ModelUsage(model=name, calls=len(of), **sums, + input_includes_cache=flags.pop() if len(flags) == 1 else None)) + return tuple(rows) def _span(name: str, operation: str, started: str, model: str | None, *, prompt: Any = None, 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 47593d402..8eca71908 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 @@ -436,8 +436,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 diff --git a/packages/agentenv-protocol/tests/test_a2a_proxy.py b/packages/agentenv-protocol/tests/test_a2a_proxy.py index b37bc69fe..4a1c50d5e 100644 --- a/packages/agentenv-protocol/tests/test_a2a_proxy.py +++ b/packages/agentenv-protocol/tests/test_a2a_proxy.py @@ -603,6 +603,20 @@ 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 test_a_turns_recorded_calls_are_given_by_the_model_each_named(client): + task_id = _send(client, "go") + for model, usage in (("gpt-4.1-mini", {"prompt_tokens": 1000, "completion_tokens": 10}), + ("gpt-4o-mini", {"prompt_tokens": 300, "completion_tokens": 5}), + (None, {"prompt_tokens": 200, "completion_tokens": 2})): + 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."}]) + + assert _usage(_settled(client, task_id))["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": 500, "output_tokens": 7, "input_includes_cache": True}] + + 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"}, diff --git a/src/agent_env/agents/AGENTS.md b/src/agent_env/agents/AGENTS.md index b602dfebc..a63bbbff5 100644 --- a/src/agent_env/agents/AGENTS.md +++ b/src/agent_env/agents/AGENTS.md @@ -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. diff --git a/src/agent_env/agents/agents/claude-code/a2a_server.py b/src/agent_env/agents/agents/claude-code/a2a_server.py index 44595f412..99f2e4aca 100644 --- a/src/agent_env/agents/agents/claude-code/a2a_server.py +++ b/src/agent_env/agents/agents/claude-code/a2a_server.py @@ -53,6 +53,7 @@ TaskRequest, TaskResult, TextPart, + ModelUsage, Usage, a2a_agent, enable, @@ -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.""" @@ -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 {} @@ -440,18 +452,12 @@ 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)) @@ -459,9 +465,9 @@ def total(read: Any) -> int: 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( diff --git a/src/agent_env/agents/agents/claude-code/requirements.txt b/src/agent_env/agents/agents/claude-code/requirements.txt index f1c2b5ce9..f749fae80 100644 --- a/src/agent_env/agents/agents/claude-code/requirements.txt +++ b/src/agent_env/agents/agents/claude-code/requirements.txt @@ -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 diff --git a/src/agent_env/agents/agents/gemini/a2a_server.py b/src/agent_env/agents/agents/gemini/a2a_server.py index 622dd30bd..7a60f77c4 100644 --- a/src/agent_env/agents/agents/gemini/a2a_server.py +++ b/src/agent_env/agents/agents/gemini/a2a_server.py @@ -52,6 +52,7 @@ TaskRequest, TaskResult, TextPart, + ModelUsage, Usage, a2a_agent, enable, @@ -241,10 +242,11 @@ async def _settled(calls: _Calls) -> None: await asyncio.sleep(_IN_FLIGHT_POLL_S) -def _turn_usage(calls: _Calls, tool_calls: int, trajectory: list[dict]) -> Usage: +def _turn_usage(calls: _Calls, tool_calls: int, trajectory: list[dict], model: str | None = None) -> Usage: """The turn's usage from the model calls its proxy forwarded, which are every call the CLI made through its base URL: the main loop's, its subagents', routing, loop and next-speaker checks, compression, web tools and answered - retries. A call answered without counts, or still running when the turn ended, is counted in + retries, by the model each call named (``models``, a call that named none counted as ``model``'s, the one the turn + was configured with). A call answered without counts, or still running when the turn ended, is counted in ``unreported_calls``. When the proxy saw no call but the CLI's own stats name tokens, the CLI went around the proxy, and those stats, short of the thoughts, are the turn's, marked a lower bound.""" answered = [record["usage"] for record in calls.records if record["outcome"] == "answered"] @@ -268,16 +270,18 @@ def total(name: str, of: list[dict] = answered) -> int | None: if total("reasoning_tokens"): details["reasoning_tokens"] = total("reasoning_tokens") - models: dict[str, list[dict]] = {} + by_model: dict[str, list[dict]] = {} for record in calls.records: - if record["outcome"] == "answered": - models.setdefault(record["model"] or "unknown", []).append(record["usage"]) - details["models"] = {model: {"calls": len(of), **{name: total(name, of) for name in _COUNTS[:3]}} - for model, of in models.items()} + if record["outcome"] == "answered" and (name := record["model"] or model): + by_model.setdefault(name, []).append(record["usage"]) + named = sum(len(of) for of in by_model.values()) == len(answered) + models = tuple(ModelUsage(model=name, calls=len(of), **{count: total(count, of) for count in _COUNTS[:4]}, + input_includes_cache=True) for name, of in by_model.items()) if named else () inputs, output = total("input_tokens"), total("output_tokens") return Usage(tool_call_count=tool_calls, input_tokens=inputs, output_tokens=output, total_tokens=(inputs or 0) + (output or 0), cache_read_tokens=total("cache_read_tokens"), - cache_write_tokens=total("cache_write_tokens"), input_includes_cache=True, provider_details=details) + cache_write_tokens=total("cache_write_tokens"), input_includes_cache=True, models=models, + provider_details=details) # install.sh, from the build context install_agent unpacks, brings Node, the Gemini CLI and a Python of the agent's @@ -676,13 +680,13 @@ async def run(self, request: TaskRequest[GeminiConfig]) -> TaskResult: .failed("infra_error", str(e)[:_ERROR_MESSAGE_LIMIT], error_type="infra_error") .add_text(str(e))) if route.calls.records or route.calls.running: - failed.usage(await self._calls_usage(route.calls, 0, [])) + failed.usage(await self._calls_usage(route.calls, 0, [], route.model)) return failed.build() finally: self._routes.pop(token, None) self._active_contexts.discard(context_id) - usage = await self._calls_usage(route.calls, result.tool_call_count, result.trajectory) + usage = await self._calls_usage(route.calls, result.tool_call_count, result.trajectory, route.model) if result.session_id: self.set_session_ref_for_context(context_id, result.session_id) @@ -703,10 +707,10 @@ async def run(self, request: TaskRequest[GeminiConfig]) -> TaskResult: ) @staticmethod - async def _calls_usage(calls: _Calls, tool_calls: int, trajectory: list[dict]) -> Usage: + async def _calls_usage(calls: _Calls, tool_calls: int, trajectory: list[dict], model: str | None) -> Usage: """The turn's usage, once its calls have settled.""" await _settled(calls) - return _turn_usage(calls, tool_calls, trajectory) + return _turn_usage(calls, tool_calls, trajectory, model) def _on_event(self, event: dict, request: TaskRequest[GeminiConfig]) -> None: if event.get("type") == "init" and event.get("session_id"): diff --git a/src/agent_env/agents/agents/gemini/requirements.txt b/src/agent_env/agents/agents/gemini/requirements.txt index dd31306bb..f749fae80 100644 --- a/src/agent_env/agents/agents/gemini/requirements.txt +++ b/src/agent_env/agents/agents/gemini/requirements.txt @@ -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 whose Usage takes the prompt cache's -# counts (cache_read_tokens, cache_write_tokens, input_includes_cache); raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.597 +# 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 diff --git a/src/agent_env/agents/agents/letta-code/letta_code_bridge.py b/src/agent_env/agents/agents/letta-code/letta_code_bridge.py index 4ffa85d24..ef94e2977 100644 --- a/src/agent_env/agents/agents/letta-code/letta_code_bridge.py +++ b/src/agent_env/agents/agents/letta-code/letta_code_bridge.py @@ -432,7 +432,7 @@ async def run_letta_code( finally: if calls.answered or calls.unreported or calls.refused: _record_attribution(project_id, task_id) - result.usage = calls.usage(result.tool_call_count) + result.usage = calls.usage(result.tool_call_count, model) return result diff --git a/src/agent_env/agents/agents/letta-code/requirements.txt b/src/agent_env/agents/agents/letta-code/requirements.txt index e76b8389c..96283bd84 100644 --- a/src/agent_env/agents/agents/letta-code/requirements.txt +++ b/src/agent_env/agents/agents/letta-code/requirements.txt @@ -1,6 +1,6 @@ # 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 whose Usage takes the prompt cache's -# counts (cache_read_tokens, cache_write_tokens, input_includes_cache); raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.597 +# 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 jsonschema>=4.18,<5 aiohttp>=3.9,<4 diff --git a/src/agent_env/agents/agents/opencode/opencode_bridge.py b/src/agent_env/agents/agents/opencode/opencode_bridge.py index 025cd3107..dbd71aa1e 100644 --- a/src/agent_env/agents/agents/opencode/opencode_bridge.py +++ b/src/agent_env/agents/agents/opencode/opencode_bridge.py @@ -452,7 +452,7 @@ async def run_opencode(prompt: str, context_id: str, **kwargs) -> OpencodeResult calls = Calls() async with model_relay(_base_url(os.environ).removesuffix("/v1"), calls, rewrite=env_date_rewrite) as relay: result = await _run_opencode(prompt, context_id, base_url=relay, **kwargs) - result.usage = calls.usage(result.tool_call_count) + result.usage = calls.usage(result.tool_call_count, kwargs.get("model")) return result diff --git a/src/agent_env/agents/agents/opencode/requirements.txt b/src/agent_env/agents/agents/opencode/requirements.txt index 482e81c7d..c204ff509 100644 --- a/src/agent_env/agents/agents/opencode/requirements.txt +++ b/src/agent_env/agents/agents/opencode/requirements.txt @@ -1,7 +1,7 @@ # 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 whose Usage takes the prompt cache's -# counts (cache_read_tokens, cache_write_tokens, input_includes_cache); raise it when the agent needs a newer protocol. -agentenv-framework-protocol[agent]>=0.1.597 +# 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 jsonschema>=4.18,<5 # The model relay's server and client (model_relay.py). aiohttp>=3.9,<4 diff --git a/src/agent_env/utils/model_relay/model_relay.py b/src/agent_env/utils/model_relay/model_relay.py index 489512930..f1c9defc8 100644 --- a/src/agent_env/utils/model_relay/model_relay.py +++ b/src/agent_env/utils/model_relay/model_relay.py @@ -13,7 +13,7 @@ from dataclasses import dataclass, field from typing import Any -from agentenv_protocol.a2a_agent import Usage +from agentenv_protocol.a2a_agent import ModelUsage, Usage from aiohttp import ClientError, ClientSession, ClientTimeout, web logger = logging.getLogger(__name__) @@ -28,6 +28,7 @@ # How long the relay, once its turn is done, lets the calls it is still forwarding finish. _SHUTDOWN_S = 5.0 _COUNTS = ("input_tokens", "output_tokens", "total_tokens", "cache_read_tokens", "cache_write_tokens") +_ROW_COUNTS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens") class Refusal(Exception): @@ -37,15 +38,17 @@ class Refusal(Exception): @dataclass class Calls: """The model calls a relay forwarded: each answered call's usage, read as ``Usage.from_model_response`` reads one, - and how many were answered without usage or refused. A refused call (an error status, or none at all) counts - nothing.""" + with the model its request named, and how many were answered without usage or refused. A refused call (an error + status, or none at all) counts nothing.""" answered: list[Usage] = field(default_factory=list) unreported: int = 0 refused: int = 0 + models: list[str | None] = field(default_factory=list) # each answered call's model, as its request named it - def add(self, status: int | None, usage: Usage | None) -> None: - """A call that ended with ``status`` (None when it had none), and the usage its answer carried.""" + def add(self, status: int | None, usage: Usage | None, model: str | None = None) -> None: + """A call that ended with ``status`` (None when it had none), the usage its answer carried and the model its + request named.""" if status is None or status >= 400: self.refused += 1 return @@ -53,10 +56,12 @@ def add(self, status: int | None, usage: Usage | None) -> None: self.unreported += 1 else: self.answered.append(usage) + self.models.append(model) - def usage(self, tool_call_count: int) -> Usage: + def usage(self, tool_call_count: int, model: str | None = None) -> Usage: """The calls' usage summed, with ``input_tokens`` counting the cache, and the calls without usage counted in - ``unreported_calls``; no counts when no call had any.""" + ``unreported_calls``; no counts when no call had any. ``models`` holds them by the model each named, a call + that named none counted as ``model``'s, the one the turn was configured with.""" details: dict[str, Any] = {} if self.answered or self.unreported: details["model_calls"] = len(self.answered) + self.unreported @@ -71,7 +76,27 @@ def total(name: str) -> int | None: flags = {usage.input_includes_cache for usage in self.answered} return Usage(tool_call_count=tool_call_count, **{name: total(name) for name in _COUNTS}, - input_includes_cache=flags.pop() if len(flags) == 1 else None, provider_details=details) + input_includes_cache=flags.pop() if len(flags) == 1 else None, models=self._by_model(model), + provider_details=details) + + def _by_model(self, configured: str | None) -> tuple[ModelUsage, ...]: + """The answered calls' counts by model; none when a call named no model and the turn has none configured.""" + by_model: dict[str, list[Usage]] = {} + for named, usage in zip(self.models, self.answered): + if (name := named or configured) is None: + return () + by_model.setdefault(name, []).append(usage) + + def total(of: list[Usage], name: str) -> int | None: + values = [getattr(usage, name) for usage in of if getattr(usage, name) is not None] + return sum(values) if values else None + + rows = [] + for name, of in by_model.items(): + flags = {usage.input_includes_cache for usage in of} + rows.append(ModelUsage(model=name, calls=len(of), **{count: total(of, count) for count in _ROW_COUNTS}, + input_includes_cache=flags.pop() if len(flags) == 1 else None)) + return tuple(rows) class AnswerReader: @@ -136,6 +161,15 @@ def usage(self) -> Usage | None: return read if any(getattr(read, name) for name in _COUNTS) else None +def _request_model(body: bytes) -> str | None: + """The model a call's request body names, as its JSON's ``model``; None for a body that names none.""" + try: + model = json.loads(body).get("model") + except (ValueError, AttributeError): + return None + return model if isinstance(model, str) and model else None + + def answer_usage(answer: bytes) -> Usage | None: """The usage a whole answer carried, as ``AnswerReader`` reads it.""" reader = AnswerReader() @@ -169,7 +203,7 @@ async def forward(request: web.Request) -> web.StreamResponse: # Answered as sent, so its usage can be read. outgoing["accept-encoding"] = "identity" call = request.method == "POST" and path.rstrip("/").endswith(_CALL_ROUTES) - status, reader = None, AnswerReader() + status, reader, body = None, AnswerReader(), b"" try: body = await request.read() if call and rewrite is not None: @@ -211,7 +245,7 @@ async def forward(request: web.Request) -> web.StreamResponse: raise finally: if call: - calls.add(status, reader.usage()) + calls.add(status, reader.usage(), _request_model(body)) app = web.Application(client_max_size=_MAX_REQUEST_BYTES) app.router.add_route("*", "/{token}/{path:.*}", forward) diff --git a/tst/unit/agents/claude_code/test_usage.py b/tst/unit/agents/claude_code/test_usage.py index 06f7b32ed..2ffb08cd5 100644 --- a/tst/unit/agents/claude_code/test_usage.py +++ b/tst/unit/agents/claude_code/test_usage.py @@ -8,7 +8,8 @@ import asyncio -from agentenv_protocol.a2a_agent import Usage +import pytest +from agentenv_protocol.a2a_agent import ModelUsage, Usage from tst.unit.agents.claude_code.agent import a2a_server, claude_bridge from tst.unit.agents.claude_code.support import FakeCLI @@ -67,7 +68,24 @@ def test_a_new_sessions_turn_counts_every_call_its_subagents_included(): assert _counts(usage) == _truth(TURN_1) assert usage.input_includes_cache is True and usage.cost_usd == 0.0452852 assert "unreported_calls" not in usage.provider_details - assert usage.provider_details["models"] == {HAIKU: {**_truth(TURN_1), "cost_usd": 0.0452852}} + assert usage.models == (ModelUsage(model=HAIKU, **_truth(TURN_1), input_includes_cache=True, cost_usd=0.0452852),) + assert "models" not in usage.provider_details + + +def test_a_turn_whose_subagent_ran_on_another_model_gives_each_models_counts_and_cost(): + sonnet = "claude-sonnet-4-6" + tally = {sonnet: {"inputTokens": 20, "outputTokens": 300, "cacheReadInputTokens": 60000, + "cacheCreationInputTokens": 4000, "costUSD": 0.05}, + **_tally(10, 90, 20000, 2000, 0.004)} + + usage = a2a_server._usage(_result(run_usage=[], model_usage=tally, session_base={})) + + assert usage.models == ( + ModelUsage(model=sonnet, input_tokens=64020, output_tokens=300, cache_read_tokens=60000, + cache_write_tokens=4000, input_includes_cache=True, cost_usd=0.05), + ModelUsage(model=HAIKU, input_tokens=22010, output_tokens=90, cache_read_tokens=20000, + cache_write_tokens=2000, input_includes_cache=True, cost_usd=0.004)) + assert usage.cost_usd == pytest.approx(0.054) and usage.input_tokens == 64020 + 22010 def test_a_resumed_turn_counts_its_own_calls_not_the_sessions(): diff --git a/tst/unit/agents/gemini/test_usage.py b/tst/unit/agents/gemini/test_usage.py index 6f212e85f..496ce09ac 100644 --- a/tst/unit/agents/gemini/test_usage.py +++ b/tst/unit/agents/gemini/test_usage.py @@ -163,10 +163,22 @@ def test_a_turns_usage_sums_its_calls_with_each_model_kept_apart(): assert usage.to_dict() == { "tool_call_count": 2, "input_tokens": 18400, "output_tokens": 65, "total_tokens": 18465, - "cache_read_tokens": 16900, "input_includes_cache": True, - "provider_details": {"model_calls": 3, "reasoning_tokens": 12, "models": { - "gemini-2.5-flash": {"calls": 2, "input_tokens": 18100, "output_tokens": 60, "cache_read_tokens": 16900}, - "gemini-2.5-flash-lite": {"calls": 1, "input_tokens": 300, "output_tokens": 5, "cache_read_tokens": 0}}}} + "cache_read_tokens": 16900, "input_includes_cache": True, "models": [ + {"model": "gemini-2.5-flash", "calls": 2, "input_tokens": 18100, "output_tokens": 60, + "cache_read_tokens": 16900, "input_includes_cache": True}, + {"model": "gemini-2.5-flash-lite", "calls": 1, "input_tokens": 300, "output_tokens": 5, + "cache_read_tokens": 0, "input_includes_cache": True}], + "provider_details": {"model_calls": 3, "reasoning_tokens": 12}} + + +def test_a_call_that_named_no_model_counts_as_the_configured_models(): + calls = _calls(_answered("gemini-2.5-flash-lite", 300, 5), {**_answered("unused", 900, 9), "model": None}) + + usage = a2a_server._turn_usage(calls, 0, [], "gemini-2.5-pro") + + assert [(row.model, row.calls, row.input_tokens) for row in usage.models] == [ + ("gemini-2.5-flash-lite", 1, 300), ("gemini-2.5-pro", 1, 900)] + assert a2a_server._turn_usage(calls, 0, []).models == () def test_calls_without_counts_or_still_running_are_unreported(): diff --git a/tst/unit/agents/letta_code/test_bridge.py b/tst/unit/agents/letta_code/test_bridge.py index 145b67420..2c6ea84a0 100644 --- a/tst/unit/agents/letta_code/test_bridge.py +++ b/tst/unit/agents/letta_code/test_bridge.py @@ -381,7 +381,10 @@ async def stream(proc, on_line): # The proxy's own usage for the turn: 45,853 in (22,784 cached) and 74 out. assert result.usage.to_dict() == { "tool_call_count": 0, "input_tokens": 45853, "output_tokens": 74, "total_tokens": 45927, - "cache_read_tokens": 22784, "input_includes_cache": True, "provider_details": {"model_calls": 2}} + "cache_read_tokens": 22784, "input_includes_cache": True, + "models": [{"model": "gpt-4.1-mini", "calls": 2, "input_tokens": 45853, "output_tokens": 74, + "cache_read_tokens": 22784, "input_includes_cache": True}], + "provider_details": {"model_calls": 2}} def test_a_turns_leftover_letta_processes_are_stopped_and_nothing_else(monkeypatch, tmp_path): diff --git a/tst/unit/agents/opencode/test_opencode_bridge_config.py b/tst/unit/agents/opencode/test_opencode_bridge_config.py index 1adb39ed5..290b23a10 100644 --- a/tst/unit/agents/opencode/test_opencode_bridge_config.py +++ b/tst/unit/agents/opencode/test_opencode_bridge_config.py @@ -225,6 +225,8 @@ async def relay(upstream, calls, **kwargs): assert result.usage.to_dict() == { "tool_call_count": 0, "input_tokens": 19489, "output_tokens": 105, "total_tokens": 19594, "cache_read_tokens": 9342, "cache_write_tokens": 9539, "input_includes_cache": True, + "models": [{"model": "m", "calls": 3, "input_tokens": 19489, "output_tokens": 105, "cache_read_tokens": 9342, + "cache_write_tokens": 9539, "input_includes_cache": True}], "provider_details": {"model_calls": 3}} diff --git a/tst/unit/utils/model_relay_models_test.py b/tst/unit/utils/model_relay_models_test.py new file mode 100644 index 000000000..1f852ccf7 --- /dev/null +++ b/tst/unit/utils/model_relay_models_test.py @@ -0,0 +1,40 @@ +"""The shared model relay keeps each answered call's model, as its request named it, so a turn's usage gives its +counts by model (``Usage.models``); a call that named none counts as the turn's configured model's.""" + +from agentenv_protocol.a2a_agent import ModelUsage, Usage + +from agent_env.utils.model_relay import model_relay + + +def _call(inputs: int, output: int) -> Usage: + return Usage(input_tokens=inputs, output_tokens=output, input_includes_cache=True) + + +def test_a_turns_calls_are_given_by_the_model_each_named_and_an_unnamed_one_by_the_configured_model(): + calls = model_relay.Calls() + calls.add(200, _call(1000, 10), "gpt-4.1-mini") + calls.add(200, _call(300, 5), "gpt-4o-mini") + calls.add(200, _call(200, 2), None) + calls.add(500, None, "gpt-4o-mini") + + usage = calls.usage(1, "gpt-4.1-mini") + + assert usage.models == ( + ModelUsage(model="gpt-4.1-mini", calls=2, input_tokens=1200, output_tokens=12, input_includes_cache=True), + ModelUsage(model="gpt-4o-mini", calls=1, input_tokens=300, output_tokens=5, input_includes_cache=True)) + assert (usage.input_tokens, usage.output_tokens) == (1500, 17) + + +def test_a_turn_with_a_call_that_named_no_model_and_none_configured_gives_no_rows(): + calls = model_relay.Calls() + calls.add(200, _call(1000, 10), "gpt-4.1-mini") + calls.add(200, _call(200, 2), None) + + assert calls.usage(0).models == () and calls.usage(0).input_tokens == 1200 + + +def test_a_requests_model_is_read_from_its_json_body(): + assert model_relay._request_model(b'{"model": "gpt-4.1-mini", "messages": []}') == "gpt-4.1-mini" + assert model_relay._request_model(b"not json") is None + assert model_relay._request_model(b'["a list"]') is None + assert model_relay._request_model(b'{"model": ""}') is None From 0a74cfc3423d33dbd0a94d56d4a146df02a54b07 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 10:33:12 -0800 Subject: [PATCH 2/4] fix(proxy): a model's row carries its calls' cost only when every one reported one; tests take the new floor As the host's rule since #887: a sum of some calls' figures isn't the model's cost, so the host prices it from the map. The agents' image-contract tests and the proxy usage integration test take the 0.1.640 floor and the turn's rows. Co-Authored-By: Claude Opus 5.5 --- .../src/agentenv_protocol/a2a_agent/proxy.py | 4 ++-- packages/agentenv-protocol/tests/test_a2a_proxy.py | 12 ++++++++++++ tst/integration/agent/proxy_usage_local_test.py | 4 +++- tst/unit/agents/claude_code/test_image_contract.py | 2 +- tst/unit/agents/gemini/test_image_contract.py | 2 +- tst/unit/agents/opencode/test_image_contract.py | 2 +- 6 files changed, 20 insertions(+), 6 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py index a09ea4a7f..d178cc8ff 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py @@ -591,7 +591,7 @@ def _turn_usage(turn: _Turn) -> Usage: def _by_model(turn: _Turn) -> tuple[ModelUsage, ...]: """The turn's recorded calls by the model each named, a call that named none counted as the turn's last named - model's; none when no call named one.""" + model's; none when no call named one. A model's cost is its calls' only when every one of them reported one.""" by_model: dict[str, list[Usage]] = {} for named, usage in zip(turn.call_models, turn.model_usage): if (name := named or turn.model) is None: @@ -602,7 +602,7 @@ def _by_model(turn: _Turn) -> tuple[ModelUsage, ...]: sums = {} for count in _MODEL_COUNTS: values = [value for usage in of if (value := getattr(usage, count)) is not None] - sums[count] = sum(values) if values else None + sums[count] = sum(values) if values and (count != "cost_usd" or len(values) == len(of)) else None flags = {usage.input_includes_cache for usage in of} rows.append(ModelUsage(model=name, calls=len(of), **sums, input_includes_cache=flags.pop() if len(flags) == 1 else None)) diff --git a/packages/agentenv-protocol/tests/test_a2a_proxy.py b/packages/agentenv-protocol/tests/test_a2a_proxy.py index 4a1c50d5e..0ef9934e4 100644 --- a/packages/agentenv-protocol/tests/test_a2a_proxy.py +++ b/packages/agentenv-protocol/tests/test_a2a_proxy.py @@ -851,3 +851,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) diff --git a/tst/integration/agent/proxy_usage_local_test.py b/tst/integration/agent/proxy_usage_local_test.py index b1104ec60..5190639e3 100644 --- a/tst/integration/agent/proxy_usage_local_test.py +++ b/tst/integration/agent/proxy_usage_local_test.py @@ -4,7 +4,7 @@ in the run's conversation. Local stores, no Docker.""" import pytest -from agentenv_protocol.a2a_agent.tasks.v1 import Usage +from agentenv_protocol.a2a_agent.tasks.v1 import ModelUsage, Usage from agent_env.a2a_agent import conversation_store from agent_env.artifact.store import reset_artifact_store @@ -70,6 +70,8 @@ async def test_a_turns_recorded_model_calls_reach_the_host_as_the_turns_usage(lo assert Usage.from_dict(usage) == Usage( tool_call_count=0, input_tokens=120 + 123 + 14, output_tokens=18, total_tokens=127 + 132 + 16, cache_read_tokens=210, cache_write_tokens=20, input_includes_cache=True, cost_usd=0.02, + models=(ModelUsage(model="policy-model", calls=3, input_tokens=257, output_tokens=18, cache_read_tokens=210, + cache_write_tokens=20, input_includes_cache=True),), provider_details={"model_calls": 3, "unreported": {"cache_write_tokens": 2, "cost_usd": 2}}) diff --git a/tst/unit/agents/claude_code/test_image_contract.py b/tst/unit/agents/claude_code/test_image_contract.py index e057a264d..f52d0a991 100644 --- a/tst/unit/agents/claude_code/test_image_contract.py +++ b/tst/unit/agents/claude_code/test_image_contract.py @@ -38,7 +38,7 @@ def test_the_image_installs_the_protocol_alone_from_its_requirements(): requirements = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() if line and not line.startswith("#")] - assert requirements == ["agentenv-framework-protocol[agent]>=0.1.623"] + assert requirements == ["agentenv-framework-protocol[agent]>=0.1.640"] def test_the_image_gives_the_model_node_alone_from_a_pinned_image(): diff --git a/tst/unit/agents/gemini/test_image_contract.py b/tst/unit/agents/gemini/test_image_contract.py index 030f6c1e6..e466a4ac2 100644 --- a/tst/unit/agents/gemini/test_image_contract.py +++ b/tst/unit/agents/gemini/test_image_contract.py @@ -54,7 +54,7 @@ def test_the_image_installs_the_protocol_alone_from_its_requirements(): requirements = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() if line and not line.startswith("#")] - assert requirements == ["agentenv-framework-protocol[agent]>=0.1.597"] + assert requirements == ["agentenv-framework-protocol[agent]>=0.1.640"] def test_the_image_gives_the_models_python_the_document_libraries(): diff --git a/tst/unit/agents/opencode/test_image_contract.py b/tst/unit/agents/opencode/test_image_contract.py index 7dbf2b9d3..8657ec767 100644 --- a/tst/unit/agents/opencode/test_image_contract.py +++ b/tst/unit/agents/opencode/test_image_contract.py @@ -74,7 +74,7 @@ def test_the_requirements_are_the_protocol_floor_the_output_format_validator_and requirements = [line for line in (AGENT_DIR / "requirements.txt").read_text().splitlines() if line and not line.startswith("#")] - assert requirements == ["agentenv-framework-protocol[agent]>=0.1.597", "jsonschema>=4.18,<5", "aiohttp>=3.9,<4"] + assert requirements == ["agentenv-framework-protocol[agent]>=0.1.640", "jsonschema>=4.18,<5", "aiohttp>=3.9,<4"] def test_node_is_pinned_by_version_and_checksum_for_the_image_and_an_install(): From 01a07696bf234a6657d45e7afa19a40670e8010b Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 10:50:15 -0800 Subject: [PATCH 3/4] fix(proxy): a turn with an unnamed call gives no rows, and a model's cache flag is its counted calls' The proxy has no configured model to count an unnamed call under, and the last model the turn named isn't it. A call without usage no longer leaves its model's includes-cache flag unknown. Co-Authored-By: Claude Opus 5.5 --- .../src/agentenv_protocol/a2a_agent/proxy.py | 11 ++++---- .../agentenv-protocol/tests/test_a2a_proxy.py | 25 ++++++++++++++----- 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py index d178cc8ff..950f0389f 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py @@ -590,20 +590,21 @@ def _turn_usage(turn: _Turn) -> Usage: def _by_model(turn: _Turn) -> tuple[ModelUsage, ...]: - """The turn's recorded calls by the model each named, a call that named none counted as the turn's last named - model's; none when no call named one. A model's cost is its calls' only when every one of them reported one.""" + """The turn's recorded calls by the model each named; none when a call named none, since the proxy has no + configured model to count it under. A model's cost is its calls' only when every one of them reported one, and + its includes-cache flag is the one its calls with input counts agree on.""" by_model: dict[str, list[Usage]] = {} for named, usage in zip(turn.call_models, turn.model_usage): - if (name := named or turn.model) is None: + if named is None: return () - by_model.setdefault(name, []).append(usage) + by_model.setdefault(named, []).append(usage) rows = [] for name, of in by_model.items(): sums = {} for count in _MODEL_COUNTS: values = [value for usage in of if (value := getattr(usage, count)) is not None] sums[count] = sum(values) if values and (count != "cost_usd" or len(values) == len(of)) else None - flags = {usage.input_includes_cache for usage in of} + flags = {usage.input_includes_cache for usage in of if usage.input_tokens is not None} rows.append(ModelUsage(model=name, calls=len(of), **sums, input_includes_cache=flags.pop() if len(flags) == 1 else None)) return tuple(rows) diff --git a/packages/agentenv-protocol/tests/test_a2a_proxy.py b/packages/agentenv-protocol/tests/test_a2a_proxy.py index 0ef9934e4..7aa1bae6e 100644 --- a/packages/agentenv-protocol/tests/test_a2a_proxy.py +++ b/packages/agentenv-protocol/tests/test_a2a_proxy.py @@ -603,18 +603,31 @@ 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 test_a_turns_recorded_calls_are_given_by_the_model_each_named(client): +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 (("gpt-4.1-mini", {"prompt_tokens": 1000, "completion_tokens": 10}), - ("gpt-4o-mini", {"prompt_tokens": 300, "completion_tokens": 5}), - (None, {"prompt_tokens": 200, "completion_tokens": 2})): + 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(_settled(client, task_id))["models"] == [ + 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": 500, "output_tokens": 7, "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): From e72e02fbd6ce7620349fa1f266b98c5df7e9fd3a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 11:20:29 -0800 Subject: [PATCH 4/4] refactor(agents): one model's row is ModelUsage.of its calls, and each call keeps its model beside its usage The rule for a model's row (counts summed over the calls that gave them, the cost only when every call reported one, the flag the counted calls agree on) is the protocol's ModelUsage.of, which the proxy uses; the relay and Gemini take it once their floor is the release that has it. The relay's Calls and the proxy's turn keep (model, usage) pairs rather than two lists in step, and Gemini stops at the first unnamed call when no model is configured. Co-Authored-By: Claude Opus 5.5 --- .../src/agentenv_protocol/a2a_agent/proxy.py | 30 +++++------------ .../agentenv_protocol/a2a_agent/tasks/v1.py | 17 ++++++++++ .../tests/test_usage_models.py | 18 +++++++++++ .../agents/agents/gemini/a2a_server.py | 32 +++++++++++++------ .../utils/model_relay/model_relay.py | 19 ++++++----- tst/unit/agents/test_model_relay.py | 10 +++--- 6 files changed, 79 insertions(+), 47 deletions(-) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py index 950f0389f..99d7ecbf9 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/proxy.py @@ -112,8 +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 - call_models: list[str | None] = field(default_factory=list) # the model each recorded call named + # 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 @@ -251,8 +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.call_models.append(request.model) + 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 @@ -562,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] @@ -586,28 +585,15 @@ def _turn_usage(turn: _Turn) -> Usage: models=_by_model(turn), provider_details=details if calls else {}) -_MODEL_COUNTS = ("input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "cost_usd") - - def _by_model(turn: _Turn) -> tuple[ModelUsage, ...]: - """The turn's recorded calls by the model each named; none when a call named none, since the proxy has no - configured model to count it under. A model's cost is its calls' only when every one of them reported one, and - its includes-cache flag is the one its calls with input counts agree on.""" + """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 zip(turn.call_models, turn.model_usage): + for named, usage in turn.model_calls: if named is None: return () by_model.setdefault(named, []).append(usage) - rows = [] - for name, of in by_model.items(): - sums = {} - for count in _MODEL_COUNTS: - values = [value for usage in of if (value := getattr(usage, count)) is not None] - sums[count] = sum(values) if values and (count != "cost_usd" or len(values) == len(of)) else None - flags = {usage.input_includes_cache for usage in of if usage.input_tokens is not None} - rows.append(ModelUsage(model=name, calls=len(of), **sums, - input_includes_cache=flags.pop() if len(flags) == 1 else None)) - return tuple(rows) + 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, 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 8eca71908..0a7a6b342 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 @@ -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.""" diff --git a/packages/agentenv-protocol/tests/test_usage_models.py b/packages/agentenv-protocol/tests/test_usage_models.py index 642a8344b..ce29b530c 100644 --- a/packages/agentenv-protocol/tests/test_usage_models.py +++ b/packages/agentenv-protocol/tests/test_usage_models.py @@ -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 diff --git a/src/agent_env/agents/agents/gemini/a2a_server.py b/src/agent_env/agents/agents/gemini/a2a_server.py index 7a60f77c4..93c62f645 100644 --- a/src/agent_env/agents/agents/gemini/a2a_server.py +++ b/src/agent_env/agents/agents/gemini/a2a_server.py @@ -242,6 +242,25 @@ async def _settled(calls: _Calls) -> None: await asyncio.sleep(_IN_FLIGHT_POLL_S) +def _total(name: str, counts: list[dict]) -> int | None: + values = [of[name] for of in counts if of.get(name) is not None] + return sum(values) if values else None + + +def _by_model(calls: _Calls, model: str | None) -> tuple[ModelUsage, ...]: + """The answered calls' counts by the model each named, one that named none counted as ``model``'s; none when a + call named none and no model is configured.""" + by_model: dict[str, list[dict]] = {} + for record in calls.records: + if record["outcome"] != "answered": + continue + if not (name := record["model"] or model): + return () + by_model.setdefault(name, []).append(record["usage"]) + return tuple(ModelUsage(model=name, calls=len(of), **{count: _total(count, of) for count in _COUNTS[:4]}, + input_includes_cache=True) for name, of in by_model.items()) + + def _turn_usage(calls: _Calls, tool_calls: int, trajectory: list[dict], model: str | None = None) -> Usage: """The turn's usage from the model calls its proxy forwarded, which are every call the CLI made through its base URL: the main loop's, its subagents', routing, loop and next-speaker checks, compression, web tools and answered @@ -264,19 +283,12 @@ def _turn_usage(calls: _Calls, tool_calls: int, trajectory: list[dict], model: s if not answered: return Usage(tool_call_count=tool_calls, provider_details=details) - def total(name: str, of: list[dict] = answered) -> int | None: - values = [counts[name] for counts in of if counts.get(name) is not None] - return sum(values) if values else None + def total(name: str) -> int | None: + return _total(name, answered) if total("reasoning_tokens"): details["reasoning_tokens"] = total("reasoning_tokens") - by_model: dict[str, list[dict]] = {} - for record in calls.records: - if record["outcome"] == "answered" and (name := record["model"] or model): - by_model.setdefault(name, []).append(record["usage"]) - named = sum(len(of) for of in by_model.values()) == len(answered) - models = tuple(ModelUsage(model=name, calls=len(of), **{count: total(count, of) for count in _COUNTS[:4]}, - input_includes_cache=True) for name, of in by_model.items()) if named else () + models = _by_model(calls, model) inputs, output = total("input_tokens"), total("output_tokens") return Usage(tool_call_count=tool_calls, input_tokens=inputs, output_tokens=output, total_tokens=(inputs or 0) + (output or 0), cache_read_tokens=total("cache_read_tokens"), diff --git a/src/agent_env/utils/model_relay/model_relay.py b/src/agent_env/utils/model_relay/model_relay.py index f1c9defc8..d43c83b4b 100644 --- a/src/agent_env/utils/model_relay/model_relay.py +++ b/src/agent_env/utils/model_relay/model_relay.py @@ -37,14 +37,13 @@ class Refusal(Exception): @dataclass class Calls: - """The model calls a relay forwarded: each answered call's usage, read as ``Usage.from_model_response`` reads one, - with the model its request named, and how many were answered without usage or refused. A refused call (an error - status, or none at all) counts nothing.""" + """The model calls a relay forwarded: each answered call's model, as its request named it, and usage, read as + ``Usage.from_model_response`` reads one, and how many were answered without usage or refused. A refused call (an + error status, or none at all) counts nothing.""" - answered: list[Usage] = field(default_factory=list) + answered: list[tuple[str | None, Usage]] = field(default_factory=list) unreported: int = 0 refused: int = 0 - models: list[str | None] = field(default_factory=list) # each answered call's model, as its request named it def add(self, status: int | None, usage: Usage | None, model: str | None = None) -> None: """A call that ended with ``status`` (None when it had none), the usage its answer carried and the model its @@ -55,8 +54,7 @@ def add(self, status: int | None, usage: Usage | None, model: str | None = None) if usage is None: self.unreported += 1 else: - self.answered.append(usage) - self.models.append(model) + self.answered.append((model, usage)) def usage(self, tool_call_count: int, model: str | None = None) -> Usage: """The calls' usage summed, with ``input_tokens`` counting the cache, and the calls without usage counted in @@ -69,12 +67,13 @@ def usage(self, tool_call_count: int, model: str | None = None) -> Usage: details["unreported_calls"] = self.unreported if not self.answered: return Usage(tool_call_count=tool_call_count, provider_details=details) + usages = [usage for _, usage in self.answered] def total(name: str) -> int | None: - values = [getattr(usage, name) for usage in self.answered if getattr(usage, name) is not None] + values = [getattr(usage, name) for usage in usages if getattr(usage, name) is not None] return sum(values) if values else None - flags = {usage.input_includes_cache for usage in self.answered} + flags = {usage.input_includes_cache for usage in usages} return Usage(tool_call_count=tool_call_count, **{name: total(name) for name in _COUNTS}, input_includes_cache=flags.pop() if len(flags) == 1 else None, models=self._by_model(model), provider_details=details) @@ -82,7 +81,7 @@ def total(name: str) -> int | None: def _by_model(self, configured: str | None) -> tuple[ModelUsage, ...]: """The answered calls' counts by model; none when a call named no model and the turn has none configured.""" by_model: dict[str, list[Usage]] = {} - for named, usage in zip(self.models, self.answered): + for named, usage in self.answered: if (name := named or configured) is None: return () by_model.setdefault(name, []).append(usage) diff --git a/tst/unit/agents/test_model_relay.py b/tst/unit/agents/test_model_relay.py index 353942b47..d8c4e7ced 100644 --- a/tst/unit/agents/test_model_relay.py +++ b/tst/unit/agents/test_model_relay.py @@ -114,7 +114,7 @@ async def exercise(client, root, endpoint): assert endpoint.requests[0]["path"] == "/v1/chat/completions" assert endpoint.requests[0]["headers"]["authorization"] == "Bearer sk-cli" assert endpoint.requests[0]["headers"]["accept-encoding"] == "identity" - (usage,) = calls.answered + ((_, usage),) = calls.answered assert (usage.input_tokens, usage.output_tokens, usage.cache_read_tokens, usage.cache_write_tokens, usage.input_includes_cache) == (20948, 43, 10363, 199, True) @@ -135,7 +135,7 @@ async def exercise(client, root, endpoint): _, calls, _ = _through_relay([(200, responses, "text/event-stream"), (200, messages, "text/event-stream"), (200, body, "application/json")], exercise) - assert [(usage.input_tokens, usage.output_tokens, usage.cache_read_tokens) for usage in calls.answered] == [ + assert [(usage.input_tokens, usage.output_tokens, usage.cache_read_tokens) for _, usage in calls.answered] == [ (900, 7, 512), (803, 12, 800), (50, 5, None)] @@ -166,7 +166,7 @@ async def exercise(client, root, endpoint): _, calls, _ = _through_relay([(200, CLAUDE_STREAM, "text/event-stream")], exercise) - assert [usage.input_tokens for usage in calls.answered] == [20948] + assert [usage.input_tokens for _, usage in calls.answered] == [20948] def test_a_call_whose_cli_hung_up_before_the_answer_began_is_still_counted(): @@ -179,7 +179,7 @@ async def exercise(client, root, endpoint): _, calls, _ = _through_relay([(200, CLAUDE_STREAM, "text/event-stream")], exercise) - assert [usage.input_tokens for usage in calls.answered] == [20948] + assert [usage.input_tokens for _, usage in calls.answered] == [20948] def test_a_long_streams_usage_is_read_however_long_it_ran(): @@ -213,7 +213,7 @@ async def exercise(client, root, endpoint): text, calls, _ = _through_relay([(200, CLAUDE_STREAM, "text/event-stream")], exercise) assert text == CLAUDE_STREAM - assert [usage.input_tokens for usage in calls.answered] == [20948] + assert [usage.input_tokens for _, usage in calls.answered] == [20948] def test_another_turns_path_reaches_nothing_and_other_routes_are_not_calls():