RemoteProtocolError: peer closed connection without sending complete message body (incomplete chunked read)
Cause: The connection closed while a streamed (chunked) response was still coming, so your HTTP client got only part of the reply.
Copy-paste fix
Treat a broken stream as a failed call: drop the partial text, retry the whole request a limited number of times, and log it.
RETRYABLE = {"RemoteProtocolError", "APIConnectionError", "ReadError"}
def stream_text(client, max_attempts=2, **kwargs):
for attempt in range(max_attempts):
parts = []
try:
stream = client.chat.completions.create(stream=True, **kwargs)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
parts.append(chunk.choices[0].delta.content)
return "".join(parts)
except Exception as e:
if type(e).__name__ not in RETRYABLE or attempt == max_attempts - 1:
raise
# partial text is discarded; a retry re-sends (and re-bills) the input
See what a re-sent streaming call costs on TokenCenter
What the error means
The text comes from the h11 HTTP library, which raises RemoteProtocolError with this message when a chunked body ends early; httpcore (used by httpx) passes it on as its own RemoteProtocolError.
A stream can also fail after a 200 status: Anthropic's streaming docs show errors such as overloaded_error sent as an event: error inside the stream.
Checklist
- Check proxies, load balancers and serverless limits for idle or total timeouts shorter than your longest reply.
- Handle error events inside the stream, not just exceptions.
- Show users that a reply failed instead of leaving half an answer.
- Cap stream retries; each one re-sends the whole input.
- Log the model, bytes received and elapsed time when a stream breaks.
Related
- 529 overloaded_error (Claude API)
- APITimeoutError: Request timed out.
- Failure mode: Retry and cost multipliers
- ModelRaters list: Best for fast and low cost