Building
Streaming responses
Stream tokens as they are generated with Python, TypeScript and curl, and forward the stream to a browser from a Next.js route.
7 min read · Updated November 1, 2026
Without streaming, your app waits for the full response before showing anything, which can take many seconds for long answers. With streaming, tokens arrive as they are generated, so users see output almost immediately. Every chat model on AILabStore supports streaming through the standard stream: true parameter.
How streaming works
When you set stream: true, the API responds with server-sent events (SSE). Each event contains a small JSON chunk with the next piece of text in choices[0].delta.content. The stream ends with a final data: [DONE] line.
curl
Use -N to disable buffering so you can watch tokens arrive:
curl -N https://api.ailabstore.cc/v1/chat/completions \
-H "Authorization: Bearer $AILABSTORE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-5.5",
"stream": true,
"messages": [{"role": "user", "content": "Write a short poem about latency."}]
}'
You will see lines like:
data: {"id":"...","choices":[{"index":0,"delta":{"content":"Packets"}}]}
data: {"id":"...","choices":[{"index":0,"delta":{"content":" race"}}]}
data: [DONE]
Python
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.ailabstore.cc/v1", api_key=os.environ["AILABSTORE_API_KEY"])
stream = client.chat.completions.create(
model="anthropic/claude-sonnet-5.5",
stream=True,
messages=[{"role": "user", "content": "Explain HTTP/2 multiplexing in one paragraph."}],
)
full = []
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta.content or ""
print(delta, end="", flush=True)
full.append(delta)
print()
answer = "".join(full)
Async Python
import asyncio
from openai import AsyncOpenAI
aclient = AsyncOpenAI(base_url="https://api.ailabstore.cc/v1", api_key=os.environ["AILABSTORE_API_KEY"])
async def main():
stream = await aclient.chat.completions.create(
model="openai/gpt-5-mini",
stream=True,
messages=[{"role": "user", "content": "List three uses of WebSockets."}],
)
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
asyncio.run(main())
TypeScript
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.ailabstore.cc/v1",
apiKey: process.env.AILABSTORE_API_KEY,
});
const stream = await client.chat.completions.create({
model: "anthropic/claude-sonnet-5.5",
stream: true,
messages: [{ role: "user", content: "Explain HTTP/2 multiplexing in one paragraph." }],
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
Getting token usage while streaming
Usage is not included in streamed chunks by default. Ask for it with stream_options, and it arrives in a final chunk with an empty choices array:
stream = client.chat.completions.create(
model="anthropic/claude-haiku-5.5",
stream=True,
stream_options={"include_usage": True},
messages=[{"role": "user", "content": "Hi"}],
)
for chunk in stream:
if chunk.usage:
print("\nTokens:", chunk.usage.total_tokens)
elif chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
Streaming to the browser with Next.js
Never call AILabStore directly from the browser, because that would expose your key. Instead, stream through your own server route and forward plain text to the client:
// app/api/chat/route.ts
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.ailabstore.cc/v1",
apiKey: process.env.AILABSTORE_API_KEY,
});
export async function POST(req: Request) {
const { messages } = await req.json();
const stream = await client.chat.completions.create({
model: "anthropic/claude-sonnet-5.5",
stream: true,
max_tokens: 1000,
messages,
});
const encoder = new TextEncoder();
const body = new ReadableStream({
async start(controller) {
try {
for await (const chunk of stream) {
const text = chunk.choices[0]?.delta?.content;
if (text) controller.enqueue(encoder.encode(text));
}
} finally {
controller.close();
}
},
cancel() {
stream.controller.abort(); // stop generation if the user navigates away
},
});
return new Response(body, { headers: { "Content-Type": "text/plain; charset=utf-8" } });
}
And read it in a client component:
async function send(messages: { role: string; content: string }[], onText: (t: string) => void) {
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages }),
});
const reader = res.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
onText(decoder.decode(value, { stream: true }));
}
}
If you use the Vercel AI SDK, its streamText helper and useChat hook handle this plumbing for you; configure its OpenAI provider with the AILabStore base URL.
Cancelling a stream
Stopping early saves output tokens. In Python, break out of the loop and close the stream:
for chunk in stream:
text = (chunk.choices[0].delta.content or "") if chunk.choices else ""
if "STOP" in text:
stream.close()
break
In TypeScript, call stream.controller.abort().
Streaming with tool calls
When the model calls tools during a stream, arguments arrive in pieces under delta.tool_calls. Accumulate them by index and parse the JSON only after the stream finishes:
calls: dict[int, dict] = {}
for chunk in stream:
if not chunk.choices:
continue
for tc in chunk.choices[0].delta.tool_calls or []:
c = calls.setdefault(tc.index, {"name": "", "arguments": ""})
if tc.function.name:
c["name"] = tc.function.name
if tc.function.arguments:
c["arguments"] += tc.function.arguments
Tips
- Proxies and buffering: some reverse proxies buffer responses. Disable buffering for streaming routes (for nginx,
proxy_buffering off;or theX-Accel-Buffering: noheader). - Timeouts: streaming keeps connections open longer. Make sure your hosting platform's request timeout is long enough.
- Errors mid-stream: a stream can end early because of network problems. Show what arrived, and offer a retry.
- Rendering Markdown: re-render the accumulated text on each chunk, throttled to every 50 to 100 ms for smooth UI.