Skip to content

Commit 5386db1

Browse files
authored
Fixes #184: JSON parsing issue when async streaming (#216)
1 parent fb6232f commit 5386db1

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

openai/api_requestor.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,10 @@ def parse_stream_helper(line: bytes) -> Optional[str]:
9696
# and it will close http connection with TCP Reset
9797
return None
9898
if line.startswith(b"data: "):
99-
line = line[len(b"data: ") :]
100-
return line.decode("utf-8")
99+
line = line[len(b"data: "):]
100+
return line.decode("utf-8")
101+
else:
102+
return None
101103
return None
102104

103105

@@ -109,13 +111,10 @@ def parse_stream(rbody: Iterator[bytes]) -> Iterator[str]:
109111

110112

111113
async def parse_stream_async(rbody: aiohttp.StreamReader):
112-
async for chunk, _ in rbody.iter_chunks():
113-
# While the `ChunkTupleAsyncStreamIterator` iterator is meant to iterate over chunks (and thus lines) it seems
114-
# to still sometimes return multiple lines at a time, so let's split the chunk by lines again.
115-
for line in chunk.splitlines():
116-
_line = parse_stream_helper(line)
117-
if _line is not None:
118-
yield _line
114+
async for line in rbody:
115+
_line = parse_stream_helper(line)
116+
if _line is not None:
117+
yield _line
119118

120119

121120
class APIRequestor:

0 commit comments

Comments
 (0)