Skip to content

fix(anthropic): detect-and-passthrough mid-conversation system messages - #28906

Merged
hnyls2002 merged 5 commits into
sgl-project:mainfrom
JustinTong0323:xinyuan/anthropic-inline-system
Jun 26, 2026
Merged

hnyls2002 merged 5 commits into
sgl-project:mainfrom
JustinTong0323:xinyuan/anthropic-inline-system

Conversation

@JustinTong0323

@JustinTong0323 JustinTong0323 commented Jun 22, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

PR #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.

This replaces the unconditional hoisting validator with chat-template auto-detection (the approach vLLM converged on in vllm-project/vllm#46025): probe the template at AnthropicServing init; merge into the leading system block only when the template can't render mid-conversation system inline, otherwise pass the system turn through at its original position.

Detection runs in template_detection.py (alongside detect_reasoning_pattern / detect_*_parser), where the tokenizer is reachable. The protocol-layer model_validator that used to hoist is removed — it couldn't see the template. Both /v1/messages and /v1/messages/count_tokens go through the same conversion path.

Fixes #28883.

Changes

  • protocol.py: drop the move_mid_conversation_system_messages model_validator. The "system" role stays in AnthropicMessage.role (the correct half of fix(anthropic): handle mid-conversation system messages #26773).
  • managers/template_detection.py: new detect_inline_system_support(chat_template) -> bool — renders a [system, user, system, user] probe and requires the second system's sentinel text to appear in the output. Returns False (merge) when the template raises (e.g. a system-first guard) or silently drops the non-leading system turn. Explicit import jinja2/jinja2.ext/jinja2.sandbox.
  • serving.py: __init__ calls self._merge_inline_system = not detect_inline_system_support(self._chat_template()); _convert_to_chat_completion_request merges inline system into the leading block when _merge_inline_system is True, otherwise leaves it in place. handle_count_tokens reuses the same path.
  • Tests: the four fix(anthropic): handle mid-conversation system messages #26773 unit tests rewritten detection-aware (merge + passthrough), plus TestDetectInlineSystemSupport covering guarded / inline / silent-drop / missing-template cases.

Why the sentinel check

A render that doesn't raise isn't proof the template renders mid-conversation system: some templates render only the leading system turn and silently ignore later role:"system" messages. The probe asserts the second system's sentinel text appears in the rendered prompt, so such templates fall back to merging instead of dropping the instruction.

Real-world impact: Claude Code "steer" prompt

A user reported that Claude Code's mid-conversation "steer" (type a message while a tool is running, press Enter — it's queued and read after the current action completes) appeared to do nothing when the backend was sglang:latest. Tracing the actual /v1/messages body revealed three distinct failure modes across sglang versions, all stemming from how role:"system" messages are handled:

1. sglang:latest (0.5.13.post1, pre-#26773) — hard 400. AnthropicMessage.role was Literal["user","assistant"] with no "system", so a mid-conversation role:"system" turn fails Pydantic validation at the route layer and the entire request is rejected with 400 Input should be 'user' or 'assistant'. The model never sees the steer; from the user's side the feature is dead. (This also blocks the SessionStart hook injection, which is itself a ~40K-char role:"system" message listing agent types + skills.)

2. sglang:dev (#26773 hoist) — prefix-cache fork. #26773 added "system" to the role Literal (fixing the 400) but also added move_mid_conversation_system_messages, a model_validator that strips every role:"system" turn out of messages and concatenates its text into the top-level system field. The steer text reaches the model, but its mid-conversation position is lost (it becomes a leading global system instruction), and — worse for the multi-turn agent workload this feature targets — the top-level system now changes every turn (each steer has different text), so the radix/prefix cache is invalidated and the long tool+history prefix is re-prefilled from scratch each turn. This is the regression #28883 reported.

3. This PR (detect-and-passthrough) — correct. role:"system" stays at its original position in messages; the top-level system field is untouched, so the cached prefix remains stable across turns, and the steer is read by the model at the point the client intended (after the preceding tool_result, before the next assistant decision).

Evidence (interactive Claude Code v2.1.185 trace)

Captured by patching AnthropicServing.handle_messages to dump the raw /v1/messages body, then driving a real interactive Claude Code session against Qwen/Qwen3.6-35B-A3B-FP8 TP1 + EAGLE spec v2 + --mamba-scheduler-strategy extra_buffer on an H200 devbox.

The steer (user typed sleep 5s while Bash(sleep 10) was running) arrives on the wire as:

{"role": "system", "content": "The user sent a new message while you were working:
sleep 5s

IMPORTANT: After completing your current task, you MUST address the user's message above. Do not ignore it."}

placed in messages immediately after the preceding tool_result — not as role:"user". (A steer typed after a turn completes, with no tool in flight, does arrive as role:"user"; both shapes need to be handled correctly.)

Across an 11-request interactive trace, role:"system" turns appear at messages indices [1, 4, 9] in the raw body. With this PR applied:

raw system indices parsed system indices top-level system
stock sglang:dev (hoist) [1, 4, 9] [] (stripped) grows each turn (forks cache)
+ this PR (passthrough) [1, 4, 9] [1, 4, 9] (unchanged) stable

The model follows the steer correctly (e.g. a continue to sleep 5s steer issued mid-sleep 12 is executed), and #cached-token stays high across turns (30K+ prefix reused), confirming the cache is preserved.

Verification

  • Unit: test/registered/unit/entrypoints/anthropic/test_serving.py — 59 passed.
  • Detection probed against real model chat templates on an H200 devbox:
    • zai-org/GLM-5.2-FP8 → passthrough ✅
    • Qwen/Qwen2.5-7B-Instruct → passthrough ✅
    • Qwen/Qwen3-8B → passthrough ✅
    • a guarded template that raise_exceptions → merge ✅
    • a silent-drop template (renders only leading system) → merge ✅
  • e2e on GLM-5.2-FP8 TP8: mid-conversation role:"system" does not 400, returns correct responses (Paris / BLUE-7421), two-turn prompt-token delta small (41→68), indicating prefix reuse.

CI States

Latest PR Test (Base): ✅ Run #28086590088
Latest PR Test (Extra): ❌ Run #28086589942

@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 refactors how mid-conversation system messages are handled in the Anthropic API adapter. Instead of unconditionally folding mid-conversation system messages into the top-level system block during request validation, it introduces an auto-detection mechanism in the serving layer. This mechanism probes the chat template to determine if it natively supports inline system messages (preserving the prefix cache for multi-turn agent workloads) or if it requires system-first ordering (in which case they are merged). Feedback suggests leveraging the tokenizer's native apply_chat_template method for the probe when available, as it already registers correct custom filters and globals (like raise_exception), and registering a dummy raise_exception helper in the fallback Jinja environment to prevent false positives.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +205 to +207
self._merge_inline_system = self._detect_merge_inline_system(
self._chat_template()
)

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.

medium

Instead of manually rendering the template string with a bare Jinja environment, we should leverage the tokenizer's native apply_chat_template method when available. This is much more robust because the tokenizer's environment already has all the correct custom filters and globals (such as raise_exception or other model-specific extensions) registered, preventing false positives where a valid template fails the probe due to missing environment setup.

        tokenizer_manager = getattr(openai_serving_chat, "tokenizer_manager", None)
        tokenizer = getattr(tokenizer_manager, "tokenizer", None) if tokenizer_manager else None
        self._merge_inline_system = self._detect_merge_inline_system(
            self._chat_template(),
            tokenizer=tokenizer,
        )

@JustinTong0323
JustinTong0323 force-pushed the xinyuan/anthropic-inline-system branch 2 times, most recently from b480b94 to 045f838 Compare June 22, 2026 08:47
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
@JustinTong0323
JustinTong0323 force-pushed the xinyuan/anthropic-inline-system branch from 045f838 to 8a1c0d8 Compare June 22, 2026 10:27
detect_inline_system_support belongs with the other chat-template
detection helpers (detect_reasoning_pattern, detect_*_parser), not as a
staticmethod on AnthropicServing. Serving now imports and calls it;
semantics flipped to 'supported' (True=inline/passthrough, False=merge).
Merely rendering without raising isn't sufficient: some templates render
only the leading system turn and silently ignore later role:"system"
messages. The probe now asserts the second system's sentinel text appears
in the rendered prompt, so such templates fall back to merging instead of
dropping mid-conversation system instructions.
@JustinTong0323
JustinTong0323 force-pushed the xinyuan/anthropic-inline-system branch from b3587af to 5710448 Compare June 22, 2026 13:59
@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Jun 22, 2026
@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

2 similar comments
@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

@lioZ129

lioZ129 commented Jun 23, 2026

Copy link
Copy Markdown

Hi! I hit mid-conversation issues with Claude Code on SGLang. Happy to help test if there’s anything still needed for this PR. Thanks!

@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

2 similar comments
@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

1 similar comment
@JustinTong0323

Copy link
Copy Markdown
Collaborator Author

/rerun-failed-ci

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.

[Anthropic] Mid-conversation system messages are hoisted to top-level, forking the prefix cache on inline-capable templates

3 participants