Streaming
Both the Chat Completions and Responses endpoints support streaming via Server-Sent Events (SSE). Streaming delivers tokens incrementally as the model generates them, instead of waiting for the full response.
Enabling streaming
Set stream: true in the request body:
curl -X POST https://api.quantized.us/v1/chat/completions \
-H "Authorization: Bearer sk-quantized-YOUR-KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-4.1-mini",
"messages": [{"role": "user", "content": "Write a haiku about code."}],
"stream": true
}'
The response uses Content-Type: text/event-stream with the following headers:
Content-Type: text/event-stream; charset=utf-8
Cache-Control: no-cache
X-Accel-Buffering: no
x-request-id: 4bf92f3577b34da6a3ce929d0e0e4736
x-request-id identifies the request; see Request IDs. It is sent with these headers, so you have it before the first event arrives, and still have it if the stream later fails.
Errors that happen before the stream starts (validation, authentication, budget, policy, provider selection, or an input guardrail block) return a normal JSON error response with the matching status code. Once the stream has started, the status is 200 and errors are reported inside the stream. See Errors during a stream.
Chat Completions stream format
Each event is a data: line containing a JSON object. The stream ends with data: [DONE].
data: {"id":"gen-abc","object":"chat.completion.chunk","model":"openai/gpt-4.1-mini","choices":[{"index":0,"delta":{"role":"assistant","content":"","tool_calls":null},"finish_reason":null}],"usage":null}
data: {"id":"gen-abc","object":"chat.completion.chunk","model":"openai/gpt-4.1-mini","choices":[{"index":0,"delta":{"role":null,"content":"Lines","tool_calls":null},"finish_reason":null}],"usage":null}
data: {"id":"gen-abc","object":"chat.completion.chunk","model":"openai/gpt-4.1-mini","choices":[{"index":0,"delta":{"role":null,"content":" of code","tool_calls":null},"finish_reason":null}],"usage":null}
data: {"id":"gen-abc","object":"chat.completion.chunk","model":"openai/gpt-4.1-mini","choices":[{"index":0,"delta":{"role":null,"content":null,"tool_calls":null},"finish_reason":"stop"}],"usage":null}
data: {"id":"gen-abc","object":"chat.completion.chunk","model":"openai/gpt-4.1-mini","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":12,"total_tokens":26}}
data: [DONE]
Every chunk has id, object, model, choices, and usage keys. Unused fields are null rather than omitted. Chunks have no created field. The model in chunks is the name reported by the provider, which can differ from the model ID you sent. On Bedrock, id is an empty string.
Each delta carries role, content, and tool_calls. Reasoning text and log probabilities are not streamed. Tool-call deltas are streamed for OpenAI-compatible providers (OpenRouter, OpenAI, CheaperInference, DeepInfra, Novita, Parasail, Relace, Together AI), but not for Anthropic or Bedrock, whose streams carry text only. Use a non-streaming request when you need tool calls from those providers.
Token usage is always reported near the end of the stream, whatever you set in stream_options. Most providers send it in a usage-only chunk where choices is an empty array ([]). Anthropic sends it on the chunk that carries finish_reason. Client code must not assume choices[0] exists on every SSE event. The usage object may contain additional keys; rely only on the token counts.
Streams do not report credits: there is no credits_used field in streamed usage. Credits are computed after the stream ends and recorded with the request.
Responses stream format
The Responses endpoint uses typed events with event: and data: lines:
event: response.created
data: {"id":"resp-abc","object":"response","status":"in_progress","model":"openai/gpt-4.1-mini","output":[]}
event: response.in_progress
data: {"id":"resp-abc","object":"response","status":"in_progress"}
event: response.output_item.added
data: {"type":"message","id":"msg-001","role":"assistant","content":[]}
event: response.content_part.added
data: {"type":"output_text","text":""}
event: response.output_text.delta
data: {"type":"output_text","delta":"Lines"}
event: response.output_text.delta
data: {"type":"output_text","delta":" of code"}
event: response.output_text.done
data: {"type":"output_text","text":"Lines of code flow..."}
event: response.content_part.done
data: {"type":"output_text","text":"Lines of code flow..."}
event: response.output_item.done
data: {"type":"message","id":"msg-001","role":"assistant","content":[...]}
event: response.completed
data: {"id":"resp-abc","object":"response","status":"completed","output":[...],"usage":{"input_tokens":14,"output_tokens":12,"credits_used":200}}
data: [DONE]
Each event includes a sequence_number that increases monotonically.
Errors during a stream
A provider failure is reported one of two ways, depending on whether anything has been sent yet.
Before the first chunk, the router holds the response for up to 20 seconds. A failure in that time gets the same status code and JSON error body as the same request without stream, for example 502 provider_error or 400 context_length_exceeded. Past 20 seconds the headers go out and the stream starts, so a slow first token (long reasoning) never holds them.
After the first chunk, the 200 has already been sent, so the stream ends with one error event.
On Chat Completions, the error line carries the same body as a JSON error response, with code as a string, and is followed by [DONE]:
data: {"error": {"message": "The upstream provider returned an error", "type": "server_error", "param": null, "code": "provider_error", "request_id": "4bf92f3577b34da6a3ce929d0e0e4736"}}
data: [DONE]
On Responses, the stream ends with OpenAI’s error event and no [DONE]. code is the error code. The event has no request_id: read it from the x-request-id header.
event: error
data: {"type": "error", "code": "provider_error", "message": "The upstream provider returned an error", "param": null}
code takes the same values as in a JSON error, such as provider_error, upstream_timeout, or rate_limit_exceeded. See the Error reference for each. Treat either event as a failed request: discard the partial output, or keep it and show the response as incomplete. The OpenAI SDKs raise an APIError on the Chat Completions error line, and hand you the Responses one as an event whose type is "error".
Consuming streams
Python (OpenAI SDK)
from openai import OpenAI
client = OpenAI(
api_key="sk-quantized-YOUR-KEY",
base_url="https://api.quantized.us/v1",
)
stream = client.chat.completions.create(
model="openai/gpt-4.1-mini",
messages=[{"role": "user", "content": "Write a haiku about code."}],
stream=True,
)
for chunk in stream:
# Usage-only chunks often have `choices: []`; never index `[0]` blindly.
if not chunk.choices:
continue
delta = chunk.choices[0].delta
if delta and delta.content:
print(delta.content, end="", flush=True)
print()
Python (httpx, raw SSE)
import httpx
with httpx.stream(
"POST",
"https://api.quantized.us/v1/chat/completions",
headers={"Authorization": "Bearer sk-quantized-YOUR-KEY"},
json={
"model": "openai/gpt-4.1-mini",
"messages": [{"role": "user", "content": "Write a haiku about code."}],
"stream": True,
},
) as response:
for line in response.iter_lines():
if line.startswith("data: ") and line != "data: [DONE]":
import json
chunk = json.loads(line[6:])
if "error" in chunk:
# The stream failed after it started; see "Errors during a stream".
raise RuntimeError(f"{chunk['error']['code']}: {chunk['error']['message']}")
choices = chunk.get("choices") or []
if not choices:
continue
delta = choices[0].get("delta") or {}
content = delta.get("content") or ""
if content:
print(content, end="", flush=True)
print()
JavaScript
const response = await fetch('https://api.quantized.us/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer sk-quantized-YOUR-KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai/gpt-4.1-mini',
messages: [{ role: 'user', content: 'Write a haiku about code.' }],
stream: true,
}),
});
if (!response.ok) {
// Errors before the stream starts come back as a normal JSON body.
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let output = '';
outer: while (true) {
const { done, value } = await reader.read();
if (done) break;
// A network read can end mid-event, so buffer until a blank line closes the event.
buffer += decoder.decode(value, { stream: true });
const events = buffer.split('\n\n');
buffer = events.pop();
for (const event of events) {
for (const line of event.split('\n')) {
if (!line.startsWith('data: ')) continue;
const data = line.slice('data: '.length);
if (data === '[DONE]') break outer;
const chunk = JSON.parse(data);
// The stream failed after it started; see "Errors during a stream".
if (chunk.error) throw new Error(`${chunk.error.code}: ${chunk.error.message}`);
// Usage-only chunks have `choices: []`.
const content = chunk.choices?.[0]?.delta?.content;
if (content) output += content;
}
}
}
console.log(output);