Skip to content

fix(anthropic): handle mid-conversation system messages - #26773

Merged
JustinTong0323 merged 4 commits into
sgl-project:mainfrom
VarV0id:fix/anthropic-mid-conversation-system
Jun 21, 2026
Merged

JustinTong0323 merged 4 commits into
sgl-project:mainfrom
VarV0id:fix/anthropic-mid-conversation-system

Conversation

@VarV0id

@VarV0id VarV0id commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

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:

1 validation error: {'type': 'literal_error', 'loc': ('body', 'messages', N, 'role'), 'msg': 'Input should be ...'}

Additionally, the 'system' role was completely missing from the AnthropicMessage validation, causing any system messages to be rejected.

Root Cause

  1. Missing role: AnthropicMessage.role was defined as Literal["user", "assistant"] - excluding 'system'
  2. Mid-conversation system messages: Claude Code sends system messages after user/assistant messages, violating Anthropic's spec

Solution

  1. Add 'system' role to AnthropicMessage validation
  2. Add model_validator to extract mid-conversation system messages and move them to the top-level system field

The validator:

  • Extracts system messages from any position in the messages array
  • Appends them to existing system content
  • Preserves message order for non-system messages

Testing

Verified fix handles Claude Code's message format:

  • System messages at any position are accepted
  • Content is moved to the system field
  • No 400 errors on multi-turn conversations

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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.
@JustinTong0323
JustinTong0323 force-pushed the fix/anthropic-mid-conversation-system branch from 5c62d4c to d39655c Compare June 17, 2026 16:31
@JustinTong0323

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Jun 17, 2026
@JustinTong0323
JustinTong0323 force-pushed the fix/anthropic-mid-conversation-system branch from 044b17f to cf3772a Compare June 17, 2026 16:32
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.
@JustinTong0323
JustinTong0323 force-pushed the fix/anthropic-mid-conversation-system branch from b889f94 to becccbe Compare June 17, 2026 16:53

@JustinTong0323 JustinTong0323 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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) — a role: "system" turn in messages returns 200.
  • test_in_messages_system_role_folded_to_top_level — mid-conversation system is folded into the top-level system field, not left as a dialogue turn.
  • test_in_messages_system_role_merged_with_top_level — top-level system + an in-messages system turn are merged (top-level first).
  • test_top_level_system_only_is_unchanged — a request with only a top-level system (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``).
@JustinTong0323
JustinTong0323 force-pushed the fix/anthropic-mid-conversation-system branch from 1933ec7 to 4e020fe Compare June 17, 2026 19:45
@JustinTong0323

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

JustinTong0323 added a commit to JustinTong0323/sglang that referenced this pull request Jun 22, 2026
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
Chronostasys pushed a commit to MindLab-Research/sglang that referenced this pull request Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants