mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-07 03:28:50 +08:00
fix(llm): require message_stop before completing Anthropic streams
This commit is contained in:
@@ -622,39 +622,29 @@ class AnthropicProvider(LLMProvider):
|
||||
idle_timeout_s = 90
|
||||
try:
|
||||
async with self._client.messages.stream(**kwargs) as stream:
|
||||
if on_content_delta or on_reasoning_delta:
|
||||
# Iterate the raw event stream rather than ``text_stream``.
|
||||
# ``text_stream`` yields text blocks only, so an extended
|
||||
# thinking model streamed its answer here while its
|
||||
# reasoning — the part a reader most wants to watch arrive —
|
||||
# was silently dropped, and ``on_reasoning_delta`` went
|
||||
# unused despite being accepted.
|
||||
stream_iter = stream.__aiter__()
|
||||
while True:
|
||||
try:
|
||||
event = await asyncio.wait_for(
|
||||
stream_iter.__anext__(),
|
||||
timeout=idle_timeout_s,
|
||||
)
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
if getattr(event, "type", "") != "content_block_delta":
|
||||
continue
|
||||
delta = getattr(event, "delta", None)
|
||||
delta_type = str(getattr(delta, "type", "") or "")
|
||||
if delta_type == "text_delta" and on_content_delta:
|
||||
text = str(getattr(delta, "text", "") or "")
|
||||
if text:
|
||||
await on_content_delta(text)
|
||||
elif delta_type == "thinking_delta" and on_reasoning_delta:
|
||||
thinking = str(getattr(delta, "thinking", "") or "")
|
||||
if thinking:
|
||||
await on_reasoning_delta(thinking)
|
||||
response = await asyncio.wait_for(
|
||||
stream.get_final_message(),
|
||||
timeout=idle_timeout_s,
|
||||
)
|
||||
return self._parse_response(response)
|
||||
# The SDK's accumulated message can be returned after EOF
|
||||
# even if the server never finished sending it.
|
||||
stream_iter = stream.__aiter__()
|
||||
while True:
|
||||
try:
|
||||
event = await asyncio.wait_for(
|
||||
stream_iter.__anext__(),
|
||||
timeout=idle_timeout_s,
|
||||
)
|
||||
except StopAsyncIteration:
|
||||
return LLMResponse(
|
||||
content="Error calling LLM: Anthropic stream ended before message_stop",
|
||||
finish_reason="error",
|
||||
)
|
||||
if event.type == "message_stop":
|
||||
return self._parse_response(event.message)
|
||||
if event.type != "content_block_delta":
|
||||
continue
|
||||
delta = event.delta
|
||||
if delta.type == "text_delta" and on_content_delta and delta.text:
|
||||
await on_content_delta(delta.text)
|
||||
elif delta.type == "thinking_delta" and on_reasoning_delta and delta.thinking:
|
||||
await on_reasoning_delta(delta.thinking)
|
||||
except asyncio.TimeoutError:
|
||||
return LLMResponse(
|
||||
content=f"Error calling LLM: stream stalled for more than {idle_timeout_s} seconds",
|
||||
|
||||
104
tests/services/llm/test_anthropic_stream_terminal.py
Normal file
104
tests/services/llm/test_anthropic_stream_terminal.py
Normal file
@@ -0,0 +1,104 @@
|
||||
"""The Anthropic Messages stream needs an explicit terminal event."""
|
||||
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from deeptutor.services.llm.provider_core.anthropic_provider import AnthropicProvider
|
||||
|
||||
anthropic = pytest.importorskip("anthropic")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("with_callback", [False, True])
|
||||
@pytest.mark.parametrize("end_at", ["text", "stop_reason", "message_stop"])
|
||||
async def test_anthropic_stream_completion_requires_message_stop(
|
||||
monkeypatch, with_callback, end_at
|
||||
):
|
||||
# The Anthropic SDK changed its transport package in 2.x.
|
||||
if issubclass(anthropic.DefaultAsyncHttpxClient, httpx.AsyncClient):
|
||||
transport = httpx
|
||||
else:
|
||||
import httpx2 as transport
|
||||
|
||||
events = [
|
||||
{
|
||||
"type": "message_start",
|
||||
"message": {
|
||||
"id": "msg_fixture",
|
||||
"type": "message",
|
||||
"role": "assistant",
|
||||
"model": "claude-sonnet-4-6",
|
||||
"content": [],
|
||||
"stop_reason": None,
|
||||
"stop_sequence": None,
|
||||
"usage": {"input_tokens": 5, "output_tokens": 0},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "content_block_start",
|
||||
"index": 0,
|
||||
"content_block": {"type": "text", "text": ""},
|
||||
},
|
||||
{"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hi"}},
|
||||
]
|
||||
if end_at != "text":
|
||||
events.extend(
|
||||
[
|
||||
{"type": "content_block_stop", "index": 0},
|
||||
{
|
||||
"type": "message_delta",
|
||||
"delta": {"stop_reason": "end_turn", "stop_sequence": None},
|
||||
"usage": {"output_tokens": 1},
|
||||
},
|
||||
]
|
||||
)
|
||||
if end_at == "message_stop":
|
||||
events.append({"type": "message_stop"})
|
||||
|
||||
class Body(transport.AsyncByteStream):
|
||||
closed = False
|
||||
|
||||
async def __aiter__(self):
|
||||
for event in events:
|
||||
yield f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode()
|
||||
|
||||
async def aclose(self):
|
||||
self.closed = True
|
||||
|
||||
body = Body()
|
||||
calls = []
|
||||
|
||||
async def send(request):
|
||||
calls.append(request.url.path)
|
||||
return transport.Response(200, headers={"content-type": "text/event-stream"}, stream=body)
|
||||
|
||||
deltas = []
|
||||
|
||||
async def emit(text):
|
||||
deltas.append(text)
|
||||
|
||||
async with anthropic.AsyncAnthropic(
|
||||
api_key="fixture",
|
||||
base_url="https://anthropic.test",
|
||||
http_client=transport.AsyncClient(transport=transport.MockTransport(send)),
|
||||
max_retries=0,
|
||||
) as client:
|
||||
monkeypatch.setattr(anthropic, "AsyncAnthropic", lambda **kwargs: client)
|
||||
provider = AnthropicProvider(api_key="fixture", default_model="claude-sonnet-4-6")
|
||||
result = await provider.chat_stream_with_retry(
|
||||
messages=[{"role": "user", "content": "Hello"}],
|
||||
on_content_delta=emit if with_callback else None,
|
||||
retry_delays=(0.001,),
|
||||
)
|
||||
assert calls == ["/v1/messages"]
|
||||
assert body.closed
|
||||
assert deltas == (["Hi"] if with_callback else [])
|
||||
if end_at == "message_stop":
|
||||
assert result.finish_reason == "stop"
|
||||
assert result.content == "Hi"
|
||||
assert result.usage["total_tokens"] == 6
|
||||
else:
|
||||
assert result.finish_reason == "error"
|
||||
assert "message_stop" in result.content
|
||||
Reference in New Issue
Block a user