Skip to content

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

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
NilayYadav:anthropic-stream-error
Sep 13, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
NilayYadav:anthropic-stream-error

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

When Anthropic failed a reply after it had started, for example with an overloaded error, Studio saved the partial answer as if it had finished. There was no error and no way to continue it. If the failure came before any text, the reply was left blank. Anthropic sends these failures inside the reply stream, and Studio ignored that message and ended the reply normally.

Now Studio passes the error on to the chat, the same way it already does for OpenAI replies. The chat shows the error with a Retry button, and the partial answer is marked as interrupted so it can be continued. A reply that fails before any text is also saved as interrupted, so the error is still there after a page reload.

Replies that finish normally are unchanged. Tested in the Studio chat with a stand-in Anthropic server that fails partway through. Before, the half answer was saved as complete. After, the error, Retry, and Continue are shown, and they stay after a reload.


Before / after in Studio

Both sides are a full install.sh --local build, BEFORE from this PR's merge base 8ee07d6ae and AFTER from 7b9be3578, each pointed at the same stand-in Anthropic Messages API that streams The three causes are and then the documented in-stream frame {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}. No key is used and no request leaves the machine. Each side recorded exactly one POST /v1/messages, so both builds saw identical bytes.

Live, once the turn settles. BEFORE saves the half answer as a finished turn: no error, no Retry, no Continue. AFTER shows Overloaded (overloaded_error) with Retry, the Response interrupted. Continue bar, and a Generation failed toast.

Studio chat, live turn, before and after

After a full page reload, reopening the thread from Recents. BEFORE is still a finished turn. AFTER still carries the error box, Retry and Continue; its message falls back to the generic An error occurred, because the provider's own text is not persisted.

