# Streaming

Get a chat answer piece by piece as it is written, with token usage and errors.

Add `"stream": true` to a [chat completions](https://ewest.ai/docs/chat) request and the answer arrives as Server-Sent Events while the model writes it, instead of as one JSON body at the end. You see the first words sooner, and long answers are not held up by the time limit on a normal response. The OpenAI libraries do this with `stream=True`.

## The chat stream

The response has `Content-Type: text/event-stream`. Each event is one line starting with `data: ` and holding a JSON chunk, followed by a blank line. Every chunk has `"object": "chat.completion.chunk"`, the same `id` for the whole answer, and the `ewest/*` name in `model`.

- The first chunk's `choices[0].delta` usually has `role: "assistant"` and often the first words in `content`.
- Each following chunk's `delta.content` holds the next piece of text. Add the pieces together in order. A chunk can also carry no text at all, so check that `content` is set.
- A chunk whose `finish_reason` is set ends the answer: `stop` (finished), `length` (hit `max_tokens`), `tool_calls` (the model wants a [tool](https://ewest.ai/docs/tool-calling) run) or `error` (see below).
- The last event is the literal line `data: [DONE]`, which is not JSON.

## Token usage

Streamed answers carry token counts only if you ask: send `"stream_options": {"include_usage": true}`. The counts then arrive in one extra chunk after the one with `finish_reason` and before `[DONE]`. That chunk has a `usage` object with `prompt_tokens`, `completion_tokens` and `total_tokens` and no text. Without the option no chunk has `usage`.

## Reading the stream

The examples below read the stream by hand, so you can see the format. They print the text as it arrives, return the usage, stop at `[DONE]`, and raise an error if the answer fails part-way. With the OpenAI libraries you can skip all of that: they do the same for you.

cURL:

```bash
# -N turns off curl's output buffering so chunks print as they arrive.
curl -N https://api.ewest.ai/v1/chat/completions \
  -H "Authorization: Bearer $EWEST_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "ewest/gemini-flash",
       "stream": true,
       "stream_options": {"include_usage": true},
       "messages": [{"role": "user", "content": "Write a haiku about the sea."}]}'
```

Python:

```python
import json, os, requests

def stream_chat(payload, on_text):
    """Calls on_text() with each piece of the answer; returns the token usage."""
    usage = None
    finished = False
    with requests.post(
        "https://api.ewest.ai/v1/chat/completions",
        headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"},
        json={**payload, "stream": True, "stream_options": {"include_usage": True}},
        stream=True,
        timeout=(10, 100),  # connect, then at most 100 s of silence
    ) as res:
        if not res.ok:  # a problem found before the answer starts is a normal error response
            raise RuntimeError(f"{res.status_code}: {res.text}")
        for raw in res.iter_lines():
            line = raw.decode("utf-8")
            if not line.startswith("data:"):
                continue  # blank separators and comments
            data = line[5:].strip()
            if data == "[DONE]":
                finished = True
                break
            chunk = json.loads(data)
            if chunk.get("error"):  # the answer failed after it started; the stream ends here
                raise RuntimeError(chunk["error"].get("message", "stream failed"))
            usage = chunk.get("usage") or usage  # arrives in the last chunk before [DONE]
            for choice in chunk.get("choices", []):
                text = choice.get("delta", {}).get("content")
                if text:
                    on_text(text)
    if not finished:  # the connection dropped: the answer may be incomplete
        raise RuntimeError("stream ended before [DONE]")
    return usage

usage = stream_chat(
    dict(
        model="ewest/gemini-flash",
        messages=[{"role": "user", "content": "Write a haiku about the sea."}],
    ),
    lambda text: print(text, end="", flush=True),
)
print("\n", usage)
```

JavaScript:

```javascript
async function streamChat(payload, onText) {
  // Give up after 100 s without any data (the timer restarts on every read).
  const controller = new AbortController();
  let timer;
  const idle = () => {
    clearTimeout(timer);
    timer = setTimeout(() => controller.abort(), 100_000);
  };
  idle();
  try {
    const res = await fetch("https://api.ewest.ai/v1/chat/completions", {
      method: "POST",
      headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({ ...payload, stream: true, stream_options: { include_usage: true } }),
      signal: controller.signal,
    });
    // A problem found before the answer starts is a normal error response.
    if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
    return await readStream(res, onText, idle);
  } finally {
    clearTimeout(timer);
  }
}

async function readStream(res, onText, idle) {
  let usage = null;
  let finished = false;
  const handle = (line) => {
    if (!line.startsWith("data:")) return; // blank separators and comments
    const data = line.slice(5).trim();
    if (data === "[DONE]") {
      finished = true;
      return;
    }
    const chunk = JSON.parse(data);
    // The answer failed after it started; the stream ends here.
    if (chunk.error) throw new Error(chunk.error.message ?? "stream failed");
    usage = chunk.usage ?? usage; // arrives in the last chunk before [DONE]
    for (const choice of chunk.choices ?? []) {
      if (choice.delta?.content) onText(choice.delta.content);
    }
  };

  // A chunk can end in the middle of a line, so keep the unfinished part for the next read.
  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  for (;;) {
    const { done, value } = await reader.read();
    idle();
    buffer += decoder.decode(value, { stream: !done });
    const lines = buffer.split("\n");
    buffer = done ? "" : lines.pop();
    lines.forEach(handle);
    if (done) {
      // The connection dropped: the answer may be incomplete.
      if (!finished) throw new Error("stream ended before [DONE]");
      return usage;
    }
  }
}

const usage = await streamChat(
  {
    model: "ewest/gemini-flash",
    messages: [{ role: "user", content: "Write a haiku about the sea." }],
  },
  (text) => process.stdout.write(text),
);
console.log("\n", usage);
```

- A network read can end in the middle of a line. Keep the unfinished part and add the next read to it, as the JavaScript example does.
- Browsers' `EventSource` cannot send a POST body or an `Authorization` header. Read the stream with `fetch`, and call eWest from your server, not from the page, so the key stays private (see [Authentication](https://ewest.ai/docs/authentication)).
- Set a read timeout on the connection (not only a total time), so a stalled stream does not hang for ever.

## Errors and time limits

A problem found before the answer starts, such as a wrong key or an unknown model, is a normal HTTP error and the body is not a stream: check `res.ok` first. Once the answer has started the status is already `200`, so a later failure arrives inside the stream. For chat, the last chunk then has `finish_reason: "error"` and an `error` object, and the stream ends. Text you already received stays valid. To try again, send the whole request again. [Errors](https://ewest.ai/docs/errors#streams) lists this for all three stream formats.

A chat request has to produce its first byte within about 90 seconds. Without streaming the first byte is the finished answer, so the whole answer has to arrive within that time. With streaming the first chunk normally comes within seconds, so use it for long answers, and for any model or prompt that may take a while. See [Rate limits and retries](https://ewest.ai/docs/rate-limits) for what to retry.

## Messages and Responses streams

The other two text endpoints stream too, with `"stream": true` and the event names of their own formats. Token usage is part of the stream there and needs no option.

- **Messages** (`POST /v1/messages`): events with an `event:` line, in this order: `message_start`, then for each content block `content_block_start`, many `content_block_delta` and `content_block_stop`, then `message_delta` (with `stop_reason` and the output tokens) and `message_stop`. `ping` events can appear in between and can be ignored. A failure is an `error` event.
- **Responses** (`POST /v1/responses`): read the `type` field in each `data:` line (do not rely on `event:` lines being present): `response.created`, `response.in_progress`, `response.output_item.added`, `response.content_part.added`, many `response.output_text.delta`, then `response.output_text.done`, `response.content_part.done`, `response.output_item.done` and `response.completed`, which holds the full response with its `usage`. A normal stream ends with `data: [DONE]`; a failure ends it with an `error` event and no `[DONE]`.

> Whether a model can stream is the `supports_streaming` field in `GET /v1/models/{id}` (see [Models](https://ewest.ai/docs/models)). It is true for every chat model today.

Source: https://ewest.ai/docs/streaming
