feat: add StreamChunk::Usage variant for streaming token usage #96
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
StreamChunk::Usage(Usage)variant to expose token usage data during streamingmessage_deltaeventsstream_options.include_usageis set)Donefor predictable consumer patternsMotivation
When using
chat_stream_with_tools, we need a way to get token usage data (input_tokens, output_tokens, cache_read_tokens, etc.) that's available in non-streamingChatResponse::usage(). Both Anthropic and OpenAI include usage in their final streaming events, but this data wasn't being exposed.Changes
src/chat/mod.rsStreamChunk::Usage(Usage)variantsrc/backends/anthropic.rsusagefield toAnthropicStreamResponse, createdconvert_anthropic_usage()helper, updated parser to emit Usage before Donesrc/providers/openai_compatible.rsusagefield toOpenAIToolStreamChunk, updated parser to emit Usage (handles both inline and separate chunk cases)tests/test_backends.rsAPI Behavior
Anthropic:
message_deltaevents include cumulativeusagefieldStreamChunk::Usageimmediately beforeStreamChunk::DoneOpenAI:
usagewhenstream_options.include_usage: true(already configured)finish_reason, or in separate empty-choices chunkUsage Example
Test Plan