Repository navigation
Studio /v1/messages: accept thinking and unknown content blocks - #7017
Conversation
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.
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
https://github.com/unslothai/unsloth/blob/b706557c52a156d1d5de8d08987f5a90e97b9542/temp_err#L1
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".
| # 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| return data | ||
| content = data.get("content") | ||
| if data.get("role") == "assistant": | ||
| return {**data, "content": ""} if content is None else data |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| btype = ( | ||
| block.get("type") if isinstance(block, dict) else getattr(block, "type", None) | ||
| ) | ||
| if btype not in _KNOWN_ANTHROPIC_BLOCK_TYPES: |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| content = data.get("content") | ||
| if data.get("role") == "assistant": | ||
| return {**data, "content": ""} if content is None else data |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Problem
Resuming a Claude Code session against Studio fails with:
The Anthropic-compatible
/v1/messagesendpoint models a message'scontentasUnion[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 carrythinking(extended thinking) blocks, and sometimes anullcontent for a tool-only turn; both trip this and return a 400. The...content.strin the message is just the first half of the union error. Reproduced against the model: athinkingblock,null, and a bare block dict each produce that exact error, while a plain text list passes.Fix
AnthropicUnknownBlockfallback to the content-block union: any block whosetypeis not one of the four known ones (text/image/tool_use/tool_result) is accepted verbatim. Atypevalidator rejects the known types in the fallback, so a known block still parses as its typed model and a malformed known block (e.g. atool_usemissingid) still 400s cleanly instead of being swallowed.nullmessage content (andtool_resultcontent) to"", so the converter'sfor block in contentstays safe.anthropic_messages_to_openaialready ignores block types it does not translate, so athinkingblock 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:thinking+text+tool_useand a followingnull-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.tool_use(missingid) still raises.Existing
test_anthropic_messages.py(100), thinking-translation, message-content, tool-empty-content, and compaction suites pass unchanged.