Streaming
All generative endpoints support streaming — set stream: true on the request and the response is delivered as Server-Sent Events (SSE).
Enabling streaming
Section titled “Enabling streaming”stream = client.chat.completions.create( model="...", messages=[{"role": "user", "content": "Hello"}], stream=True, stream_options={"include_usage": True},)for chunk in stream: if chunk.choices: print(chunk.choices[0].delta.content or "", end="")with client.messages.stream( model="...", max_tokens=1024, messages=[{"role": "user", "content": "Hello"}],) as stream: for text in stream.text_stream: print(text, end="")curl https://api.aiand.com/v1/chat/completions \ -H "Authorization: Bearer sk-..." \ -d '{"model":"...","stream":true,"messages":[{"role":"user","content":"Hello"}]}'What you receive
Section titled “What you receive”- OpenAI shape:
data: {...}events withchoices[].deltachunks; finaldata: [DONE]. - Anthropic shape: typed events —
message_start,content_block_delta,message_delta,message_stop. - ai& trailer (OpenAI shape, opt-in): with the
X-Aiand-Metrics: truerequest header, ai& appends ametricsevent with token counts, cost, and currency after the model’s terminal event. See Streaming Events.
When the model stops sending
Section titled “When the model stops sending”If the model sends nothing for 5 minutes after the stream has started, ai& ends the stream with an error event instead of the terminal event, and bills the output you received:
- OpenAI shape:
event: errorwithdata: {"error":{"type":"server_error","code":"timeout",...}}, and nodata: [DONE]. - Anthropic shape:
event: errorwithdata: {"type":"error","error":{"type":"timeout_error",...}}, and nomessage_stop.
The OpenAI and Anthropic SDKs raise this as an API error. Treat the partial output as incomplete.
Usage and cost in streams
Section titled “Usage and cost in streams”Set stream_options.include_usage = true (OpenAI shape) to get the final usage block before the trailer event. Anthropic streams always carry usage in message_delta.