Skip to content

Conversation

@alexx-ftw
Copy link
Contributor

@alexx-ftw alexx-ftw commented Sep 30, 2025

Fixes #58

Summary

Fixes connection interruptions from ChatGPT API by adding graceful error handling for ChunkedEncodingError during streaming responses.

Problem

When the ChatGPT API connection is interrupted mid-response, the streaming fails abruptly with:

requests.exceptions.ChunkedEncodingError: Response ended prematurely

This results in 500 errors being returned to clients instead of graceful stream termination.

Solution

Implemented two-level error handling in sse_translate_chat:

  1. Stream initialization: Catches errors when starting iter_lines()
  2. Stream iteration: Catches errors during line-by-line processing

Both levels catch:

  • requests.exceptions.ChunkedEncodingError
  • ConnectionError
  • BrokenPipeError

When an error is caught, the stream is gracefully terminated with [DONE] message instead of returning a 500 error.

Changes

  • Modified chatmock/utils.py function sse_translate_chat (lines 465-505)
  • Added try-except blocks around stream initialization and iteration
  • Sends clean [DONE] signal on connection interruption

Testing

Tested with Claude Code Router integration where connection interruptions were occurring during long responses.

Related

…aming

Fixes connection interruptions from ChatGPT API by catching ChunkedEncodingError
and gracefully ending the stream with [DONE] instead of returning 500 errors.

Two-level error handling:
1. Catches errors during stream initialization
2. Catches errors during stream iteration

This prevents abrupt failures when the upstream connection is interrupted mid-response.
@alexx-ftw alexx-ftw force-pushed the fix/chunked-encoding-error branch from c435e1c to 24b5be8 Compare September 30, 2025 12:17
@alexx-ftw alexx-ftw marked this pull request as draft September 30, 2025 20:21
@alexx-ftw alexx-ftw marked this pull request as ready for review September 30, 2025 20:21
@RayBytes
Copy link
Owner

LGTM! Thanks for the PR

@RayBytes RayBytes merged commit fd900eb into RayBytes:main Oct 20, 2025
Wen-Tsui pushed a commit to Wen-Tsui/ChatMock that referenced this pull request Nov 16, 2025
…aming (RayBytes#57)

Fixes connection interruptions from ChatGPT API by catching ChunkedEncodingError
and gracefully ending the stream with [DONE] instead of returning 500 errors.

Two-level error handling:
1. Catches errors during stream initialization
2. Catches errors during stream iteration

This prevents abrupt failures when the upstream connection is interrupted mid-response.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: ChunkedEncodingError causes 500 errors during streaming

2 participants