Skip to content

Studio /v1/messages: accept thinking and unknown content blocks - #7017

Merged
wasimysaid merged 6 commits into
mainfrom
fix-anthropic-content-blocks
Jul 9, 2026
Merged

wasimysaid merged 6 commits into
mainfrom
fix-anthropic-content-blocks

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

Resuming a Claude Code session against Studio fails with:

API Error: 400 messages.1.content.str: Input should be a valid string

The Anthropic-compatible /v1/messages endpoint models a message's content as Union[str, list[{text | image | tool_use | tool_result}]] (studio/backend/models/inference.py). Any other block type makes Pydantic reject the whole request. A resumed session almost always replays assistant turns that carry thinking (extended thinking) blocks, and sometimes a null content for a tool-only turn; both trip this and return a 400. The ...content.str in the message is just the first half of the union error. Reproduced against the model: a thinking block, null, and a bare block dict each produce that exact error, while a plain text list passes.

Fix

  • Add a permissive AnthropicUnknownBlock fallback to the content-block union: any block whose type is not one of the four known ones (text/image/tool_use/tool_result) is accepted verbatim. A type validator rejects the known types in the fallback, so a known block still parses as its typed model and a malformed known block (e.g. a tool_use missing id) still 400s cleanly instead of being swallowed.
  • Coerce a null message content (and tool_result content) to "", so the converter's for block in content stays safe.

anthropic_messages_to_openai already ignores block types it does not translate, so a thinking block is dropped rather than forwarded to the model (verified it does not leak into the converted history).

Tests

studio/backend/tests/test_anthropic_messages.py:

  • A resumed-session payload with thinking + text + tool_use and a following null-content turn validates; the thinking block is dropped, the answer text and tool call are preserved, and the thinking text never reaches the converted messages.
  • Known blocks still parse as their typed models; a malformed tool_use (missing id) still raises.

Existing test_anthropic_messages.py (100), thinking-translation, message-content, tool-empty-content, and compaction suites pass unchanged.

The Anthropic-compatible /v1/messages endpoint modeled a message's content as
Union[str, list[{text|image|tool_use|tool_result}]], so any other block type
made Pydantic reject the whole request with
`messages.N.content.str: Input should be a valid string`. Resuming a Claude
session commonly replays assistant turns that carry `thinking` (extended
thinking) blocks, and sometimes a null content for a tool-only turn, both of
which tripped this and returned a 400.

Accept them:
- Add a permissive AnthropicUnknownBlock fallback (any block whose type is not
  one of the four known ones), so thinking/redacted_thinking/provider-specific/
  future blocks validate. A validator keeps known types on their typed models,
  so a malformed known block (e.g. a tool_use without id) still fails cleanly.
- Coerce a null message (and tool_result) content to "" so the converter's
  `for block in content` stays safe.

The converter already drops block types it does not translate, so a thinking
block is not forwarded to the model.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@danielhanchen

Copy link
Copy Markdown
Member 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

https://github.com/unslothai/unsloth/blob/b706557c52a156d1d5de8d08987f5a90e97b9542/temp_err#L1
P3 Badge Remove the checked-in temp file

The new root-level temp_err file is empty and unrelated to the /v1/messages validation changes; leaving this tracked adds an accidental debug artifact to the repository and future diffs. Please remove it from the commit.

ℹ️ 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 thread studio/backend/models/inference.py Outdated
# An assistant tool-only turn a resumed session replays can carry null
# content; the str|list union would 400 on it. An empty string is the
# neutral equivalent and keeps the converter's `for block in content` safe.
return "" if v is None else v

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Keep rejecting null user content

This validator rewrites content: null for every role, not just the assistant tool-only turns described in the comment. If a client sends a malformed user message with content: null, it now validates and is forwarded as an empty user prompt instead of being rejected at the boundary, which can hide client bugs and produce confusing backend behavior. Consider making the coercion role-aware so only assistant null content gets normalized.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in a597ba8: null coercion is role-aware. A null user content is rejected at the boundary; only an assistant tool-only turn's null content is normalized to empty.

AnthropicImageBlock,
AnthropicToolUseBlock,
AnthropicToolResultBlock,
AnthropicUnknownBlock,

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 Reject unknown user blocks instead of dropping them

