Updated
LLM API Streaming: How SSE Works and How to Debug It
LLM API streaming sends the reply as it is generated, using server-sent events, so users see text after a fraction of a second instead of waiting for the whole answer. This guide covers the wire format, working client code and how to debug a stream that stalls.

Key points
- Set stream: true and read lines starting with data: until the stream ends.
- Each chunk carries a small piece of text in choices[0].delta.content.
- Usage arrives at the end of the stream.
- A stream holds one concurrency slot until it finishes or you close it.
What SSE looks like on the wire
Server-sent events are plain HTTP. The server keeps the connection open and writes lines of text. Each event is one or more lines followed by a blank line, and chat APIs in the OpenAI format put a JSON object after data: . The stream finishes with a final marker line.
data: {"choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}
data: {"choices":[{"index":0,"delta":{"content":"Hel"}}]}
data: {"choices":[{"index":0,"delta":{"content":"lo"}}]}
data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
This is a trimmed illustration of the OpenAI-style format that this OpenAI-compatible API follows. Real chunks carry more fields, such as an ID and the model name. Your code should look only at the fields it needs: delta.content for text, delta.tool_calls for tool calls and finish_reason for the end.
See it with curl
The fastest way to understand streaming is to watch it. Use -N so curl does not buffer the output.
curl -N https://api.serverlessllmapi.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"stream": true,
"messages": [{"role": "user", "content": "Write two sentences about rivers."}]
}'
You should see lines appear one by one. If the whole output arrives at once after a delay, something between you and the server is buffering, which we cover in the debugging section. Get a key on the API key page if you do not have one yet. Run it twice, once with stream set to true and once without, and compare the time to the first visible text. That gap is the whole reason to stream: total generation time is similar, but the perceived wait drops from the full reply to the first few tokens. For a long answer of several hundred tokens, the difference is obvious on screen.
Read a stream in Python
The official OpenAI SDK handles parsing for you. Use the stream as a context manager so the connection closes even if your code raises an error.
from openai import OpenAI
client = OpenAI(base_url="https://api.serverlessllmapi.com/v1", api_key="sk-your-key")
text, usage = [], None
with client.chat.completions.create(
model="uncensored",
stream=True,
messages=[{"role": "user", "content": "Write two sentences about rivers."}],
) as stream:
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
piece = chunk.choices[0].delta.content
text.append(piece)
print(piece, end="", flush=True)
if getattr(chunk, "usage", None):
usage = chunk.usage
print()
print("usage:", usage)
Streaming responses end with usage information, so keep the last non-empty value and log it after the loop. That is where you get token counts for billing and cost tracking. Note the guard chunk.choices and ...: a chunk may arrive with an empty choices list.
Read a stream in Node
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.serverlessllmapi.com/v1",
apiKey: process.env.API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
stream: true,
messages: [{ role: "user", content: "Write two sentences about rivers." }],
});
for await (const chunk of stream) {
const piece = chunk.choices[0]?.delta?.content;
if (piece) process.stdout.write(piece);
}
If you forward the stream to a browser, relay it as text/event-stream from your own server, and do not expose the API key to the browser. Set Cache-Control: no-cache on your response and flush after each write.
Without an SDK
If you parse by hand, split on newlines, ignore lines that do not start with data: , stop at data: [DONE], and parse the rest as JSON. Network packets do not respect line boundaries, so keep a buffer and process only complete lines.
Tool calls inside a stream
Tool calling works with streaming. The function name and arguments arrive in pieces in delta.tool_calls, and the argument string is incomplete until the last piece. Append the fragments by index, then parse the JSON once finish_reason says the model stopped to call a tool. Parsing early is the most common bug, and it throws a JSON error on half a string. A simple structure is a dictionary keyed by the tool call index, where each fragment of the name or arguments is appended to the entry for its index. When the stream ends, loop over the dictionary, parse each arguments string, run the functions, and make a second request with the results. If you stream text to a user while also allowing tool calls, buffer the text separately so a half-formed call never reaches the screen. Send each result back as a message with role: "tool". The docs have the full message flow.
Debugging stalls and broken streams
| Symptom | Likely cause | What to do |
|---|---|---|
| Text arrives all at once at the end | A proxy or server buffers the response | For nginx, turn off proxy_buffering for that route; check CDN and framework settings |
| Stream stops with no error | A client or proxy timeout | Raise read timeouts; log the last chunk and its time |
| 429 on the next request | An earlier stream still holds a concurrency slot | Close streams on cancel; use a context manager or abort signal |
429 with concurrency | More simultaneous requests than the key allows | 8 on a full key, 2 on a trial key; queue the rest |
429 with Retry-After: 5 | Temporary overload | Wait five seconds, then retry |
| JSON error while parsing | Partial line or partial tool arguments | Buffer until a full line or the final chunk |
For intermittent problems, log the X-Request-Id response header with every call. It identifies the request if you need to ask for help. The X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency headers show your limits.
A habit that saves hours: reproduce the problem with curl -N against the API first. If curl streams smoothly, the API is fine and the fault is in your server, proxy or client. If curl also stalls, note the request ID and the time of the last chunk.
Cancelling and costs
When a user presses stop, close the connection. In the Python SDK, leaving the with block does this, and in Node you can pass an abort signal or call stream.controller.abort(). Closing frees the concurrency slot, which matters because a streamed request occupies one until the stream ends. A full key has 8 slots, so eight stuck streams will block all other traffic.
Billing follows tokens. At $0.15 per 1M input tokens and $0.50 per 1M output tokens, a streamed answer of 400 tokens to a 1,500-token prompt costs 1,500 x 0.15 / 1,000,000 + 400 x 0.50 / 1,000,000 = $0.000225 + $0.0002 = $0.000425. Failed or refused requests are not charged. See pricing for top-ups. You can test everything above with the $0.50 trial credit, which is one click on the key page and lasts 7 days.
More guides
Questions and answers
Read the docsHow do I turn on streaming?
Add stream: true to the request body. The response then arrives as server-sent events instead of a single JSON object.
How do I get token usage from a stream?
Usage arrives at the end of the stream. Keep the last usage value you see and read it after the loop.
Why does my stream seem to hang?
Usually a proxy is buffering the response or a timeout is closing the connection. Test with curl -N directly against the API to separate your stack from the API.
Does streaming cost more than a normal request?
No. Billing is by input and output tokens either way.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.