Streaming
Receive tokens as they are generated using server-sent events.
Streaming#
Set "stream": true to receive the response incrementally as server-sent events instead of waiting for the full completion.
curl https://cleanapis.com/v1/chat/completions \
-H "Authorization: Bearer cc_your_key_here" \
-H "Content-Type: application/json" \
-N \
-d '{
"model": "claude-opus-4.8",
"messages": [{"role": "user", "content": "Count to three"}],
"stream": true
}'
Response format#
The response arrives as text/event-stream. Each event is a data: line holding one chunk:
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","model":"claude-opus-4.8","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","model":"claude-opus-4.8","choices":[{"index":0,"delta":{"content":"One"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","model":"claude-opus-4.8","choices":[{"index":0,"delta":{"content":", two"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":12,"completion_tokens":9,"total_tokens":21}}
data: [DONE]
Concatenate choices[0].delta.content from every chunk to rebuild the full message. The stream always terminates with data: [DONE].
Token usage appears in the final chunk before [DONE].
Python#
from openai import OpenAI
client = OpenAI(api_key="cc_your_key_here", base_url="https://cleanapis.com/v1")
stream = client.chat.completions.create(
model="claude-opus-4.8",
messages=[{"role": "user", "content": "Write a haiku about databases"}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)
Node.js#
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "cc_your_key_here",
baseURL: "https://cleanapis.com/v1",
});
const stream = await client.chat.completions.create({
model: "claude-opus-4.8",
messages: [{ role: "user", content: "Write a haiku about databases" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
Long-running sessions#
Streaming connections stay open for up to one hour, and a keep-alive comment (: ping) is sent every 15 seconds so intermediaries do not drop an idle connection. This suits long agentic coding sessions.
Errors mid-stream#
If the upstream provider fails after the stream opens, an error frame is emitted and the stream closes cleanly:
data: {"error":{"message":"Upstream provider unavailable","type":"provider_error","code":502}}
data: [DONE]
Always check each parsed chunk for an error key.
Still stuck?
Open a support ticket from your dashboard and we'll take a look.