Skip to content

Commit 0b1a27f

Browse files
fix: ensure streams are always closed
1 parent e040d22 commit 0b1a27f

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

src/openai/_streaming.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,10 @@ def __stream__(self) -> Iterator[_T]:
5555
process_data = self._client._process_response_data
5656
iterator = self._iter_events()
5757

58-
for sse in iterator:
59-
if sse.data.startswith("[DONE]"):
60-
break
58+
try:
59+
for sse in iterator:
60+
if sse.data.startswith("[DONE]"):
61+
break
6162

6263
# we have to special case the Assistants `thread.` events since we won't have an "event" key in the data
6364
if sse.event and sse.event.startswith("thread."):
@@ -96,8 +97,9 @@ def __stream__(self) -> Iterator[_T]:
9697

9798
yield process_data(data=data, cast_to=cast_to, response=response)
9899

99-
# As we might not fully consume the response stream, we need to close it explicitly
100-
response.close()
100+
finally:
101+
# Ensure the response is closed even if the consumer doesn't read all data
102+
response.close()
101103

102104
def __enter__(self) -> Self:
103105
return self
@@ -156,9 +158,10 @@ async def __stream__(self) -> AsyncIterator[_T]:
156158
process_data = self._client._process_response_data
157159
iterator = self._iter_events()
158160

159-
async for sse in iterator:
160-
if sse.data.startswith("[DONE]"):
161-
break
161+
try:
162+
async for sse in iterator:
163+
if sse.data.startswith("[DONE]"):
164+
break
162165

163166
# we have to special case the Assistants `thread.` events since we won't have an "event" key in the data
164167
if sse.event and sse.event.startswith("thread."):
@@ -197,8 +200,9 @@ async def __stream__(self) -> AsyncIterator[_T]:
197200

198201
yield process_data(data=data, cast_to=cast_to, response=response)
199202

200-
# As we might not fully consume the response stream, we need to close it explicitly
201-
await response.aclose()
203+
finally:
204+
# Ensure the response is closed even if the consumer doesn't read all data
205+
await response.aclose()
202206

203207
async def __aenter__(self) -> Self:
204208
return self

0 commit comments

Comments
 (0)