News · November 17, 2026

Streaming SSE: receiving a response token by token

Enable stream:true, read the data: events up to [DONE], collect token counts with include_usage and pay only for what is produced.

· 4 min read · Effrenus Team · RSS

streamingsseapi

Generating several hundred tokens takes time. In block mode, the client waits for the whole response before displaying anything; in streaming mode, each fragment is pushed as soon as it is produced. Effrenus exposes that mode on POST /v1/chat/completions with the same contract as the OpenAI SDK: one parameter, stream: true, and the response becomes a text/event-stream flow.

One parameter, a different reading pace

Adding stream: true to the request body is enough. The server then returns a Server-Sent Events stream: a one-way HTTP channel where the server pushes events and the client simply reads. No WebSocket and no dedicated library: a long-lived HTTP connection is enough.

The price does not change: billing stays per token, input and output, identically in block mode and in streaming. What changes is perceived latency, which becomes time to first token rather than total generation time. That is what makes a chat interface usable and lets an agent display its steps as they happen.

The stream_options parameter goes with the stream. With {"include_usage": true}, the last event carries the token counters; without it, that technical chunk is filtered out by the gateway. The OpenAI SDK handles it if you pass the option:

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": "Explain SSE in three sentences."}],
    stream=True,
    extra_body={"stream_options": {"include_usage": True}},
)

for chunk in stream:
    if chunk.usage:                     # last event, empty choices
        print(chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
        continue
    if chunk.choices:
        delta = chunk.choices[0].delta.content
        if delta:
            print(delta, end="", flush=True)

Reading events without breaking the stream

Each event starts with a data: line and ends with a double newline. The content is a JSON object of type chat.completion.chunk: the text arrives in choices[0].delta.content, and the first event usually carries delta.role equal to assistant. Tool calls follow the same channel, in delta.tool_calls, with the usual OpenAI format.

The logical end signal is finish_reason, which is stop, length or tool_calls. It precedes a final data: [DONE] event, which must not be parsed as JSON: it is a termination marker. If you write your own parser, accumulate the bytes received and split on the double newline: an event can arrive split between two network reads.

The model name is rewritten in the chunks to match the one you requested, even if an equivalent model served the request. The x-ef-served-by response header then indicates the model actually used, and x-ef-request-id lets you find the request in the console.

Usage, billing and interruption

The balance is reserved before the call, and the exact debit is applied at the end of the stream. The cost is therefore known only after the last line. The x-ef-cost-micro and x-ef-balance-micro headers, present on a non-streamed response, are absent from a stream: the balance is read in the console or in the exports.

That is the purpose of stream_options.include_usage. The gateway systematically requests the usage chunk from the backend; the option therefore changes nothing about the bill, only what the client sees. With it, the last event carries prompt_tokens and completion_tokens, which lets you keep a local counter without calling the account API.

A stream that has started can no longer return an HTTP error code. Before the first byte, a 401, 402, 403, 404 or 429 arrives as classic JSON, with the corresponding HTTP code: handle it as in block mode. During the stream, a backend failure produces a data: {"error": {...}} event followed by [DONE]; the status is already 200, so test for the presence of the error key before considering the response successful.

Closing the connection interrupts the generation on the backend side. Tokens already produced are billed, estimated from the text received: the balance is not returned in full. A forgotten stream therefore keeps consuming tokens, which argues for a max_tokens ceiling and explicit cancellation in agents.

Best practices

  • Set a long read timeout, 60 to 120 seconds: cutting a long generation on the client side amounts to paying for it without reading it.
  • The gateway sends X-Accel-Buffering: no. Keep that setting behind a reverse proxy and disable compression on text/event-stream, otherwise events pile up in a buffer.
  • Cap max_tokens and plan for cancellation: a forgotten stream keeps consuming tokens.
  • Streaming does not apply to embeddings: /v1/embeddings returns a vector and ignores the stream parameter.

Block mode remains relevant for a one-off script or batch processing; streaming is useful when a person or an agent is waiting for the response. Per-token prices are published on the Pricing page, models and their capabilities in the catalogue, event details in the documentation and rate limits in the FAQ.

Read next

From reading to API calls

Create a key, top up from €5 and test the catalogue.

Create API key

← All news