Streaming SSE: receive tokens live
By default the API returns the whole answer at once. With
stream: true, tokens arrive as they are produced — same
endpoint, same contract, same per-token billing, same OpenAI compatibility.
Why stream
The model starts answering before it has finished.
An 800-token generation can take several seconds. Without streaming the client waits for the last token before showing anything; with streaming the first token appears as soon as it exists. Perceived latency becomes the time to first token (TTFT), not total duration. That is what makes a chat interface usable and lets an agent show its steps.
Streaming does not reduce cost: billing is still per token, input and output, identical in block or stream mode. It only changes how you consume the response.
Enable streaming
Three clients, one parameter.
Add stream: true to the request body on
POST /v1/chat/completions:
curl https://api.effrenus.com/v1/chat/completions \
-H "Authorization: Bearer $EF_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "dolphin-3.0-llama3.1-8b",
"messages": [{"role": "user", "content": "Explain streaming in two sentences."}],
"stream": true
}'
from openai import OpenAI
client = OpenAI(base_url="https://api.effrenus.com/v1", api_key="sk-ef-...")
stream = client.chat.completions.create(
model="dolphin-3.0-llama3.1-8b",
messages=[{"role": "user", "content": "Hello"}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content if chunk.choices else None
if delta:
print(delta, end="", flush=True)
const res = await fetch("https://api.effrenus.com/v1/chat/completions", {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${process.env.EF_KEY}`,
},
body: JSON.stringify({
model: "dolphin-3.0-llama3.1-8b",
messages: [{ role: "user", content: "Hello" }],
stream: true,
}),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
if (!line.startsWith("data:")) continue;
const payload = line.slice(5).trim();
if (payload === "[DONE]") break;
const chunk = JSON.parse(payload);
const delta = chunk.choices?.[0]?.delta?.content;
if (delta) process.stdout.write(delta);
}
}
Read the events
SSE: one data: line per event, a blank line as separator.
The response is a text/event-stream flow. Each event carries a
JSON object that looks like a truncated chat completion:
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","model":"dolphin-3.0-llama3.1-8b","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","model":"dolphin-3.0-llama3.1-8b","choices":[{"index":0,"delta":{"content":"Hel"},"finish_reason":null}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","model":"dolphin-3.0-llama3.1-8b","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}]}
data: {"id":"chatcmpl-...","object":"chat.completion.chunk","model":"dolphin-3.0-llama3.1-8b","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
delta.contentholds the generated text; the first event usually carriesdelta.role = "assistant".finish_reasonisstop,lengthortool_calls; it is the logical end, before[DONE].- The
data: [DONE]marker ends the stream: do not parse it as JSON. - The model name is rewritten to the one you requested, even when a
fallback model served the request (
x-ef-served-byheader).
Usage and billing
The exact cost is known only at the end of the stream.
A streamed request is billed like a normal one: input tokens plus output
tokens at the model price. The balance is reserved before the upstream call;
the exact debit is applied when the stream ends. The
x-ef-cost-micro and x-ef-balance-micro headers are
therefore only present on non-streaming responses, or in the console and
exports.
To receive the exact usage client-side, ask for the usage chunk:
{
"model": "dolphin-3.0-llama3.1-8b",
"messages": [{"role": "user", "content": "Hello"}],
"stream": true,
"stream_options": {"include_usage": true}
}
Without stream_options.include_usage the final
usage chunk is filtered out; with it, it arrives last with
prompt_tokens and completion_tokens. The gateway
always asks the backend for that chunk: the option changes what the client
sees, not the bill.
Errors and interruption
Once the stream has started, the HTTP status can no longer change.
- Before the stream (401, 402, 403, 404, 429): the response is a normal JSON error with the HTTP status. Handle it as in block mode.
- During the stream: if the backend fails, the gateway
sends a
data: {"error": {...}}event followed bydata: [DONE]. The status is already 200: detect theerrorobject and do not count the stream as successful. - Client disconnect: closing the connection interrupts generation on the backend. Tokens already produced are billed (estimated from the received text); the reservation is not fully released.
Best practices
- Use a long read timeout (60–120 s): long generations should not be cut by a classic inference timeout.
- Keep
X-Accel-Buffering: noat your reverse proxy (already sent by the gateway) and disable compression ontext/event-stream. - Use the OpenAI SDK instead of a hand-written parser: it handles events, the usage chunk and errors.
- In an agent, cap
max_tokensand plan cancellation: a forgotten stream keeps consuming tokens.
FAQ
Does streaming cost more?
No. The per-token price is identical to block mode and only produced tokens are billed. An interrupted generation only charges what was produced before the interruption.
Can I stream embeddings?
No. /v1/embeddings returns a vector, not a generation;
the stream parameter is ignored.
Going further
Ready to test a stream?
Create a key, top up €5 and stream your own prompt.