Skip to content

Type to search the docs and the model list.

Streaming

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

Add "stream": true to a chat completions 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 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.

# -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."}]}'
  • 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).
  • 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 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 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). It is true for every chat model today.