fix: track token usage for streaming (SSE) LLM responses - #214
Open
anwesha01b wants to merge 1 commit into
Open
Conversation
Resolves Ruthwik000#91. When a provider returns a text/event-stream or application/x-ndjson response, standardFetch previously called clonedResponse.json() which failed silently on SSE payloads, causing token counts and budget tracking to be entirely skipped. Add processStreamResponse() that asynchronously reads the cloned ReadableStream chunk-by-chunk, parses each SSE data line, and extracts usage fields per provider convention: - OpenAI / Grok / Kimi: usage.prompt_tokens / completion_tokens - Anthropic: message_start.message.usage + message_delta.usage - Gemini: usageMetadata.promptTokenCount / candidatesTokenCount The function fires in the background so the stream is returned to the caller immediately without blocking. If no usage data is found (e.g. provider omitted the usage chunk) it exits silently. Also export unpatchGlobalFetch from the public API so tests and integrations can cleanly restore the original fetch after use. Tests added: - tests/test-stream.js: full usage tracking via SSE with usage chunk - tests/test-stream-no-usage.js: graceful no-op when usage absent - tests/test-non-streaming-regression.js: existing JSON path unchanged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Problem
When making streaming LLM API requests (
stream: true), TokenFirewall silently skipped all token usage tracking and budget management. ThestandardFetchfunction cloned the response and calledclonedResponse.json()on it — which throws a SyntaxError on Server-Sent Events (SSE) payloads becausedata: …lines are not valid JSON. The error was caught by a broadcatchblock and swallowed silently, soinputTokens,outputTokens,totalCost, andbudgetManager.track()were never called.Closes #91
Root Cause
Before: always tried to JSON-parse the response body, which throws on SSE streams.
What Changed
src/interceptors/fetchInterceptor.tsstandardFetch, added aContent-Typecheck before attemptingclonedResponse.json().text/event-streamorapplication/x-ndjson, the newprocessStreamResponse()function is fired asynchronously in the background so the stream is returned to the caller immediately without blocking.processStreamResponse()reads the clonedReadableStreamchunk-by-chunk via aTextDecoder, parses eachdata:line, and accumulates token counts per provider convention:usage.prompt_tokens/completion_tokensmessage_start.message.usage.input_tokens+message_delta.usage.output_tokensusageMetadata.promptTokenCount/candidatesTokenCountsrc/index.tsunpatchGlobalFetchfrom the public API surface (previously internal only) to support clean teardown in tests and integrations.Tests
Three test scripts added under
tests/:test-stream.jstotalSpent > 0test-stream-no-usage.jstotalSpent == 0test-non-streaming-regression.jsAll three pass. TypeScript build (
tsc) passes with zero errors.git diff --checkpasses with zero trailing-whitespace violations.Notes
stream_options: { include_usage: true }in their OpenAI requests for the API to emit a usage chunk. TokenFirewall does not rewrite request bodies to inject this flag.processStreamResponsemeans budget enforcement for a streaming call takes effect on the next request, not mid-stream — consistent with standard quota-tracking conventions.