Sub topic 14
Handling failures after the first token
This chapter assumes you can read Python and JavaScript, know how Server-Sent Events (SSE) frame a streamed LLM response, and have seen a client accumulate deltas into a message. It covers what goes wrong once text is already on the screen, and how to respond.
Why mid-stream failures are different
A non-streaming call either works or fails, and the status code tells you which. A streaming call sends its status line and headers first. Once the server has sent 200 OK, it cannot change that status. Any later failure has to be reported inside the stream, or by the connection closing.
The user has also already seen part of the answer. You now have to decide what to do with partial text, whether to retry, and what to record for billing.
Failures after the first token come in these forms:
- Error event in the stream. The provider sends an event such as an overloaded notice or an internal error, then closes. The shape varies by provider. Check your provider's documentation for the event name and payload.
- Dropped connection. A network reset, a proxy timeout, or a server restart ends the response early. The client sees an exception from the reader, or a clean end of stream with no terminal marker.
- Stall. The connection stays open but no bytes arrive.
- Abnormal finish reason. The stream ends normally but the finish reason is
length(token limit reached) or a content-filter value. The response is complete as a stream but incomplete as an answer. - Malformed data. A truncated event fails JSON parsing.
Define "complete" explicitly
A stream that merely stops is not a finished response. Treat a response as complete only when you have seen the terminal signal. That is a finish reason on the last choice, plus [DONE] or the provider's stop event if it sends one. If the iterator ends without it, raise an error and keep the partial text attached to it.
import json
class StreamInterrupted(Exception):
"""Raised when a stream ends without a clean finish."""
def __init__(self, partial_text, reason):
super().__init__(reason)
self.partial_text = partial_text
self.reason = reason
def collect(payloads):
parts = []
finish_reason = None
try:
for payload in payloads:
if payload == "[DONE]":
break
event = json.loads(payload)
if "error" in event:
message = event["error"].get("message", "error event")
raise StreamInterrupted("".join(parts), message)
choices = event.get("choices") or []
if not choices:
continue # e.g. a usage-only chunk
choice = choices[0]
piece = choice.get("delta", {}).get("content")
if piece:
parts.append(piece)
if choice.get("finish_reason"):
finish_reason = choice["finish_reason"]
except (ConnectionError, TimeoutError, ValueError) as exc:
# ValueError covers json.JSONDecodeError from a truncated event.
raise StreamInterrupted("".join(parts), type(exc).__name__) from exc
if finish_reason is None:
raise StreamInterrupted("".join(parts), "ended without finish reason")
return "".join(parts), finish_reason
def broken_stream():
yield '{"choices": [{"delta": {"content": "Hel"}}]}'
yield '{"choices": [{"delta": {"content": "lo, wor"}}]}'
raise ConnectionError("connection reset")
try:
collect(broken_stream())
except StreamInterrupted as err:
print(f"Interrupted ({err.reason}); kept: {err.partial_text!r}")Running this prints Interrupted (ConnectionError); kept: 'Hello, wor'. The partial text is preserved on the exception, so the caller can choose what to do with it.
Choosing a recovery strategy
Retrying before the first token is safe, because the user has seen nothing. After the first token, silent retries cause problems. The second attempt will usually produce different text, so replacing what the user already read is jarring. Appending to it duplicates content. Each attempt also costs tokens.
| Situation | Partial text | Reasonable action |
|---|---|---|
| Error before any text | None | Retry with backoff, as with a normal request |
| Drop or error event mid-answer | Some | Keep the text, mark it as interrupted, offer Retry |
| `finish_reason` is `length` | Full but truncated | Show a notice, raise the limit or offer Continue |
| Content-filter finish | Some | Show the provider's reason, do not retry unchanged |
| Stall with no bytes | Some | Abort after a timeout, then treat as a drop |
| Streamed tool call cut off | Partial arguments | Discard the arguments, never run the tool |
Two recovery styles exist. Regeneration starts over and replaces the whole message, and it is simple and always consistent. Continuation sends the partial text back as the start of the assistant turn and asks the model to carry on. It saves tokens, but not every API supports it, and the join can read awkwardly. Start with regeneration behind a button, and add continuation only if long answers justify it.
Tool calls need extra care. Partial argument JSON is not valid JSON, and a half-built call must never be executed. Run a tool only after the stream completes cleanly and the arguments parse.
Detecting stalls in the browser
A dropped connection raises an error, but a stall does not. Add an idle timer that resets on every chunk and aborts when it fires. Keep-alive comment lines arrive as bytes, so they reset the timer too.
async function readWithWatchdog(url, body, onText, idleMs = 30000) {
const controller = new AbortController();
let timedOut = false;
let timer;
const arm = () => {
clearTimeout(timer);
timer = setTimeout(() => {
timedOut = true;
controller.abort();
}, idleMs);
};
let received = "";
try {
arm();
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
signal: controller.signal,
});
if (!response.ok || !response.body) {
throw new Error(`Request failed with status ${response.status}`);
}
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
arm();
received += value;
onText(value);
}
return { ok: true, received };
} catch (err) {
const reason = timedOut ? "stalled" : err.name === "AbortError" ? "cancelled" : "network";
return { ok: false, reason, received };
} finally {
clearTimeout(timer);
}
}The catch block separates the three causes. A user pressing Stop is not an error and should not show a red banner. A stall or network failure should keep the text and show a Retry control.
Reporting errors through your own relay
If your backend relays the provider stream, it faces the same constraint. Once it has sent headers, it cannot return a 502. Catch upstream failures inside the generator and emit an explicit error event before closing, so the browser can tell a failure from a clean end.
import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def upstream_tokens():
yield "Partial"
yield " answer"
raise RuntimeError("upstream failed")
async def relay():
try:
async for token in upstream_tokens():
yield f"data: {json.dumps({'delta': token})}\n\n"
yield "data: [DONE]\n\n"
except Exception:
# Headers are already sent, so report the failure in-band.
payload = json.dumps({"message": "The model connection was interrupted."})
yield f"event: error\ndata: {payload}\n\n"
@app.get("/relay")
async def relay_endpoint():
return StreamingResponse(
relay(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)Send a safe, generic message to the browser and log the real exception on the server. Provider error text can leak internal details.
The client rule matches the Python parser above: treat [DONE] as the only success signal. If the stream closes without it, the response was cut off, even when the relay sent an error event.
Recording usage for failed streams
Usage totals normally arrive in the final chunk, which a failed stream never delivers. You may still be billed for the tokens generated. Log the request with an incomplete flag and an estimate based on the text received, and reconcile against the provider's billing dashboard.
Exercise
A stream delivers 200 tokens of text, then the connection closes cleanly with no error event, no finish reason, and no [DONE]. Should the client treat the response as complete? What should it show the user?
Show answer
No. A clean close is not proof of completion, because a proxy or server restart can end a response early. The client should raise an interrupted state, keep the 200 tokens of text, mark the message as incomplete, and offer a Retry or Continue control instead of replacing the text silently.
Exercise
A streamed tool call has produced the text {"city": "Par when the connection drops. Why must the application not run the tool, and what should it do instead?
Show answer
The arguments are incomplete and not valid JSON. Even if a lenient parser repaired them to a plausible value such as "Par", the tool would run with guessed input and could cause real side effects. The application should discard the partial call, report the interruption, and let the user retry the whole request.