Sub topic 12
Handling failures in the middle of a stream
This chapter assumes you know how streaming responses work (server-sent events or chunked iteration in an SDK) and have read the earlier chapters on retries, backoff, and timeouts.
Why streams fail differently
A streamed response begins with a normal 200 OK. The status line is already sent, so a later failure cannot be reported as a 429 or 500. The connection may drop, the server may stop sending data, or the provider may emit an error event inside the stream. Your code has already received part of the answer when this happens.
This creates three problems that a plain request does not have:
- Retrying the request restarts generation from the beginning.
- The partial text may already have been shown to a user or passed to another system.
- A stalled stream can hang without raising any error.
Detect stalls with an idle timeout
A total timeout is a poor fit for streaming, because a long answer may legitimately take a minute. Set a short timeout on the gap between chunks, and a longer overall deadline for the whole response. Most HTTP clients call the gap a read timeout. If no chunk arrives within it, the client raises an error that you can handle like any other transport failure.
Choose a recovery strategy
| Strategy | Use when | Cost |
|---|---|---|
| Discard and restart | The output is consumed only after it is complete | You pay for the tokens generated twice |
| Keep the partial and surface an error | A person is reading and the partial text is still useful | The answer is incomplete |
| Continue from the partial | You can send the partial text back and ask the model to continue | The continuation may not match the original wording |
Restarting is the simplest and the safest default. Continuing is possible but unreliable, because sampling is not deterministic. Treat a continued answer as new text and check it.
Example: restart with a clean buffer
The key rule is that every attempt starts with an empty buffer. If you keep appending to the same list, a retry produces duplicated text. This example simulates a stream that drops once.
import time
class StreamInterrupted(Exception):
pass
def fake_stream(fail_after=None):
words = "A retry restarts the stream from the beginning".split()
for i, word in enumerate(words):
if fail_after is not None and i == fail_after:
raise StreamInterrupted("connection dropped")
yield word + " "
def collect_stream(make_stream, max_attempts=3):
for attempt in range(1, max_attempts + 1):
parts = [] # fresh buffer for every attempt
try:
for chunk in make_stream(attempt):
parts.append(chunk)
return "".join(parts)
except StreamInterrupted as exc:
print(f"attempt {attempt} failed after {len(parts)} chunks: {exc}")
if attempt == max_attempts:
raise
time.sleep(0.1 * attempt)
text = collect_stream(lambda attempt: fake_stream(fail_after=3 if attempt == 1 else None))
print(text)In real code, replace StreamInterrupted with your client's transport and timeout exceptions, and use the backoff and jitter function from the earlier chapters instead of the fixed sleep.
Pitfalls
- If the model's output triggers actions, such as tool calls, wait for the complete message before running them. A cut-off tool call may contain invalid JSON.
- Count restarts against your retry limit and budget. Each restart repeats the input tokens and any output already generated.
- Check the stop signal. A stream that ends without a finish reason, such as
stoporlength, was cut short even if no exception was raised. - Log how many chunks arrived before each failure so you can tell stalls from early drops.
Exercise
A stream has delivered 40 chunks and then raises a connection error. Your code appends chunks to a list that is created once, before the retry loop. What goes wrong after a successful retry, and how do you fix it?
Show answer
The list still holds the 40 chunks from the failed attempt, so the final text begins with a stale partial answer followed by the full new answer. Create the buffer inside the loop so each attempt starts empty, and return only the buffer from the successful attempt.