[Bug]: chat-completions non-streaming response never sets `usage`; and the agent's final `Msg` only carries the last model call's usage, so the obvious fix would under-report
Describe the bug
-
ChatCompletionsResponseBuilder#buildResponse(agentscope-extensions-chat-completions-web) never callssetUsage(...), so the non-streaming/v1/chat/completionsresponse has nousageobject. The class javadoc example shows"usage": {"prompt_tokens": 10, ...}, andChatCompletionsResponsealready has aUsagetype and setter. Gateways (OneAPI/NewAPI), LangChain callbacks and cost trackers read this field. -
The natural one-line fix,
response.setUsage(...)fromreply.getChatUsage(), would under-report for any agent that called a tool. InReActAgentthe finalMsgonly carries the usage of the last model call. The only aggregation,collectAggregatedUsage, is on the structured-output fallback path, and it sums only the structured-output attempts. Nothing in core exposes the total usage of one invocation; the only per-call source isModelCallEndEvent.
To reproduce
Model stub: the first call returns a ToolUseBlock with usage 10 in / 2 out; the second call returns text with usage 15 in / 3 out. After agent.call(...):
reply.getChatUsage(); // input=15, output=3 (last call only)
// expected for an OpenAI "usage" object: prompt=25, completion=5, total=30
Verified on main (0a409c83) and on v2.0.4. I have a JUnit test with this stub that I can contribute.
Why not just make the final Msg carry the aggregate
Msg#getChatUsage() is per-model-call today, and existing code reads it that way. For example, SessionModels persists the last message's usage, and each assistant message in the context keeps its own call's usage. Making the final message carry an aggregate would change that meaning. It would also double-count for anyone who sums usage over the context, which is what collectAggregatedUsage does.
Proposed fix (looking for maintainer preference before I open a PR)
- Option A (my preference): expose the invocation total separately and keep
CHAT_USAGEper-call. For example, accumulateModelCallEndEventusage per invocation and attach it under a new metadata key such asMessageMetadataKeys.INVOCATION_USAGE, or onAgentResultEvent. ThenbuildResponsemaps that tousage, and the field is omitted when no provider reported usage, instead of being reported as 0. - Option B: keep core unchanged and have the chat-completions starter accumulate
ModelCallEndEventusage itself, e.g. via a smallonModelCallmiddleware. This is narrower, but every other integration (A2A and so on) would have to repeat it.
Streaming (stream_options.include_usage) is out of scope here. ChatCompletionsChunk has no usage field, and ChatCompletionsRequest has no stream_options. I can file that as a separate feature request.
Happy to implement whichever option you prefer.
I'll take this one. I already have a regression test for both parts locally: the missing usage field, and the tool-call scenario where the final Msg reports 15 instead of 25. I'll open a PR as soon as we agree on a direction (Option A or B above). If nobody objects within a few days, I'll go ahead with Option A.
PR is up: #3713 (Option A, as no one objected).
- Core: new
MessageMetadataKeys.INVOCATION_USAGE/Msg#getInvocationUsage(), the sum of the agent's ownModelCallEndEvents in one invocation. Subagent usage is not included.CHAT_USAGEstays per-call. - chat-completions:
buildResponsemaps it tousage, and omits the field when no usage was reported.
One deviation from what I wrote above: the total is written onto the reply in place, so the stored final message carries it too. Returning a copy broke existing tests that compare the reply with the last context message by reference. Details and the alternative are in the PR description. Happy to switch if you prefer the other way.