# Usage in streams

**Last updated:** 2026-11-27T12:30:47-03:00 (UTC-3)

In streamed (SSE) responses, the provider can report usage in a finishing chunk or terminal event; it is not necessarily the last SSE event. With `stream_usage`, the gateway reads the bounded stream while it relays it to the client and records the input and output counters, without changing a single byte. Without the flag, streamed calls have no tokens in the history.

It applies to the native streams of Chat Completions, Responses, Anthropic Messages and Gemini.

With [durable receipts](/docs/features/durable-usage/#recovery), a live stream keeps its pending receipt renewed until the actual operation ends. The receipt lease is not an additional generation timeout. This heartbeat does not create usage counters: terminal provider evidence is still required below, and a truncated or cancelled answer remains conservative.

## Administrative interruption

An emergency stop interrupts an unfinished stream without a provider-blaming error event, a normal terminal marker or a retry. Once response headers have been sent, the HTTP connection is aborted rather than given a second status. With usage collection, an actual stop is logged at Info with `termination: gateway_panic`; its measurement keeps the observer's original state. A known stop reason creates no tokens or financial proof. A terminal response or completed receipt already observed before a later stop keeps its existing evidence. Client cancellation and genuine provider read errors retain their own classification. See [operations](/docs/operate/operations/#emergency-stop-panic) and [telemetry](/docs/features/observability/#logs-and-traces-otlp).

## How to turn it on

```yaml
features:
  stream_usage: true
```

In **Chat Completions**, the provider sends the usage only when the request sets `stream_options: {"include_usage": true}`. By default that is the client's choice; an alias with [`stream_usage: inject`](#ask-for-the-usage-on-the-clients-behalf) asks for it when the client did not.

## What is recorded

| Route | Where usage comes from | Recorded |
| --- | --- | --- |
| Chat Completions | Last chunk with `usage` and `choices: []`, followed by `[DONE]` | `prompt_tokens`, `completion_tokens` |
| Responses | `response.completed`, `response.incomplete` or `response.failed` | `input_tokens`, `output_tokens` |
| Messages | `message_start`, cumulative `message_delta` and `message_stop` | `input_tokens`, final `output_tokens` (without summing deltas) |
| Gemini | Valid `finishReason` on every candidate and the last `usageMetadata` | `promptTokenCount`, `candidatesTokenCount` |

**Only proven counters are recorded.** An interrupted stream, or missing, invalid or partial counters leave usage **absent**, never zero. Identical duplicates are not summed. A stream the provider cut is still recorded as a failure: its request log row and request event carry `error_code: stream_interrupted` with the status the client received, every error count includes it, the provider error counter and the circuit breaker count it, and a budget reservation stays held, because the provider may have charged for the part it generated.

- Responses `incomplete` or `failed` can have valid usage, if the provider reports it; that does not turn into success.
- In Gemini, output is only `candidatesTokenCount`; the gateway does not deduce reasoning tokens from the total.
- Anthropic cache and tool tokens stay in their own fields and are not added to the input.

## Guarantees

- **No byte changes:** payload, events, order, status and headers stay the same. The one exception is an alias with `stream_usage: inject`, which removes the usage it asked for (below).
- **No extra cost:** no additional call, no retry, no queue.
- The gateway writes to the client before observing, and a slow client slows the stream down (backpressure).

Observation limits, per stream: 256 KiB per event, 32 MiB in total and 100,000 events (64 candidates in Gemini). Beyond that, measurement is turned off for that stream and the content keeps being delivered.

## Ask for the usage on the client's behalf

Most applications stream without `stream_options`, so their streamed calls have no tokens: the request log, [budgets and TPM](/docs/features/budgets-and-tpm/), [valuation](/docs/features/usage-valuation/) and [request events](/docs/features/request-events/) cannot say what they used, and under a budget such a stream is refused before the call (`stream_profile_not_supported`). Changing every application is often not possible. With `stream_usage: inject` on the alias, the gateway asks the provider for the usage itself, measures it, and takes it out of the stream before it reaches the client, so the client receives what it would have received without the option.

```yaml
features:
  stream_usage: true          # required: it is what reads the usage
models:
  - id: gpt-5-mini
    stream_usage: inject      # default: client
    targets:
      - provider: openai
        model: gpt-5-mini
```

| Field | Default | Values |
| --- | --- | --- |
| `models[].stream_usage` | `client` (also when absent) | `client`: the client's `stream_options` decides, as before. `inject`: the gateway asks for the usage when the client did not. |

The setting belongs to the alias, not to a target: whether the client sees a usage chunk is a property of the alias it calls, and every fallback target of one request must give the client the same stream. It is accepted only on an alias with the `chat` capability, and not on an `auto_route` alias (set it on the aliases the route chooses) or a [`alias_of`](/docs/features/model-aliases/) entry (it follows its canonical model). An unknown value is refused when the configuration loads and when the console or the model API saves the alias. The value is checked whatever the flag says, but it is applied only while `stream_usage` is on: without the flag nothing reads the usage, so nothing is asked for. Saved in the console (**Models**, the alias editor, **Stream usage**) or through the model API, it applies to the next request, with no restart; in the YAML it follows the usual rollout.

### When it applies

All of these must hold; otherwise the request goes out exactly as the client sent it:

- the request is a Chat Completions stream (`stream: true`) on `/v1/chat/completions`. The Messages, Responses and GenerateContent routes translated through the chat pipeline already ask for the usage themselves, since their own terminal events carry it;
- the client did not ask for the usage: `stream_options` is absent or `null`, or an object whose `include_usage` is absent, `null` or `false`. A client that sent `include_usage: true` keeps its stream exactly as before. A value the gateway cannot complete (`stream_options` that is not an object, an `include_usage` that is not a boolean) is the client's request and is forwarded as it is, so the provider answers it as before.

### What the provider receives

| Target | What the gateway changes |
| --- | --- |
| `openai` on Chat Completions (including any compatible backend) | `stream_options.include_usage: true`, keeping the client's other `stream_options` members (for example `include_obfuscation`) |
| SageMaker (the body is forwarded) | The same |
| OCI | The same, which its translation sends as `streamOptions.isIncludeUsage: true` |
| Anthropic, Gemini, Bedrock, Cohere, an `openai` target on the Responses API | Nothing: these providers always end their stream with the usage. Their translator then emits the canonical usage chunk, as if the client had asked, so the request is measured |

Before this setting, a translated stream whose client did not ask for the usage was measured only for a budget or a valuation (the translator reads the provider's usage for them); the request log and the request event had no tokens. With `inject` they have them too.

The change is made to each attempt's own copy of the body, after the [request parameter policy](/docs/features/request-parameter-policy/) of the target. The client's body, which the semantic cache key, guardrails and the next fallback target start from, is not changed. The policy and this setting are independent: `stream_options` is not in the policy's allowlist and cannot be dropped, so no policy can undo the injection.

### What the client receives

Exactly the stream the provider would send without `include_usage`, which by the [Chat Completions contract](https://developers.openai.com/api/reference/resources/chat/subresources/completions/streaming-events) has no usage at all:

- the final chunk that exists only for the usage (`"choices": []` with a non-null `usage`) is removed. A client that reads `choices[0]` of every chunk would fail on it. A compatible backend that leaves that chunk's `choices` out, or sends `null`, gets the same treatment;
- the `usage` member that every other chunk then carries (`"usage": null`, or a provider's usage on its finishing chunk or a running count) is removed from the chunk; everything else in the chunk keeps its bytes and order;
- `data: [DONE]`, comments, `id:`/`event:`/`retry:` lines, error events, the status and the headers are forwarded unchanged.

The gateway holds back only the event being received and forwards each event as soon as its closing blank line arrives (at its CR, for a provider that ends lines with CRLF, as SSE dispatches it): no read-ahead, no extra goroutine, the same backpressure. An event is decided whole, so a usage split across reads is still removed. The cost of that: a provider that sends one event in slow pieces, or a comment without its blank line, reaches the client only when the event ends, so a client with a short idle timeout sees the gap the provider left inside the event. Something the gateway cannot decide safely is forwarded as received:

- an event over the 256 KiB observation bound is forwarded as it arrives, untouched (the usage chunk is a few hundred bytes);
- a chunk whose JSON spans several `data:` lines keeps its `usage: null` (rewriting it would change its framing); a usage-only chunk is removed either way;
- data that is not a JSON object, or not valid JSON, passes untouched;
- an event the provider never finished (the stream ended or failed in its middle) is delivered as received, before the gateway's interruption event, as it would have been.

If the client leaves or the request ends before the provider's last event, the stream ends as any other cancelled stream: the unfinished event held is not delivered and the measurement is `cancelled`. With [`stream_settle_on_disconnect`](#when-the-client-disconnects) the provider is read to its end instead, and nothing more is delivered. Since no complete event is ever held, a cancellation after `[DONE]` keeps the stream `reported`, as without the setting.

### What is measured

The observer reads the provider's stream before the removal, so the injected usage is measured like a usage the client asked for: the request log's input and output tokens, the request event (`tokens`, `cost`), the [valuation](/docs/features/usage-valuation/) and, under a budget or TPM, the reservation is admitted and settled. On an openai Chat Completions target such a stream no longer needs the client's `include_usage`: the budget admits `stream_options` absent or `null`, or an object with only `include_usage` (`true`, `false` or `null`) and `include_obfuscation`, which changes padding, not tokens. The `stream_usage` log record of such a request adds `usage_injected` with `chunks_removed` and `members_removed`, so a measured stream the client asked nothing of is explainable.

A provider that ignores the option sends no usage: its stream reaches the client unchanged, the measurement is `missing` and the usage stays unknown (a budget reservation stays held), never zero.

### Before you turn it on

- A compatible backend that refuses `stream_options` answers 400 to every streamed request of the alias. Check the backend first, or keep `client` on that alias.
- A backend that always streams a usage, even unasked, loses it from the client's stream under `inject`: the client then receives the stream the Chat Completions contract promises for a request without `include_usage`.
- The usage is metered, not hidden from the provider: the provider still bills the same tokens; the option changes only what it reports.
- Semantic cache hits make no provider call and keep their behavior: they include the usage only when the client asked.

### Upgrade and rollback

Nothing changes on upgrade: every alias keeps `client` until it sets `inject`. There is no migration; an alias saved through the API keeps the field in its stored JSON. Before rolling back to an older binary, remove `stream_usage` from the YAML (its strict schema refuses the unknown field); an older binary ignores the field in a stored alias and sends streams as the client wrote them.

## When the client disconnects

By default a client that leaves in the middle of a stream ends the provider call with it: the gateway closes the provider connection at once. The final usage never arrives, so the stream is not measured, and under a [budget](/docs/features/budgets-and-tpm/) its reservation stays held as `unknown`, because the provider may have charged for what it generated.

Some clients do this on every run (a coding agent that opens a last call on exit and closes the connection without reading it). Each run then leaves one unknown reservation. For those, turn on `stream_settle_on_disconnect`:

```yaml
features:
  stream_usage: true
  stream_settle_on_disconnect: true
```

| | Off (default) | On |
| --- | --- | --- |
| Provider call after the client leaves | Closed at once | Read to its end; nothing more is written to the client |
| Usage | Not measured | The provider's final usage, as for a stream the client read whole |
| Reservation | Held as `unknown` | Settled at the measured amount |
| What the provider generates | Usually stops when the connection closes | **The whole answer, which the provider bills in full** |
| Request log | Cut by the client, no tokens | Cut by the client (`client_closed_stream`), with tokens and cost |

**The trade.** With the flag on, a client that gives up no longer stops the generation: the provider produces, and bills, the whole answer up to the request's own output limit. You pay for output nobody reads, and in exchange every call is measured and no budget is held by an unknown amount. Leave it off where clients cancel long answers on purpose; turn it on where unknown reservations from abandoned streams are the problem. It is an operator flag, off by default, changed in the YAML or under **Settings & sources** without a restart, and it requires `stream_usage`.

**Which streams.** Every stream the gateway measures for a reservation or a [valuation](/docs/features/usage-valuation/): Chat Completions, Responses, Anthropic Messages and Gemini `streamGenerateContent` (the Gemini API and Vertex AI), native or [translated](/docs/features/protocol-translation/) (Bedrock, Anthropic, Gemini and Cohere behind another route's dialect). The disconnect is noticed when the client's connection closes or a write to it fails. It counts from the moment the call goes out to the provider: a client that leaves while the gateway is still waiting for the provider's first byte no longer cancels the call, and the whole answer is read without being written.

**Bounds.** The read after the disconnect never runs free:

- the stream's own [clocks](/docs/features/stream-timeouts/) keep counting: `network.stream_idle_timeout` between provider bytes and `network.stream_max_duration` for the whole stream (or the request timeout without `stream_timeouts`);
- it stops after 256 KiB plus 1 KiB per token the reservation holds, and never past the 32 MiB the observer reads from any stream;
- the emergency stop ends it at once.

When a bound ends it, or the provider ends without a valid final usage, nothing is measured and the reservation stays held, exactly as with the flag off. Once the client has left, the gateway makes no new provider call for it: a retry or a fallback that would send the request again ends the request instead. The `stream_usage` log line then carries `after_client_disconnect` with `measured: false` and the bytes read.

**Where it does not apply**, and the reservation stays held:

- a stream that is not measured: `stream_usage` off, or a [passthrough](/docs/features/passthrough/) route, whose optional usage never proves a charge;
- a client that leaves before the call went out to the provider (while the request is still being admitted): nothing was sent, so nothing is held;
- a non-streaming call the client abandons: there is nothing to read ahead of the answer;
- [realtime](/docs/features/realtime/) sessions: each response is settled by its own terminal event, and the session ends with its WebSocket;
- an answer cut by an output guardrail, a gateway clock or the emergency stop: those are the gateway's decisions, not the client's.

For the unknown reservations that remain, see [financial reconciliation](/docs/features/quota-finance/).

## Limits

- Stream counters are for analytics, not for invoicing: [valuation](/docs/features/usage-valuation/) values a stream only when these counters are reported and every event fits its text profile. For budgets on streams, see `quota_streaming` in [protected profiles](/docs/features/quota-protocols/).
- The reason for a missing measurement goes in the request's structured log (`reported`, `missing`, `incomplete`, `invalid`, `limit_exceeded`, `cancelled`...), not in the console.

## See also

- [Logs, traces and metrics](/docs/features/observability/).
- [Durable receipts](/docs/features/durable-usage/).
- Official contracts: [OpenAI Chat streaming](https://developers.openai.com/api/reference/resources/chat/subresources/completions/streaming-events), [OpenAI Responses streaming](https://developers.openai.com/api/reference/resources/responses/streaming-events), [Anthropic streaming](https://platform.claude.com/docs/en/build-with-claude/streaming), [Gemini GenerateContent](https://ai.google.dev/api/generate-content).
