Skip to content

Streaming responses

Consume partial Chat Completions output as it arrives.

Updated View as Markdown

Streaming reduces the time before a user sees the first output. Set stream: true on a compatible request and process each event until the stream ends.

JavaScript

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.SYNUX_API_KEY,
  baseURL: "https://api.synux.ai/v1",
});

const stream = await client.chat.completions.create({
  model: "your-model-id",
  messages: [{ role: "user", content: "Write a two-line welcome message." }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

Python

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["SYNUX_API_KEY"],
    base_url="https://api.synux.ai/v1",
)

stream = client.chat.completions.create(
    model="your-model-id",
    messages=[
        {"role": "user", "content": "Write a two-line welcome message."}
    ],
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)

cURL and server-sent events

curl --no-buffer "https://api.synux.ai/v1/chat/completions" \
  --header "Authorization: Bearer ${SYNUX_API_KEY}" \
  --header "Content-Type: application/json" \
  --data '{
    "model": "your-model-id",
    "messages": [{ "role": "user", "content": "Say hello." }],
    "stream": true
  }'

The HTTP response uses server-sent events. Each data: event contains a JSON chunk; the stream finishes with data: [DONE] for Chat Completions.

Handle interruptions

  • Set a request timeout that fits the workload and model.
  • Stop reading when the downstream client disconnects.
  • Preserve output only after your application validates each chunk.
  • Record the response X-Request-Id when diagnosing a failed request.
  • Do not blindly replay a stream after output has started; the original request may already have consumed tokens and produced user-visible output.

For retryable failures before output begins, use bounded exponential backoff with jitter. See Errors and retries.

Navigation

Type to search…

↑↓ navigate↵ selectEsc close