diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 45c13cc11d..006ab34f21 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -61,6 +61,14 @@ def __stream__(self) -> Iterator[_T]: try: for sse in iterator: if sse.data.startswith("[DONE]"): + # Drain remaining bytes so h11 fully parses the chunked terminator + # before close(), allowing the connection to be returned to the pool. + # Errors are suppressed — the stream is done at [DONE] regardless. + try: + for _ in iterator: + pass + except Exception: + pass break # we have to special case the Assistants `thread.` events since we won't have an "event" key in the data @@ -171,6 +179,14 @@ async def __stream__(self) -> AsyncIterator[_T]: try: async for sse in iterator: if sse.data.startswith("[DONE]"): + # Drain remaining bytes so h11 fully parses the chunked terminator + # before aclose(), allowing the connection to be returned to the pool. + # Errors are suppressed — the stream is done at [DONE] regardless. + try: + async for _ in iterator: + pass + except Exception: + pass break # we have to special case the Assistants `thread.` events since we won't have an "event" key in the data