Repository navigation
fix(anthropic): handle mid-conversation system messages - #26773
JustinTong0323 merged 4 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request adds support for handling mid-conversation system messages in the Anthropic protocol by extracting them from the messages list and appending them to the top-level system field. It also updates the allowed roles in AnthropicMessage to include "system". A critical issue was identified where combining multiple system messages into a list of strings would cause a Pydantic validation error, as the system field expects a string or a list of AnthropicContentBlocks. The reviewer suggested joining the system messages with a double newline into a single string to resolve this.
Claude Code and other clients may send system messages mid-conversation
(after user/assistant messages), which violates Anthropic's API spec.
This fixes two issues:
1. Adds 'system' to the AnthropicMessage role Literal (was missing)
2. Adds a model_validator that extracts mid-conversation system messages
and moves them to the top-level 'system' field
This allows sglang to handle non-standard message ordering while
maintaining proper API structure for downstream processing.
Fixes 400 error: "1 validation error: {'type': 'literal_error', 'loc':
('body', 'messages', N, 'role'), 'msg': 'Input should be ...'}"
when Claude Code makes multi-turn requests.
5c62d4c to
d39655c
Compare
|
/tag-and-rerun-ci |
044b17f to
cf3772a
Compare
The validator collected system text fragments into a list and, when more than one was present, stored ``list[str]`` in the ``system`` field. That field is typed ``str | list[AnthropicContentBlock]``, so a ``list[str]`` failed validation and a request with both a top-level ``system`` and an in-messages system turn 400'd. Join the fragments into a single string instead.
b889f94 to
becccbe
Compare
JustinTong0323
left a comment
There was a problem hiding this comment.
Reviewed and updated this PR: rebased onto the latest main (resolved the merge conflicts), added test coverage, and fixed a bug the tests surfaced.
Conflict resolution: the AnthropicMessage.role change now uses Union[str, list[AnthropicContentBlock]] (main's post-rebase form) instead of the old str | list[...].
Tests added (test/registered/unit/entrypoints/anthropic/test_serving.py + test_anthropic_server.py):
test_in_messages_system_role(endpoint, via the Anthropic SDK as a real client would) — arole: "system"turn inmessagesreturns 200.test_in_messages_system_role_folded_to_top_level— mid-conversation system is folded into the top-levelsystemfield, not left as a dialogue turn.test_in_messages_system_role_merged_with_top_level— top-levelsystem+ an in-messages system turn are merged (top-level first).test_top_level_system_only_is_unchanged— a request with only a top-levelsystem(no in-messages system) is untouched, guarding the common multi-turn path.
Bug fix (join folded system text into a string): the validator collected system text fragments into a list[str] and stored it in system when more than one was present. system is typed str | list[AnthropicContentBlock], so list[str] failed validation and a request carrying both a top-level system and an in-messages system turn 400'd. The fragments are now joined into a single string. Verified end-to-end with the Anthropic SDK against a served model.
Behavior: unchanged for any request without an in-messages role: "system" (no system / top-level str / top-level block list) — the validator leaves system and messages untouched. Only requests that previously 400'd (system role in messages) are now accepted.
Adopted @alexnails's suggestion to use the Anthropic SDK in the endpoint test (it's already a core dependency, anthropic>=0.20.0).
The ``mode="before"`` validator assumed ``messages`` were raw dicts (the HTTP
path). When the request is built programmatically with ``AnthropicMessage``
objects — as ``handle_count_tokens`` does — ``msg.get("role")`` raised
``AttributeError: 'AnthropicMessage' object has no attribute 'get'`` and the
request 400'd. Normalize each message (and any existing ``system`` block) to a
dict via ``model_dump()`` before reading it, so the validator handles both the
dict and the object paths.
Adds ``test_validator_handles_constructed_message_objects`` to guard the
object path (the existing tests exercise the dict path via ``model_validate``).
1933ec7 to
4e020fe
Compare
|
/rerun-failed-ci |
PR sgl-project#26773 fixed the hard 400 on mid-conversation role:"system" by hoisting every such turn into the top-level system field. That breaks inline-capable chat templates (GLM, Kimi, Qwen3): the rotating system reminder Claude Code emits each turn gets moved to the front, forking the prefix cache and forcing a full re-prefill every turn, and it silently rewrites the request's intended structure. Replace the unconditional hoisting validator with chat-template auto-detection (vLLM#46025 precedent): render a [system, user, system, user] probe at AnthropicServing init; if the template raises (e.g. Qwen's loop.first guard) merge into the leading system block, otherwise pass the system turn through at its original position. Detection runs in the serving layer where the tokenizer is reachable, and covers both /v1/messages and count_tokens. Fixes sgl-project#28883
…26773) Co-authored-by: Xinyuan Tong <[email protected]>
Problem
Claude Code and other clients send system messages mid-conversation (after user/assistant messages), which violates Anthropic's API spec. This causes 400 errors:
Additionally, the 'system' role was completely missing from the AnthropicMessage validation, causing any system messages to be rejected.
Root Cause
AnthropicMessage.rolewas defined asLiteral["user", "assistant"]- excluding 'system'Solution
systemfieldThe validator:
Testing
Verified fix handles Claude Code's message format:
Fixes errors when Claude Code makes requests through arch-router-cuda to sglang.
CI States
Latest PR Test (Base): 🚫 Run #27715250341
Latest PR Test (Extra): ❌ Run #27715248707