Back to Docs

Streaming

Receive responses token by token in real-time using server-sent events (SSE).

How it works

1

Send "stream": true in your request body.

2

The server responds with Content-Type: text/event-stream.

3

Each chunk contains a JSON object with delta.content that accumulates to form the full response.

4

When finished, you receive a chunk with finish_reason: "stop" followed by "data: [DONE]".

Request

bash
curl https://api.ai.tryflama.com/v1/chat/completions \
  -H "Authorization: Bearer $KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-max",
    "messages": [{"role": "user", "content": "Write a haiku about coding."}],
    "stream": true
  }'

Response format

Each line starts with "data: " followed by a JSON object. The last line is "data: [DONE]".

text
data: {"id":"chatcmpl-abc","choices":[{"delta":{"role":"assistant"},"index":0}]}

data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":"Rustic"},"index":0}]}

data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":" keyboards"},"index":0}]}

data: {"id":"chatcmpl-abc","choices":[{"delta":{"content":" click"},"index":0}]}

data: {"id":"chatcmpl-abc","choices":[{"delta":{},"finish_reason":"stop","index":0}]}

data: [DONE]

The first chunk contains the role, intermediate chunks contain delta.content with partial tokens, and the last chunk contains finish_reason.

Client examples

Python

python
import openai

client = openai.OpenAI(
    base_url="https://api.ai.tryflama.com/v1",
    api_key="tf_sk_..."
)

stream = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[{"role": "user", "content": "Write a haiku about coding."}],
    stream=True
)

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

TypeScript

typescript
import OpenAI from "openai";

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

const stream = await client.chat.completions.create({
  model: "qwen3.8-max",
  messages: [{ role: "user", content: "Write a haiku about coding." }],
  stream: true,
});

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

Tips

The OpenAI SDKs handle streaming automatically when you pass stream=True.

Streaming reduces perceived latency because the user sees tokens appear in real-time.

If the model is busy, streaming may take longer to start. Handle timeouts in your client.