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].deltausually hasrole: "assistant"and often the first words incontent. - Each following chunk's
delta.contentholds the next piece of text. Add the pieces together in order. A chunk can also carry no text at all, so check thatcontentis set. - A chunk whose
finish_reasonis set ends the answer:stop(finished),length(hitmax_tokens),tool_calls(the model wants a tool run) orerror(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'
EventSourcecannot send a POST body or anAuthorizationheader. Read the stream withfetch, 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 anevent:line, in this order:message_start, then for each content blockcontent_block_start, manycontent_block_deltaandcontent_block_stop, thenmessage_delta(withstop_reasonand the output tokens) andmessage_stop.pingevents can appear in between and can be ignored. A failure is anerrorevent. - Responses (
POST /v1/responses): read thetypefield in eachdata:line (do not rely onevent:lines being present):response.created,response.in_progress,response.output_item.added,response.content_part.added, manyresponse.output_text.delta, thenresponse.output_text.done,response.content_part.done,response.output_item.doneandresponse.completed, which holds the full response with itsusage. A normal stream ends withdata: [DONE]; a failure ends it with anerrorevent 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.