Skip to content

[Streaming] Token usage not returned when stream is aborted mid-generation #539

Description

@Hovo-Dev

Summary

When using streaming with stream_options: { include_usage: true },
the token usage chunk is never received if the stream is aborted
mid-generation. This makes accurate token tracking impossible for
apps that allow users to cancel responses early.

Current Behavior

The usage chunk is emitted as the very last SSE event, after generation
fully completes:

data: {"choices": [{"delta": {"content": "..."}}]} ← content chunks
data: {"choices": [{"finish_reason": "stop"}]} ← generation done
data: {"usage": {"prompt_tokens": 10, ...}} ← never received on abort
data: [DONE]

If the client aborts at any point before generation finishes, the usage
chunk is never sent.

Expected Behavior

One of the following:

Option A — Emit a partial usage chunk when server detects client disconnect:
data: {"usage": {"prompt_tokens": 42, "completion_tokens": 17, "partial": true}}

Option B — Include a running completion_tokens_so_far counter
on every chunk (opt-in via stream_options):
data: {"delta": {"content": "..."}, "usage": {"completion_tokens_so_far": 5}}

Why It Matters

  • Billing per user becomes inaccurate when generation is cancelled
  • Common real-world patterns that trigger this: user closes tab,
    presses stop button, request timeout fires
  • Workarounds like client-side tiktoken counting are approximate
    and inconsistent across models

Reproduction

const stream = await openai.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Write a very long essay" }],
  stream: true,
  stream_options: { include_usage: true },
});

for await (const chunk of stream) {
  // abort after first chunk
  stream.controller.abort();
  break;
}
// usage is never received

Workaround Today

Client-side token estimation using js-tiktoken — inaccurate,
especially for tokens with special characters or multi-byte sequences.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    apiAPI behavior, capabilities, availability, and account-related feedback.enhancementNew feature or requestreproReproduced; investigation details recorded in Linear

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions