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.
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, or look the request up afterwards with GET /v1/requests/{id}. See 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.
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 shows how to check first.
Tool calls in a stream#
Tool-call arguments arrive in pieces across chunks. Tool calling shows how to assemble them.