Skip to content

Stream a response

Read text as it arrives and handle interruptions explicitly.

Enable streaming

Set stream to true on a chat-completions request. Router sends ordered server-sent events containing content deltas, followed by a final finish reason, usage, and [DONE].

python
import osfrom openai import OpenAI
client = OpenAI(    base_url=os.environ["ROUTER_BASE_URL"],    api_key=os.environ["ROUTER_API_KEY"],)
stream = client.chat.completions.create(    model="gemma3:1b",    messages=[{"role": "user", "content": "Hello!"}],    stream=True,)
for chunk in stream:    if chunk.choices:        print(chunk.choices[0].delta.content or "", end="")

Handle completion and failure

An opened connection is not a completed answer. Track content as it arrives and distinguish a finished response from a failed or interrupted stream.

Stop a request

Close or abort the client request when the user stops generation. Release your stream reader and show a stopped state. Keep cancellation and request errors distinct in your interface.

See errors and limits for recovery guidance.