Skip to content

Commit 7b4c5f7

Browse files
stainless-botRobertCraigie
authored andcommitted
fix(client): correctly handle errors during streaming
1 parent 3815517 commit 7b4c5f7

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/openai/_streaming.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import httpx
88

99
from ._types import ResponseT
10+
from ._utils import is_mapping
11+
from ._exceptions import APIError
1012

1113
if TYPE_CHECKING:
1214
from ._base_client import SyncAPIClient, AsyncAPIClient
@@ -50,7 +52,15 @@ def __stream__(self) -> Iterator[ResponseT]:
5052
break
5153

5254
if sse.event is None:
53-
yield process_data(data=sse.json(), cast_to=cast_to, response=response)
55+
data = sse.json()
56+
if is_mapping(data) and data.get("error"):
57+
raise APIError(
58+
message="An error ocurred during streaming",
59+
request=self.response.request,
60+
body=data["error"],
61+
)
62+
63+
yield process_data(data=data, cast_to=cast_to, response=response)
5464

5565

5666
class AsyncStream(Generic[ResponseT]):
@@ -92,7 +102,15 @@ async def __stream__(self) -> AsyncIterator[ResponseT]:
92102
break
93103

94104
if sse.event is None:
95-
yield process_data(data=sse.json(), cast_to=cast_to, response=response)
105+
data = sse.json()
106+
if is_mapping(data) and data.get("error"):
107+
raise APIError(
108+
message="An error ocurred during streaming",
109+
request=self.response.request,
110+
body=data["error"],
111+
)
112+
113+
yield process_data(data=data, cast_to=cast_to, response=response)
96114

97115

98116
class ServerSentEvent:

0 commit comments

Comments
 (0)