agentscope-java icon indicating copy to clipboard operation
agentscope-java copied to clipboard

[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

Open littlebird69 opened this issue 1 month ago • 2 comments

Describe the bug

  1. ChatCompletionsResponseBuilder#buildResponse (agentscope-extensions-chat-completions-web) never calls setUsage(...), so the non-streaming /v1/chat/completions response has no usage object. The class javadoc example shows "usage": {"prompt_tokens": 10, ...}, and ChatCompletionsResponse already has a Usage type and setter. Gateways (OneAPI/NewAPI), LangChain callbacks and cost trackers read this field.

  2. The natural one-line fix, response.setUsage(...) from reply.getChatUsage(), would under-report for any agent that called a tool. In ReActAgent the final Msg only 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 is ModelCallEndEvent.

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_USAGE per-call. For example, accumulate ModelCallEndEvent usage per invocation and attach it under a new metadata key such as MessageMetadataKeys.INVOCATION_USAGE, or on AgentResultEvent. Then buildResponse maps that to usage, 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 ModelCallEndEvent usage itself, e.g. via a small onModelCall middleware. 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.

littlebird69 avatar Oct 20 '26 10:10 littlebird69

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.

littlebird69 avatar Oct 20 '26 10:10 littlebird69

PR is up: #3713 (Option A, as no one objected).

  • Core: new MessageMetadataKeys.INVOCATION_USAGE / Msg#getInvocationUsage(), the sum of the agent's own ModelCallEndEvents in one invocation. Subagent usage is not included. CHAT_USAGE stays per-call.
  • chat-completions: buildResponse maps it to usage, 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.

littlebird69 avatar Oct 22 '26 02:10 littlebird69