Streaming Synth 2.5 in Production: Cut-Off Replies, Mid-Stream Errors and the 60-Second Idle Limit
A streaming demo takes ten lines. The production version has to tell a finished reply from a broken one, stop paying when the user leaves, and survive a quiet minute. We ran the platform's gateway code against a model server that fails on purpose. This is what your client sees, and code that handles it.
Short answer: a streamed reply is complete only if you saw finish_reason: "stop". A clean [DONE] is not proof, and a mid-stream failure still has HTTP status 200. The gateway drops a connection that carries no data for 60 seconds, so stream anything that might take that long, and turn off SDK retries on long calls: in our test, a timed-out request retried by SDK defaults was billed three times and returned nothing. Set max_tokens on every call, and abort the upstream request when the user leaves.
Six ways a stream can end
Send "stream": true and the platform answers with server-sent events: data: lines holding chat.completion.chunk objects, then data: [DONE]. What matters is how it ends:
| What you see | What happened | What to do |
|---|---|---|
| finish_reason "stop", then [DONE] | The model finished | Save it. |
| finish_reason "length", then [DONE] | It hit max_tokens or the context window | Keep it and offer to continue. |
| [DONE] with no finish_reason | The model server closed early; the gateway still closed the stream cleanly | Treat as cut off. |
| A data line with an error object | The model server failed mid-reply. The HTTP status was already 200 | Treat as cut off. |
| Connection drops, no [DONE] | Network, a proxy, or the 60-second idle cut | Treat as cut off. |
| JSON body with a 4xx or 5xx status | It failed before the first byte | Use your normal retry rules. |
Rows three and four are the easy ones to miss. In row three nothing looks wrong: your loop exits normally, and if you asked for usage you even get token counts. Only the missing finish_reason gives it away. In row four the status code you logged says 200, and the error exists only inside the stream. The OpenAI SDKs turn it into an APIError with no HTTP status, so an error handler that switches on err.status misses it.
Automatic fallback doesn't help here. A request for synth-2.5-pro can fall back to synth-2.5-flash before the first byte; after that, the reply can't change models. Every chunk's model field names the one that answered.
The 60-second idle limit
The gateway closes any connection that has had no data for 60 seconds. For a stream that is rarely a problem, because tokens keep arriving. For a normal, non-streamed request it is a hard limit: nothing is sent until the whole reply is ready. In our test, a 50-second reply came back fine, and a longer one lost its connection at 60.0 seconds.
The lost connection isn't the expensive part. The model server kept generating, and the request was billed when it finished. The OpenAI Node SDK also retries a dropped connection twice by default. With default settings, one slow request became three upstream generations, three charges and a Connection error after 181 seconds. So:
- Stream long replies, even in background jobs. Collect the chunks and use the text at the end. You don't need a user watching to benefit from streaming.
- Set
maxRetries: 0on generation calls and retry deliberately, where you can see it and count it.max_retries=0in Python. - Set the SDK timeout under 60 seconds. The Node SDK's default is 10 minutes, so it won't help you here. A 55-second timeout gives you a clear timeout error instead of an unexplained disconnect.
- Cap
max_tokens. A shorter reply is also a faster one.
The first token counts too. If the model server takes a full minute to start, the stream is dropped like any other silent connection. Very long prompts make that more likely; the context window guide covers trimming them.
Check the proxies on your side as well. nginx's proxy_read_timeout is 60 seconds between reads by default, and proxy_buffering is on, which can hold back your stream and deliver it in one lump. The platform sends X-Accel-Buffering: no on its own streams, but that doesn't cover nginx in front of your app. Your relay has to send it too.
What a cancel costs
When you close the connection mid-stream, the gateway stops reading from the model server and bills the input plus the output delivered so far. In our test, cancelling a 100-chunk reply after one second stopped it at chunk 20, and only those 20 were billed.
Before the first token it works differently. If the model server hasn't started its response when you disconnect, the request can run to the end and be billed in full. In our test it did. Two habits keep that small:
- Always send
max_tokens. It caps the output a late cancel can cost. 800 output tokens on Synth 2.5 Pro is $0.00016 at $0.20 per million. - Debounce the send button. A user who sends, stops and resends three times can pay for three replies. Disable sending until the first token or an error arrives.
A cancelled stream never delivers its usage chunk, so your own log has to estimate. The per-customer cost tracking guide has that code. Remember that a Pro request uses one of the model's 5 shared requests per minute when it starts, cancelled or not.
A backend relay that gets the ending right
Your browser code should never call the platform directly, because the API key would be visible to every visitor (see our API key guide). It calls your backend, which holds the key and passes the text along. This handler uses web-standard Request and Response, so it fits Next.js route handlers, Hono, Bun and Deno:
// app/api/chat/route.js (web-standard handler: Next.js, Hono, Bun, Deno)
import OpenAI from 'openai'
const synth = new OpenAI({
baseURL: 'https://platform.lucidity.sh/v1',
apiKey: process.env.LUCIDITY_API_KEY,
maxRetries: 0, // a silent retry is a second bill
timeout: 55_000, // give up before the gateway's 60-second idle cut
})
export async function POST(request) {
const { messages } = await request.json() // authenticate, validate and trim in real code
const upstream = new AbortController()
request.signal.addEventListener('abort', () => upstream.abort())
let stream
try {
stream = await synth.chat.completions.create({
model: 'synth-2.5-pro',
messages,
max_tokens: 800, // also caps what a late cancel can cost
stream: true,
stream_options: { include_usage: true },
}, { signal: upstream.signal })
} catch (err) { // failed before the first byte: a normal status code
return Response.json({ error: 'model_unavailable' }, { status: err.status ?? 502 })
}
const enc = new TextEncoder()
const body = new ReadableStream({
async start(out) {
const send = (event, data) => out.enqueue(enc.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`))
let finish = null, usage = null, model = null
try {
for await (const chunk of stream) {
model = chunk.model ?? model
usage = chunk.usage ?? usage
const choice = chunk.choices[0]
if (choice?.delta?.content) send('delta', choice.delta.content)
finish = choice?.finish_reason ?? finish
}
// [DONE] alone proves nothing. Only finish_reason says the reply is whole.
const status = { stop: 'complete', length: 'length' }[finish] ?? 'cut'
if (!upstream.signal.aborted) send('end', { status, model, usage })
} catch {
if (!upstream.signal.aborted) send('end', { status: 'cut', model, usage })
} finally {
try { out.close() } catch {} // already closed if the user left
}
},
cancel() { upstream.abort() }, // user closed the tab: stop paying
})
return new Response(body, { headers: {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
'X-Accel-Buffering': 'no', // tells nginx in front of your app not to buffer
} })
}Three choices in it are deliberate. It sends its own end event with a status, so the browser doesn't have to know the rules above. Failures before the first byte keep their real status code, so a 402 or 429 still looks like one. And it aborts the upstream call both when the request is aborted and when the response body is cancelled, because frameworks differ in which one they signal. When you abort, the SDK's loop ends without throwing; that is why the code checks upstream.signal.aborted before calling a reply cut off.
Reading the stream in the browser
The built-in EventSource accepts only a URL and a withCredentials option, so it can't POST a conversation. Use fetch and read the body:
export async function streamChat(messages, { onText, signal }) {
const res = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages }),
signal,
})
if (!res.ok) throw Object.assign(new Error('request failed'), { status: res.status })
const reader = res.body.getReader()
const decoder = new TextDecoder() // stream: true keeps split characters intact
let buffer = ''
for (;;) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
let cut
while ((cut = buffer.indexOf('\n\n')) !== -1) {
const frame = buffer.slice(0, cut)
buffer = buffer.slice(cut + 2)
const event = /^event: (.*)$/m.exec(frame)?.[1]
const data = JSON.parse(/^data: (.*)$/m.exec(frame)[1])
if (event === 'delta') onText(data)
if (event === 'end') return data // { status: 'complete' | 'length' | 'cut', ... }
}
}
return { status: 'cut' } // closed without an end event
}The buffer is the part people skip. Network chunks don't line up with events, so one read can hold half an event or three. Splitting on the blank line handles both, and decode(value, { stream: true }) keeps a multi-byte character that lands across two reads from turning into �. We tested this parser one byte at a time with accented and Chinese text. If you call the platform's stream with plain fetch on a server instead, the same buffering applies, with [DONE] as the last frame.
The same rules in Python
import os
from openai import OpenAI, APIError
client = OpenAI(base_url="https://platform.lucidity.sh/v1", api_key=os.environ["LUCIDITY_API_KEY"],
max_retries=0, timeout=55)
def stream_reply(messages):
text, finish, usage, model = [], None, None, None
try:
with client.chat.completions.create(
model="synth-2.5-pro", messages=messages, max_tokens=800,
stream=True, stream_options={"include_usage": True},
) as stream:
for chunk in stream:
model = chunk.model or model
usage = chunk.usage or usage
if chunk.choices:
c = chunk.choices[0]
text.append(c.delta.content or "")
finish = c.finish_reason or finish
except APIError as err:
if not text:
raise # failed before the first token: use your normal retry rules
return {"text": "".join(text), "status": "cut", "error": str(err), "model": model}
status = {"stop": "complete", "length": "length"}.get(finish, "cut")
return {"text": "".join(text), "status": status, "usage": usage, "model": model}The with block closes the connection if your code raises or returns early, which is what stops the billing. APIConnectionError and timeouts are subclasses of APIError, so one handler covers a dropped connection and an in-stream error.
What to do with a cut-off reply
You have already paid for the partial text, so decide by feature:
- Chat or drafting: keep the partial, mark it, and show Continue and Regenerate. Don't regenerate silently; the user watched those words appear.
- Continue: send the conversation again with the partial as an
assistantmessage and a short user instruction such as “Continue from where you stopped. Don't repeat anything.” You pay for the input again. Check the join for repeated words. - Anything a machine reads: discard it. A cut-off JSON object or a classification without its label is worse than an error. Retry once, buffered, with a smaller
max_tokens. - Saved content: store the status next to the text. A half-finished product description that gets published is the failure your customers will notice.
Log four fields per stream: status, served model, time to first token and characters delivered. A rising share of cut is an early sign of trouble, and an error log keyed on HTTP status won't show it.
Synth 2.5 streaming FAQ
How do I know a streamed Synth 2.5 reply is complete?
Check finish_reason. A value of stop means the model finished, and length means it ran out of max_tokens or context window. If the stream ends without any finish_reason, the reply was cut off, even when the stream closed cleanly with data: [DONE].
What happens if Synth 2.5 fails in the middle of a stream?
The HTTP status is already 200, so the error arrives as a data line with an error object, followed by [DONE]. The OpenAI SDKs for Python and Node raise an APIError with no HTTP status. The platform does not fall back to another model once bytes have been sent, and the tokens already delivered are billed.
Is there a timeout on LuciditySH Platform requests?
The gateway closes a connection that has had no data for 60 seconds. A non-streamed request sends nothing until the whole reply is ready, so a reply that takes longer than 60 seconds is lost. Stream long replies, so data keeps moving.
Am I billed if the user cancels a streamed reply?
You are billed for the input and for the output delivered up to the cancel. Cancelling before the first token is less certain: the model server can keep generating, and you can be billed for the full reply. Set max_tokens on every call to cap that cost.
Can I use EventSource to stream Synth 2.5 in the browser?
Not for this API. EventSource takes only a URL and a withCredentials option, so it cannot send a POST body or an Authorization header, and the API key must not be in the browser anyway. Call your own backend with fetch and read the response body as a stream.
How we tested
On November 23, 2026 we ran the gateway's streaming code with the timeouts set in its code, on a local machine, against a stand-in model server scripted to finish, stop early, crash, send an error, or wait. Clients were the OpenAI Node SDK 7.27.0 and the current OpenAI Python SDK. The stand-in isn't Synth, so nothing here measures model speed, and proxies between you and the platform can change how a dropped connection looks.
Sources
- openai-python streaming source (how an in-stream error becomes an APIError)
- openai-node README (two retries and a 10-minute timeout by default)
- MDN: Using server-sent events and the EventSource constructor
- nginx proxy module reference (proxy_read_timeout, proxy_buffering, X-Accel-Buffering)
- Fastify connectionTimeout and Node.js server.timeout (what an idle socket timeout does)
- LuciditySH Platform docs: streaming and automatic fallback (in the dashboard after sign-in)
Create an account and get an API key for Synth 2.5 Pro and Flash. Prepaid, per token, no monthly fee.
Create an account