# Streaming

Stream chat completions as server-sent events, and read exact token counts from the last chunk.


Set `stream` to `true` on `POST /v1/chat/completions` and the reply arrives as server-sent events, one `data:` line per chunk, ending with `data: [DONE]`. The first token shows up as soon as the model writes it.

## Get token counts

Set `stream_options.include_usage` to `true`. The last chunk before `[DONE]` then has an empty `choices` array and a `usage` object with exact token counts. These are the numbers you are billed on.

```python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["BOUNDLESS_API_KEY"],
    base_url="https://api.inference.boundless.network/v1",
)

stream = client.chat.completions.create(
    model="deepseek/deepseek-v4.1-flash-1017",
    messages=[{"role": "user", "content": "Say hello"}],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print(f"\n{chunk.usage}")
```

Check `chunk.choices` before you read it. The usage chunk has none.

## Cost on a stream

A streamed response sends its headers before the first token, so the charge is not known yet. `X-Response-Cost` is left out, not set to zero. Read the usage chunk and multiply by the [rate card](https://inference.boundless.network/docs/pricing), or look the request up afterwards with `GET /v1/requests/{id}`. See [Request ids and per-request cost](https://inference.boundless.network/docs/api-compatibility#request-ids-and-per-request-cost).

## Other wire formats

`POST /v1/responses` streams the request lifecycle as typed events. `POST /v1/messages` streams the standard Anthropic SSE events. See [API Compatibility](https://inference.boundless.network/docs/api-compatibility).

## When a stream fails

A failure before the first byte is an ordinary HTTP error with a status and a JSON body. A failure after the stream has started cannot change the status, which is already 200. The gateway sends one error event with the same `error` object, then closes the stream. A stream that ends without `[DONE]` did not finish.

Do not resend blindly. The request may have been charged for the tokens it produced. [Retrying safely](https://inference.boundless.network/docs/errors#retrying-safely) shows how to check first.

## Tool calls in a stream

Tool-call arguments arrive in pieces across chunks. [Tool calling](https://inference.boundless.network/docs/tool-calling) shows how to assemble them.