Studio chat, after reload, before and after

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-13T13:37:19.824614Z c91d547 Manual request
🔒 Security Review ✅ Completed 2026-09-13T13:34:49.445774Z 7b9be35 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a4a2756ce9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +7800 to +7801
yield {
content: partialContent,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict empty interrupted turns to started streams

When any request fails before producing a chunk—for example, streamChatCompletions receives a non-200 response for an invalid API key, unavailable model, or oversized prompt—this unconditional yield now persists an empty assistant message marked interrupted and offers Continue even though generation never started. This changes every provider and preflight failure merely to preserve Anthropic's streamed error case; retain the prior nonempty guard for ordinary early failures and use a dedicated signal for the Anthropic error event that needs an empty persisted turn.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping this as is. Continue is only offered when the partial has text (resumable requires partial.trim() in thread.tsx), so a turn that fails before any output shows the error with Retry, not Continue. Saving it as interrupted also matches server-managed runs, which already mark any failed run interrupted whatever its content, and it is what keeps the failure visible after a reload.

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Review + GitHub Actions UI evidence

Pinned review: 76993d58ea6ffc0d66241c933756db4d08e43144.

Codex round on a4a2756

  • Rate-limit status (two threads, same finding): fixed in 76993d5. An in-stream Anthropic error now keeps the HTTP status of its documented type (rate_limit_error 429, api_error 500, timeout_error 504, overloaded_error 529, unknown 502), so a rate limit before any text reaches Deep Research's backoff as 429. The regression test fails on a4a2756 ('502' == '429') and passes on 76993d5.
  • Empty interrupted turn: kept. Continue requires a non-empty partial, so an early failure shows the error with Retry only.

Real Studio flow on GitHub Actions (ubuntu-latest, Chromium, 1280×820) on fresh upstream main bf87e29 plus the PR. Both branches use the same harness and differ only in external_provider.py and chat-adapter.ts. The connection points at a stand-in Anthropic Messages API, so no key is used.

  • Fix reverted — expected-failing run: partial reply then overloaded_error: error box false, Retry false, Continue false, saved incomplete null, before and after reload. Error before any text: blank reply, no error, saved incomplete null. Failed at 7 of 7 assertions.
  • PR head — passing run: partial reply: "Overloaded (overloaded_error)" with Retry and "Response interrupted. Continue", both still there after reload, saved incomplete {reason: interrupted}. Error before any text: error box with Retry and no Continue, still there after reload, saved interrupted.

PR 10811 GitHub Actions before/after

Other reds: (Python 3.13) fails on test_deepseek_r1_huge_fenceless_body_is_linear, a timing check that fails the same way on main. The parity red is a reasoning_toggle scroll-offset difference: both arms have the same 21 messages, and the harness marks the pair as not like-for-like.

Minor, not blocking: after a reload the error box keeps Retry but its text becomes the generic "An error occurred", because the provider's message is not saved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 11, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

1 similar comment
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 76993d58ea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +3064 to +3068
yield _error_sse_line(
_ANTHROPIC_ERROR_STATUS.get(error_type, 502),
_json.dumps(event),
self.provider_type,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Stop the Studio tool loop after relaying an Anthropic error

When Studio tools are enabled, this error frame passes through stream_with_studio_tools, which relays payloads without choices but does not mark the provider turn as failed. After Anthropic's generator closes, the loop can therefore execute a completed local tool call collected before the error, or nudge a short partial response and open another billed provider request; durable chat generation drains that entire stream, so client disconnect does not stop this behavior. Treat this frame as terminal inside the tool loop rather than merely yielding it—the new test calls _stream_anthropic directly and does not cover the public tool-loop path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An Anthropic connection never reaches stream_with_studio_tools. The route only opens the loop when provider_model_runs_local_tools(provider_type, model) is true, and that returns False for anthropic because its registry entry has no studio_tools flag (every other provider sets it). providers.py documents why: _stream_anthropic never forwards function-tool schemas, so there are no local tool calls to collect or run, and no Studio nudge turn on this path. This error frame goes straight to the chat stream.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 76993d58ea

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the Anthropic stream loop in studio/backend/core/inference/external_provider.py handles no error event today, so a mid-stream overload ends the reply as if it finished, and the status mapping now keeps a rate limit at 429 for the research backoff. Will get this reviewed.

An in-stream error whose type is not a string (a list or a dict, from a gateway
standing in for Anthropic) raised TypeError out of _stream_anthropic on the dict
lookup. The route's catch-all turned that into "An internal error occurred" with
type server_error, so the provider's own message was lost and the status Deep
Research backs off on never arrived. Non-string types now fall back to 502 like
any unknown type.

Also adds conflict_error 409, the one type in the repo's own
ANTHROPIC_TYPE_BY_STATUS that the streamed map did not name.
@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 7b9be35783

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 13, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 7b9be35783

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: c91d547804

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Reviewed this end to end and pushed two fixes onto the branch. The change is correct and I am happy with it.

The defect is real, not theoretical

I reverted only the two production hunks in a worktree and re-ran the PR's tests against that tree: all six fail on the merge base and pass on head. Anthropic's docs confirm the wire shape the branch handles, event: error with {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}, and state that an error after a 200 does not follow the normal error mechanism. Before this PR the loop had no branch for it, the generator just ended, the route appended its own [DONE], and the chat saved the half answer as a finished turn. The before and after screenshots are now at the end of the description.

Two fixes pushed

  1. c91d547 / 3b6ffb5: a malformed error frame used to kill the reply. _ANTHROPIC_ERROR_STATUS.get(error_type, 502) raised TypeError when error.type was not hashable (a list or a dict), and since only httpx exceptions are caught in _stream_anthropic, that propagated to the route's catch-all, which reported An internal error occurred with type: server_error. The provider's own message was lost and the status Deep Research backs off on never arrived. This is reachable rather than hypothetical: an Anthropic connection keeps an editable base URL (base_url_editable defaults to true), so any gateway or stand-in server can send it, which is exactly what this PR's own test harness is. Non-string types now fall back to 502 like any unknown type.
  2. conflict_error 409 added. It is the one type in the repo's own ANTHROPIC_TYPE_BY_STATUS that the streamed map did not name, and it is in Anthropic's published table. A test now asserts the two tables cannot drift apart.

Both fixes have regression tests that fail on 76993d5 and pass on head.

What I checked beyond the diff

  • 3036 tests pass across all 55 backend suites that touch external_provider.
  • A 58 case simulation matrix written for this review: every documented error type, the error at ten different stream positions (before message_start, mid text, mid thinking, after content_block_stop, after a usage carrying message_delta, inside an open web_search block, after pause_turn and after refusal), ten malformed payloads, SSE framing with embedded newlines, a data: prefix, 20KB and unicode messages, events after the error being ignored, two errors in a row, early consumer close, and the success path as a control.
  • 14 frontend simulations covering the guard removal. The empty yield cannot erase text that already streamed (assistant-ui merges content ? [...initial, ...content]), a post abort yield is discarded by the runtime, and Continue is correctly withheld from an empty or whitespace only partial.

On the two items I marked down

The tool loop one does not apply: provider_model_runs_local_tools gates on the registry's studio_tools flag and the Anthropic entry does not set it, so an Anthropic stream never reaches stream_with_studio_tools. The empty interrupted turn one is narrower than it reads: the yield is still behind if (!abortSignal.aborted) and assistant-ui drops post abort yields, so Stop is untouched, and an empty assistant row was already persisted before this PR by the history adapter, which has no content guard. The change adds metadata to a row that already existed.

Two follow ups, neither blocking

  • The error break skips the usage chunk, so a turn that produced tokens and then failed records no token counts. The OpenAI mid-stream path has the same gap, so this is not a regression, but it is worth closing separately.
  • research_runs only backs off on a 429 when the error is the stream's first line, because _peek_stream_head reads one line. A rate_limit_error arriving after some text still propagates as an error rather than a retry. That is the pre-existing peek design, not something this PR changed, but the description reads slightly broader than the behaviour.

Platforms

The per OS staging jobs pass on ubuntu-latest, macos-15 and windows-latest. There is no hardware path here: the diff contains no device, CUDA, ROCm or torch code, and the changed frontend region touches no browser API, so there is nothing for a GPU vendor or a browser engine to vary. No dependency, schema or migration changes, and chat-api.ts has handled error frames since June, so a stale tab on an older bundle degrades gracefully against an updated backend.

@danielhanchen
danielhanchen merged commit a320992 into unslothai:main Sep 13, 2026
40 checks passed
CelesteHeartsong pushed a commit to CelesteHeartsong/unsloth that referenced this pull request Sep 22, 2026
…ai#10365 conflicts)

unslothai#10365 landed on main after this branch forked from the shared dev base, so its
reviewed durable-turns code collided with the copy carried here. Resolved per file:

- backend state/tool_approvals.py, tests/test_tool_approvals.py and
  tests/studio/test_desktop_reliability_frontend_contract.py: take main's reviewed
  version (this PR has no unique work in them).
- core/inference/chat_generation_runs.py: take main's reviewed park/lease logic.
- routes/chat_generation_runs.py, durable-gate.ts, durable-gate.test.ts and
  test_multi_chat_prompt_queue_contract.py: keep THIS PR's media-turns work -
  UNSLOTH_STUDIO_DURABLE_MEDIA_TURNS toggle (default on), media removed from the
  frontend gate, and the matching "media turns are durable" assertions.
- chat-adapter.ts: keep shapeToolResult shaper + media-durable gate args; take main
  for import formatting and the partial-yield block (unslothai#10811 removed that guard); drop
  the duplicate local isMcpImageToolResult (imported from utils/tool-result-shape).
- runtime-provider.tsx: keep this PR's self-consistent recovery impl.
- generation-tool-recovery.test.ts: union the mock store stubs.

REVIEW NOTE: main's media-refusal branch also detects input-audio / embedded-image /
video inside messages[] (added after this branch forked); this branch's toggle-off
refusal only checks top-level _MEDIA_FIELDS. Decide whether to fold those in.

Follow-ups before landing: tsc -b + npm test; backend test_chat_generation_runs +
test_tool_approvals; reconcile the shared replay files with unslothai#10910 (keep unslothai#10910's).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants