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

[Feature]: chat-completions streaming: support stream_options.include_usage (report usage in the final chunk)

Open littlebird69 opened this issue 1 month ago • 2 comments

Is your feature request related to a problem? Please describe.

Follow-up to #3679 / #3713, which add usage to the non-streaming /v1/chat/completions response. The streaming response has no way to report usage at all:

  • ChatCompletionsRequest has no stream_options field, so "stream_options": {"include_usage": true} from the client is silently ignored.
  • ChatCompletionsChunk has no usage field.
  • ChatCompletionsStreamingAdapter#stream is built on the deprecated ReActAgent#stream(List, StreamOptions) / Event API (EventType.REASONING, EventType.TOOL_RESULT), which does not expose ModelCallEndEvent or AgentResultEvent, so the adapter has nothing to read the total from.

Per the OpenAI spec, when the request sets stream_options: {"include_usage": true}, the chunk usage field "contains a null value except for the last chunk which contains the token usage statistics for the entire request". Most clients stream by default (OpenAI SDKs, LangChain, gateways such as OneAPI/NewAPI), so in practice they currently get no usage from this endpoint at all.

Describe the solution you'd like

  1. Add stream_options (with include_usage) to ChatCompletionsRequest, and an optional usage field to ChatCompletionsChunk. It stays omitted (NON_NULL, as today) unless requested, so existing clients see no change.
  2. Move ChatCompletionsStreamingAdapter from the deprecated stream(...) to ReActAgent#streamEvents(...). Text and tool-call deltas map from TextBlockDeltaEvent / ToolCall*Event, and the final AgentResultEvent gives the reply and, with #3713, Msg#getInvocationUsage().
  3. When include_usage is true, emit one more chunk before data: [DONE] carrying that total. If no model call reported usage, keep usage absent rather than reporting zeros, consistent with #3713.

Step 2 is the bulk of the work, but it is needed anyway since stream(...) is @Deprecated(since = "2.0.0", forRemoval = true). It also removes the current text-deduplication workaround (hasSeenIncrementalReasoning / convertEventToChunksWithoutText), because streamEvents exposes the deltas as separate TextBlockDeltaEvents instead of a final accumulated event that has to be filtered out.

Describe alternatives you've considered

  • Keep the deprecated Event API and sum usage from the last REASONING event of each model call. This avoids the migration, but it relies on every model call surfacing as a final REASONING event with its usage (I haven't verified this for the summary and structured-output calls), and it duplicates the aggregation #3713 adds to core. It would also have to be redone when stream(...) is removed.
  • Always include usage in the last chunk. Simpler, but it doesn't follow the spec: clients that didn't ask for it don't expect the extra usage-only chunk.

Additional context

I'd like to wait until the direction of #3713 is settled (in particular, where the invocation total lives), then implement this. I'm happy to take it if that works for the maintainers.

littlebird69 avatar Oct 22 '26 13:10 littlebird69

I'll take this one. I'll build it on top of #3713, since it needs the invocation total from there, and open a PR once that settles. If #3713's direction changes, I'll adapt.

littlebird69 avatar Oct 22 '26 13:10 littlebird69

One more requirement from downstream use, which I'll fold into #3725 before taking it out of draft.

Callers that drive the agent themselves have no non-deprecated path. An OpenAI-compatible endpoint built on this extension (ours, for example) calls ReActAgent#streamEvents(messages, ctx) itself:

  • it passes a per-request RuntimeContext (session, user, memory opt-out), and
  • it needs to observe AgentResultEvent itself, e.g. to tell a finished turn from one that stopped for tool confirmation (GenerateReason.PERMISSION_ASKING).

Today such a caller uses the per-event convertEventToChunks(Event, ...). In #3725 that method is deprecated, the AgentEvent conversion (toChunks) is private, and stream(...) takes no RuntimeContext. So the only way left for these callers is the deprecated Event API that this issue is moving away from.

Planned additions to #3725:

  1. A stream(...) overload that takes a RuntimeContext and passes it to streamEvents(messages, ctx).
  2. The per-event conversion exposed as a public per-stream converter, e.g. newEventConverter(requestId, model, includeUsage), returning a stateful AgentEvent -> List<ChatCompletionsChunk> function (the tool call index and tool result text are per stream). Callers that drive streamEvents themselves can then convert events while still seeing them. The existing stream(...) methods would be built on it.
  3. The deprecation note on convertEventToChunks points to that converter.

littlebird69 avatar Oct 30 '26 09:10 littlebird69