[Feature]: chat-completions streaming: support stream_options.include_usage (report usage in the final chunk)
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:
ChatCompletionsRequesthas nostream_optionsfield, so"stream_options": {"include_usage": true}from the client is silently ignored.ChatCompletionsChunkhas nousagefield.ChatCompletionsStreamingAdapter#streamis built on the deprecatedReActAgent#stream(List, StreamOptions)/EventAPI (EventType.REASONING,EventType.TOOL_RESULT), which does not exposeModelCallEndEventorAgentResultEvent, 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
- Add
stream_options(withinclude_usage) toChatCompletionsRequest, and an optionalusagefield toChatCompletionsChunk. It stays omitted (NON_NULL, as today) unless requested, so existing clients see no change. - Move
ChatCompletionsStreamingAdapterfrom the deprecatedstream(...)toReActAgent#streamEvents(...). Text and tool-call deltas map fromTextBlockDeltaEvent/ToolCall*Event, and the finalAgentResultEventgives the reply and, with #3713,Msg#getInvocationUsage(). - When
include_usageis true, emit one more chunk beforedata: [DONE]carrying that total. If no model call reported usage, keepusageabsent 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
EventAPI and sum usage from the lastREASONINGevent of each model call. This avoids the migration, but it relies on every model call surfacing as a finalREASONINGevent 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 whenstream(...)is removed. - Always include
usagein 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.
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.
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
AgentResultEventitself, 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:
- A
stream(...)overload that takes aRuntimeContextand passes it tostreamEvents(messages, ctx). - The per-event conversion exposed as a public per-stream converter, e.g.
newEventConverter(requestId, model, includeUsage), returning a statefulAgentEvent -> List<ChatCompletionsChunk>function (the tool call index and tool result text are per stream). Callers that drivestreamEventsthemselves can then convert events while still seeing them. The existingstream(...)methods would be built on it. - The deprecation note on
convertEventToChunkspoints to that converter.