Streaming
Stream AI responses in real time with Server-Sent Events. Use stream:true with the OpenAI-compatible chat completions endpoint for token-by-token output.
Streaming lets you receive tokens as they're generated, providing a better user experience for chat and long-form generation.
Enabling streaming
Set stream: true in your request body:
curl https://api.ruvicode.com/v1/chat/completions \
-H "Authorization: Bearer rvcd_..." \
-H "Content-Type: application/json" \
-d '{
"model": "glm-5.2",
"messages": [{"role": "user", "content": "Write a poem"}],
"stream": true
}'SSE format
Streaming responses use Server-Sent Events. Each line starts with data: :
data: {"choices":[{"delta":{"content":"Hello"}}]}
data: {"choices":[{"delta":{"content":" world"}}]}
data: {"choices":[{"finish_reason":"stop"}]}
data: [DONE]
Python streaming
stream = client.chat.completions.create(
model="glm-5.2",
messages=[{"role": "user", "content": "Hello!"}],
stream=True
)
for chunk in stream:
if not chunk.choices:
continue # the final chunk carries usage and no choices
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)Node.js streaming
const stream = await client.chat.completions.create({
model: "glm-5.2",
messages: [{ role: "user", content: "Hello!" }],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) process.stdout.write(content);
}Usage and cost
You don't need to set stream_options.include_usage yourself, the gateway adds it when missing so the final chunk always carries usage. That chunk also carries the exact charge for the request as usage.cost, in USD (the same figure as the X-Cost header on non-streaming responses, which a stream cannot send because its headers go out before generation starts):
data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":7,"total_tokens":19,"cost":0.00004321}}OpenAI SDKs keep the extra field: in Python read chunk.usage.cost (or chunk.usage.model_extra["cost"]), in Node chunk.usage.cost.
Keep in mind that usage arrives only in the final SSE chunk, before [DONE]. If the stream ends before that chunk (your client disconnects, the connection drops, or a stream time limit is reached) after output already reached you, the request is billed an estimate of the prompt and the output delivered. If your client disconnects before any output, the prompt may still be billed as an estimate, because the provider has already processed it. When the provider later reports the real token counts, the charge is corrected to them.
Strict SSE parsing
Events are separated by blank lines, per the SSE specification. Each data: line is one JSON chunk, and the stream ends with data: [DONE]. Standard parsers (EventSource, OpenAI SDKs, Vercel AI SDK) work out of the box.