Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: Show an error when Anthropic fails a reply partway through (#10811)

Nilaya32099207f8e
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 12f6e7a6614..9c3ed68ffa6 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -3109,6 +3109,21 @@ class ExternalProviderClient:
yield "data: [DONE]"
await response.aclose() # set PoolByteStream._closed=True FIRST
break
+
+ elif event_type == "error":
+ if thinking_open:
+ yield _content_chunk("</think>")
+ error = event.get("error")
+ error_type = error.get("type") if isinstance(error, dict) else None
+ # An unhashable `type` from a stand-in gateway raised out of here.
+ if not isinstance(error_type, str):
+ error_type = None
+ yield _error_sse_line(
+ _ANTHROPIC_ERROR_STATUS.get(error_type, 502),
+ _json.dumps(event),
+ self.provider_type,
+ )
+ break
except GeneratorExit:
await response.aclose() # set PoolByteStream._closed=True FIRST
await lines_gen.aclose() # now safe — aclose() is a no-op
@@ -6561,6 +6576,22 @@ def _readable_provider_error(status_code: int, message: str, provider_type: str)
return f"{text} ({code})" if code and code not in text else text
+# A mid-stream error keeps the status its type maps to, so a rate limit still reads as 429.
+_ANTHROPIC_ERROR_STATUS = {
+ "invalid_request_error": 400,
+ "authentication_error": 401,
+ "billing_error": 402,
+ "permission_error": 403,
+ "not_found_error": 404,
+ "conflict_error": 409,
+ "request_too_large": 413,
+ "rate_limit_error": 429,
+ "api_error": 500,
+ "timeout_error": 504,
+ "overloaded_error": 529,
+}
+
+
def _error_sse_line(
status_code: int,
message: str,
diff --git a/studio/backend/tests/test_anthropic_stream_error.py b/studio/backend/tests/test_anthropic_stream_error.py
new file mode 100644
index 00000000000..b47bb96e5db
--- /dev/null
+++ b/studio/backend/tests/test_anthropic_stream_error.py
@@ -0,0 +1,166 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import httpx
+import pytest
+
+from core import research_runs
+from core.inference.external_provider import _ANTHROPIC_ERROR_STATUS
+from utils.api_errors import ANTHROPIC_TYPE_BY_STATUS
+
+from .test_anthropic_thinking_translation import (
+ _anthropic_sse,
+ _collect,
+ _drive,
+ _make_client,
+ _mock_http_client,
+ _payloads_from_lines,
+)
+
+_MESSAGE_START = {
+ "type": "message_start",
+ "message": {
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "content": [],
+ "usage": {"input_tokens": 5, "output_tokens": 1},
+ },
+}
+_TEXT = [
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "text_delta", "text": "The three causes are"},
+ },
+]
+_THINKING = [
+ {
+ "type": "content_block_start",
+ "index": 0,
+ "content_block": {"type": "thinking", "thinking": "", "signature": ""},
+ },
+ {
+ "type": "content_block_delta",
+ "index": 0,
+ "delta": {"type": "thinking_delta", "thinking": "Let me plan"},
+ },
+]
+
+
+def _error(error_type, message):
+ return {"type": "error", "error": {"type": error_type, "message": message}}
+
+
+def _stream_lines(monkeypatch, events):
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ content = _anthropic_sse([_MESSAGE_START, *events]),
+ headers = {"content-type": "text/event-stream"},
+ )
+
+ _mock_http_client(monkeypatch, handler)
+
+ async def run():
+ client = _make_client()
+ lines = await _collect(
+ client._stream_anthropic(
+ messages = [{"role": "user", "content": "hi"}],
+ model = "claude-opus-4-6",
+ temperature = 0.7,
+ top_p = 0.95,
+ max_tokens = 4096,
+ )
+ )
+ await client.close()
+ return lines
+
+ return _drive(run())
+
+
+ ("events", "error", "content", "expected"),
+ [
+ (
+ _TEXT,
+ _error("overloaded_error", "Overloaded"),
+ "The three causes are",
+ {"message": "Overloaded (overloaded_error)", "code": "529"},
+ ),
+ (
+ [],
+ _error("overloaded_error", "Overloaded"),
+ "",
+ {"message": "Overloaded (overloaded_error)", "code": "529"},
+ ),
+ (
+ _THINKING,
+ _error("overloaded_error", "Overloaded"),
+ "<think>Let me plan</think>",
+ {"message": "Overloaded (overloaded_error)", "code": "529"},
+ ),
+ (
+ _TEXT,
+ _error("api_error", "Internal server error"),
+ "The three causes are",
+ {"message": "Internal server error (api_error)", "code": "500"},
+ ),
+ (
+ _TEXT,
+ _error("some_new_error", "Something went wrong"),
+ "The three causes are",
+ {"message": "Something went wrong (some_new_error)", "code": "502"},
+ ),
+ ],
+)
+def test_midstream_error_event_ends_stream_with_error(
+ monkeypatch, events, error, content, expected
+):
+ payloads = _payloads_from_lines(_stream_lines(monkeypatch, [*events, error]))
+
+ assert payloads[-1:] == [
+ {"error": {**expected, "type": "provider_error", "provider": "anthropic"}}
+ ]
+ assert "[DONE]" not in payloads
+ combined = "".join(p["choices"][0]["delta"].get("content", "") for p in payloads[:-1])
+ assert combined == content
+
+
+def test_midstream_rate_limit_is_retried_by_research(monkeypatch):
+ lines = _stream_lines(monkeypatch, [_error("rate_limit_error", "Rate limited")])
+
+ assert _payloads_from_lines(lines)[-1]["error"]["code"] == "429"
+ assert research_runs._stream_rate_limit_delay(lines[0]) == 0.0
+
+
+def test_every_documented_error_type_has_a_streamed_status():
+ missing = set(ANTHROPIC_TYPE_BY_STATUS.values()) - set(_ANTHROPIC_ERROR_STATUS)
+ assert not missing, f"no streamed status for {missing}"
+ assert _ANTHROPIC_ERROR_STATUS["conflict_error"] == 409
+
+
+ "error",
+ [
+ {"type": "error", "error": {"type": ["overloaded_error"], "message": "listy"}},
+ {"type": "error", "error": {"type": {"a": 1}, "message": "dicty"}},
+ {"type": "error", "error": {"type": 529, "message": "numeric"}},
+ {"type": "error", "error": {"message": "no type at all"}},
+ {"type": "error", "error": "a bare string"},
+ {"type": "error", "error": None},
+ {"type": "error"},
+ ],
+)
+def test_malformed_error_frame_still_reaches_the_client(monkeypatch, error):
+ # An unhashable ``type`` used to raise, and the chat showed "An internal error occurred".
+ payloads = _payloads_from_lines(_stream_lines(monkeypatch, [*_TEXT, error]))
+
+ reported = payloads[-1]["error"]
+ assert reported["type"] == "provider_error"
+ assert reported["provider"] == "anthropic"
+ assert isinstance(reported["message"], str) and reported["message"]
+ assert "[DONE]" not in payloads
+ combined = "".join(p["choices"][0]["delta"].get("content", "") for p in payloads[:-1])
+ assert combined == "The three causes are"
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 7209f9c0686..58e764d9784 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -7845,41 +7845,39 @@ export function createOpenAIStreamAdapter(
closeReasoningContent();
const partialText = mergeContinuation(cumulativeText, { final: true });
const partialContent = buildAssistantContent(partialText);
- if (partialContent.length > 0) {
- const partialTiming = buildTiming(
- streamStartTime,
- totalChunks,
- firstTokenTime,
- Date.now() - streamStartTime,
- estimateTokenCount(partialText),
- toolCallParts.length,
- );
- yield {
- content: partialContent,
- metadata: {
- timing: partialTiming,
- custom: {
- ...reasoningDurationTracker.metadata(),
- contextTruncation,
- // Unfinished too, so it also offers Continue -- unless the provider already
- // said why the model stopped.
- incomplete: {
- reason: resolveIncompleteReason(
- err instanceof GenerationLengthError
- ? ("length" as const)
- : err instanceof ChatGenerationTerminalError &&
- err.generationStatus === "cancelled"
- ? ("cancelled" as const)
- : ("interrupted" as const),
- contextWindowExceeded,
- ),
- },
- timing: partialTiming,
- ...generationCustom(),
+ const partialTiming = buildTiming(
+ streamStartTime,
+ totalChunks,
+ firstTokenTime,
+ Date.now() - streamStartTime,
+ estimateTokenCount(partialText),
+ toolCallParts.length,
+ );
+ yield {
+ content: partialContent,
+ metadata: {
+ timing: partialTiming,
+ custom: {
+ ...reasoningDurationTracker.metadata(),
+ contextTruncation,
+ // Unfinished too, so it also offers Continue -- unless the provider already
+ // said why the model stopped.
+ incomplete: {
+ reason: resolveIncompleteReason(
+ err instanceof GenerationLengthError
+ ? ("length" as const)
+ : err instanceof ChatGenerationTerminalError &&
+ err.generationStatus === "cancelled"
+ ? ("cancelled" as const)
+ : ("interrupted" as const),
+ contextWindowExceeded,
+ ),
},
+ timing: partialTiming,
+ ...generationCustom(),
},
- };
- }
+ },
+ };
}
throw err;
} finally {
diff --git a/studio/frontend/tests/chat-continuation.test.ts b/studio/frontend/tests/chat-continuation.test.ts
index 0f972136567..fc836ded33c 100644
--- a/studio/frontend/tests/chat-continuation.test.ts
+++ b/studio/frontend/tests/chat-continuation.test.ts
@@ -1819,6 +1819,15 @@ test("a failure on a thread leaves a hold whose run is already streaming alone",
assert.equal(keeper.held(), 0);
});
+test("a turn that fails before any text is still saved as interrupted", () => {
+ const failure = CHAT_ADAPTER.slice(
+ CHAT_ADAPTER.indexOf("const partialContent = buildAssistantContent(partialText);"),
+ );
+ const saved = failure.slice(0, failure.indexOf("throw err;"));
+ assert.doesNotMatch(saved, /if \(partialContent\.length > 0\)/);
+ assert.match(saved, /yield \{\s*content: partialContent,[\s\S]*incomplete: \{/);
+});
+
test("the keeper is wired to the failure the adapter already reports", () => {
// There is exactly one signal for a run that failed on its way out, and it is not a
// deadline: the adapter wrapper catches everything `adapter.run` throws and announces it