Skip to content

Commit 8bf7866

Browse files
memory improvements + true streaming vs. batched processing before
1 parent e7dbc7c commit 8bf7866

1 file changed

Lines changed: 15 additions & 10 deletions

File tree

src/cohere/core/http_sse.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -155,18 +155,23 @@ def iter_sse(self) -> Iterator[ServerSentEvent]:
155155
self._check_content_type()
156156
decoder = SSEDecoder()
157157

158-
# Process the raw stream instead of using iter_lines() which may truncate
159-
# Read the entire response as bytes and process it manually
160-
raw_data = b""
158+
buffer = ""
161159
for chunk in self._response.iter_bytes():
162-
raw_data += chunk
163-
164-
# Convert to string and split on newlines manually
165-
text_data = raw_data.decode('utf-8', errors='replace')
166-
lines = text_data.split('\n')
160+
# Decode chunk and add to buffer
161+
text_chunk = chunk.decode('utf-8', errors='replace')
162+
buffer += text_chunk
163+
164+
# Process complete lines
165+
while '\n' in buffer:
166+
line, buffer = buffer.split('\n', 1)
167+
line = line.rstrip('\r')
168+
sse = decoder.decode(line)
169+
if sse is not None:
170+
yield sse
167171

168-
for line in lines:
169-
line = line.rstrip("\r")
172+
# Process any remaining data in buffer
173+
if buffer.strip():
174+
line = buffer.rstrip('\r')
170175
sse = decoder.decode(line)
171176
if sse is not None:
172177
yield sse

0 commit comments

Comments
 (0)