Sub topic 14
Handling failures after the first token
This chapter assumes you can read the SSE (Server-Sent Events) format and accumulate deltas into a message, as covered earlier. It also assumes you know basic Python exceptions and HTTP status codes.
Why status codes no longer help
An HTTP response starts with its status line. Once the server sends 200 OK and the first token, it can't change that status. If the model backend fails at token 40, the client still sees a successful response that stops early or contains an error event.
Failures therefore arrive in three forms:
| Failure | What the client sees | How to detect it |
|---|---|---|
| Error event | A normal event with an `error` payload | Check each parsed event |
| Dropped connection | An exception or an abrupt end of the body | Catch the read error |
| Silent truncation | The stream closes cleanly, with no finish reason or `[DONE]` | Check for a completion marker after the loop |
The third form is the easiest to miss. A proxy timeout can close the stream cleanly, and your loop will exit as if the answer were finished.
Detecting incomplete streams
Treat the finish reason as the proof of success. This function keeps the partial text and raises a single exception type for all three failures.
class StreamIncomplete(Exception):
def __init__(self, partial, reason):
super().__init__(reason)
self.partial = partial
def collect(events):
parts = []
finish = None
try:
for event in events:
if "error" in event:
raise StreamIncomplete("".join(parts), event["error"]["message"])
choice = event["choices"][0]
if choice["delta"].get("content"):
parts.append(choice["delta"]["content"])
if choice.get("finish_reason"):
finish = choice["finish_reason"]
except ConnectionError as exc:
raise StreamIncomplete("".join(parts), str(exc)) from exc
if finish is None:
raise StreamIncomplete("".join(parts), "stream ended without finish reason")
return "".join(parts), finish
def broken_stream():
yield {"choices": [{"delta": {"content": "Hel"}}]}
yield {"choices": [{"delta": {"content": "lo"}}]}
raise ConnectionError("connection reset")
try:
collect(broken_stream())
except StreamIncomplete as exc:
print(repr(exc.partial), "-", exc) # 'Hello' - connection resetDeciding what to do next
The partial text is real output the user may already have read, so don't discard it. Pick a policy based on the cost of repeating the request:
- Show the partial text with a visible "response interrupted" marker and a Retry button.
- Retry automatically only if nothing was shown yet, or if you can discard the partial text safely.
- Never append a retried response to the partial one. The model may phrase it differently, and the result will read as duplicated or contradictory text.
- Don't save a partial message to history as if it were complete. Store a flag such as
incomplete: true.
If your server relays the stream, it must forward upstream errors to the browser as an event, or close the connection abnormally. If it ends the response cleanly, the browser can't tell a failure from a finished answer.
Exercise
A stream's last event is a text delta, then the connection closes cleanly with no finish reason. Is the response complete, and how should the client handle it?
Show answer
No. The missing finish reason means the stream was truncated, for example by a proxy timeout. The client should keep the partial text, mark the message incomplete, and offer a retry rather than treating it as a finished answer.