diff --git a/dashscope/transport/sse.py b/dashscope/transport/sse.py index ab6b9393..5dfc60fe 100644 --- a/dashscope/transport/sse.py +++ b/dashscope/transport/sse.py @@ -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, @@ -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, diff --git a/tests/test_sse.py b/tests/test_sse.py index eb49c047..7ca9bba6 100644 --- a/tests/test_sse.py +++ b/tests/test_sse.py @@ -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( @@ -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():