Skip to content
smol.Docs

    Open console

    Stream an answer

    Parse chat-completion server-sent events, measure the first visible text, and distinguish a completed stream from an interruption.

    Use the same generation request and headers, with "stream": true. A successful HTTP handshake returns Content-Type: text/event-stream. An HTTP error before streaming generally uses JSON instead. Keep the X-Smol-Request-Id header when supplied.

    An SSE event ends with a blank line. A TCP or HTTP chunk can contain half an event or several events. Read UTF-8 lines and dispatch events, not transport chunks. An abbreviated successful exchange looks like this:

    data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
    data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Consistent terminology."},"finish_reason":null}]}
    data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
    data: {"object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":24,"completion_tokens":4,"total_tokens":28}}
    data: [DONE]
    • Append nonempty choices[].delta.content to the visible answer. A role announcement, empty delta or usage-only event is not a first token.
    • Record the non-null finish_reason (stop, length or content_filter). A length limit is different from an ordinary stop. A usage chunk may have an empty choices array. Do not invent zero usage when it is missing.
    • The success terminal marker is data: [DONE] followed by the event separator after a finish reason. A terminal data: {"error":{"code":"…"}} is a failure, even after HTTP 200 or some text. EOF or disconnect without a confirmed terminal outcome is not a successful generation.

    This reader accepts an open binary response such as http.client.HTTPResponse from the Python example. Set stream to True in that example and, after confirming HTTP 200 and a text/event-stream content type, replace the JSON read with for text in read_text(response): print(text, end="", flush=True). It surfaces failures; it never reconnects or replays a generation.

    import io
    import json
    def read_text(binary_response):
    fields = []
    finished = False
    with io.TextIOWrapper(binary_response, encoding="utf-8", newline=None) as lines:
    for line in lines:
    line = line.removesuffix("\n")
    if line:
    name, separator, value = line.partition(":")
    if name == "data":
    fields.append(value.removeprefix(" ") if separator else "")
    continue
    if not fields:
    continue
    data = "\n".join(fields)
    fields.clear()
    if data == "[DONE]":
    if not finished:
    raise RuntimeError("Stream ended without a finish reason")
    return
    value = json.loads(data)
    if "error" in value:
    raise RuntimeError("Stream failed: " + value["error"]["code"])
    for choice in value["choices"]:
    if finished:
    raise RuntimeError("Unexpected choice after finish")
    text = choice.get("delta", {}).get("content")
    if text:
    yield text
    reason = choice.get("finish_reason")
    if reason is not None:
    if reason not in {"stop", "length", "content_filter"}:
    raise RuntimeError("Unrecognized finish reason")
    finished = True
    raise RuntimeError("Stream ended before [DONE]; inspect the request, do not replay")

    Measure what the user feels. Start a monotonic timer immediately before sending; stop the first-text timer on the first nonempty visible content, not the first response byte. Measure full completion separately. Closing the stream stops local consumption; it does not prove the provider stopped work or that the call is unbillable. Inspect an interrupted request.