Adding the unknown-block fallback to the shared content union also accepts unsupported blocks in current user messages. In that case anthropic_messages_to_openai only translates user text/image/tool_result blocks and skips every other type, so a request such as a user turn containing only a future/file-like block now succeeds while the backend receives no user content, instead of failing fast. Please limit this fallback to assistant replay history or reject unknown user blocks before conversion.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in a597ba8: the leniency is now role-aware. An unknown/untranslatable block in a user message is rejected (400) instead of silently dropped; assistant replay history still accepts unknown/thinking blocks (the converter drops them).

danielhanchen and others added 2 commits July 9, 2026 06:42
Make the thinking/null leniency role-aware so it never silently drops real
user input. Assistant turns (replayed history) still accept unknown/thinking
blocks and coerce a null tool-only turn to empty. User turns keep the strict
boundary: a null user content is rejected, and a content block the converter
cannot translate is rejected instead of being dropped into an empty prompt.

Also remove an empty file committed by accident.
@danielhanchen

Copy link
Copy Markdown
Member 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: 088916f5c6

ℹ️ 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 thread studio/backend/models/inference.py Outdated
return data
content = data.get("content")
if data.get("role") == "assistant":
return {**data, "content": ""} if content is None else data

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 Coalesce after accepting null assistant turns

When a resumed history contains user -> assistant(content: null) -> user, this new coercion turns the middle turn into an empty assistant message. The /v1/messages route then drops that empty assistant via _drop_empty_assistant_sentinels, but this path does not call _coalesce_consecutive_user_turns, so strict local chat templates can receive adjacent user turns and fail instead of the newly accepted resume payload working. Please either coalesce after the Anthropic conversion/drop step or preserve a safe placeholder for these null assistant turns.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch. The /v1/messages count and generation paths now run _coalesce_consecutive_user_turns after the empty-assistant drop, so a resumed user -> assistant(null) -> user history stays alternating and the strict GGUF chat template no longer 400s on non-alternating roles. Fixed in 91e9ad3 with a route-level test.

Comment thread studio/backend/models/inference.py Outdated
btype = (
block.get("type") if isinstance(block, dict) else getattr(block, "type", None)
)
if btype not in _KNOWN_ANTHROPIC_BLOCK_TYPES:

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 Reject non-string block types safely

For a malformed user content block where type is an unhashable value such as a list or dict, this membership test raises TypeError before normal field validation can report a 400-style validation error. Since this validator runs on raw request data, a bad client payload like {"role":"user","content":[{"type": []}]} can escape as an internal error; check that btype is a string before testing membership.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 91e9ad3. The membership test now guards isinstance(btype, str) first, so a block with an unhashable type like {"type": []} raises a clean validation error (400) instead of a TypeError that would surface as a 500. Added a test covering list, dict and int types.

Comment thread studio/backend/models/inference.py Outdated
Comment on lines +1633 to +1635
content = data.get("content")
if data.get("role") == "assistant":
return {**data, "content": ""} if content is None else data

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 Preserve required content validation for assistants

Because dict.get("content") returns None for both an explicit JSON null and a missing field, this normalizer now accepts malformed assistant messages that omit content entirely by injecting "". Those requests previously failed required-field validation, but now the empty assistant turn can be dropped and the model runs on a silently altered history; only coerce when the key is present and explicitly null.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 91e9ad3. The null-to-empty coercion now only triggers when the content key is present and explicitly null; an assistant turn that omits content entirely still fails required-field validation instead of being coerced to an empty string. Added a regression test.

danielhanchen and others added 2 commits July 9, 2026 07:33
…checks

- The /v1/messages count and generation paths now coalesce the adjacent user
  turns that dropping an empty or null assistant turn can leave behind, so a
  strict GGUF chat template no longer 400s on non-alternating roles.
- A user content block with a non-string type (list / dict) is rejected as a
  clean 400 instead of raising TypeError and escaping as a 500.
- The assistant null-to-empty coercion only applies to an explicit null; an
  assistant turn that omits content entirely still fails required-field
  validation instead of being silently coerced to an empty string.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: d5cdfac4a1

ℹ️ 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 Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: bbe74442f0

ℹ️ 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".

@wasimysaid
wasimysaid merged commit eb775d3 into main Jul 9, 2026
48 checks passed
@wasimysaid
wasimysaid deleted the fix-anthropic-content-blocks branch July 9, 2026 10:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants