Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions dashscope/transport/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@ def __init__(
def __iter__(self) -> Iterator[T]:
try:
for sse in EventSource(self._response).iter_sse():
if sse.data == DONE_MARKER:
break
body = _next_event(
sse.data,
self._response.headers,
Expand Down Expand Up @@ -247,6 +249,8 @@ def __aiter__(self):
async def _iterate(self):
try:
async for sse in EventSource(self._response).aiter_sse():
if sse.data == DONE_MARKER:
break
body = _next_event(
sse.data,
self._response.headers,
Expand Down
72 changes: 57 additions & 15 deletions tests/test_sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,23 +206,35 @@ def handler(request):
next(iter(stream))


class _OpenEndedSSEBody(httpx.ByteStream):
def __iter__(self):
yield from super().__iter__()
raise AssertionError("read beyond the [DONE] marker")

async def __aiter__(self):
async for chunk in super().__aiter__():
yield chunk
raise AssertionError("read beyond the [DONE] marker")


_DONE_EVENTS = [
{
"id": "chatcmpl-1",
"choices": [{"index": 0, "delta": {"content": "Hi"}}],
},
"[DONE]",
]


def test_done_marker_ends_stream():
response = httpx.Response(
200,
headers={"Content-Type": "text/event-stream"},
stream=_OpenEndedSSEBody(_sse(_DONE_EVENTS).encode()),
)

def handler(request):
return httpx.Response(
200,
headers={"Content-Type": "text/event-stream"},
text=_sse(
[
{
"id": "chatcmpl-1",
"choices": [
{"index": 0, "delta": {"content": "Hi"}},
],
},
"[DONE]",
],
),
)
return response

client = _make_client(handler, protocol="openai")
stream = client.chat.completions.create(
Expand All @@ -231,6 +243,36 @@ def handler(request):
stream=True,
)
assert list(stream.text_stream) == ["Hi"]
assert response.is_closed


@pytest.mark.asyncio
async def test_async_done_marker_ends_stream():
response = httpx.Response(
200,
headers={"Content-Type": "text/event-stream"},
stream=_OpenEndedSSEBody(_sse(_DONE_EVENTS).encode()),
)

def handler(request):
return response

async with httpx.AsyncClient(
transport=httpx.MockTransport(handler),
) as http_client:
client = AsyncClient(
api_key="sk-test",
protocol="openai",
base_url=BASE_URL,
http_client=http_client,
)
stream = await client.chat.completions.create(
model="qwen-plus",
messages=[{"role": "user", "content": "hi"}],
stream=True,
)
assert [text async for text in stream.text_stream] == ["Hi"]
assert response.is_closed


def test_stream_error_carries_response_request_id():
Expand Down
Loading