Repository navigation
fix(anthropic): detect-and-passthrough mid-conversation system messages - #28906
Conversation
There was a problem hiding this comment.
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.
| self._merge_inline_system = self._detect_merge_inline_system( | ||
| self._chat_template() | ||
| ) |
There was a problem hiding this comment.
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,
)b480b94 to
045f838
Compare
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
045f838 to
8a1c0d8
Compare
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.
b3587af to
5710448
Compare
|
/tag-and-rerun-ci |
|
/rerun-failed-ci |
|
/rerun-failed-ci |
2 similar comments
|
/rerun-failed-ci |
|
/rerun-failed-ci |
|
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! |
|
/rerun-failed-ci |
2 similar comments
|
/rerun-failed-ci |
|
/rerun-failed-ci |
|
/rerun-failed-ci |
1 similar comment
|
/rerun-failed-ci |
Summary
PR #26773 fixed the hard 400 on mid-conversation
role:"system"by hoisting every such turn into the top-levelsystemfield. 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
AnthropicServinginit; 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(alongsidedetect_reasoning_pattern/detect_*_parser), where the tokenizer is reachable. The protocol-layermodel_validatorthat used to hoist is removed — it couldn't see the template. Both/v1/messagesand/v1/messages/count_tokensgo through the same conversion path.Fixes #28883.
Changes
protocol.py: drop themove_mid_conversation_system_messagesmodel_validator. The"system"role stays inAnthropicMessage.role(the correct half of fix(anthropic): handle mid-conversation system messages #26773).managers/template_detection.py: newdetect_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. ReturnsFalse(merge) when the template raises (e.g. a system-first guard) or silently drops the non-leading system turn. Explicitimport jinja2/jinja2.ext/jinja2.sandbox.serving.py:__init__callsself._merge_inline_system = not detect_inline_system_support(self._chat_template());_convert_to_chat_completion_requestmerges inline system into the leading block when_merge_inline_systemis True, otherwise leaves it in place.handle_count_tokensreuses the same path.TestDetectInlineSystemSupportcovering 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
systemturn and silently ignore laterrole:"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/messagesbody revealed three distinct failure modes across sglang versions, all stemming from howrole:"system"messages are handled:1.
sglang:latest(0.5.13.post1, pre-#26773) — hard 400.AnthropicMessage.rolewasLiteral["user","assistant"]with no"system", so a mid-conversationrole:"system"turn fails Pydantic validation at the route layer and the entire request is rejected with400 Input should be 'user' or 'assistant'. The model never sees the steer; from the user's side the feature is dead. (This also blocks theSessionStarthook injection, which is itself a ~40K-charrole:"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 addedmove_mid_conversation_system_messages, amodel_validatorthat strips everyrole:"system"turn out ofmessagesand concatenates its text into the top-levelsystemfield. 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-levelsystemnow 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 inmessages; the top-levelsystemfield 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 precedingtool_result, before the next assistant decision).Evidence (interactive Claude Code v2.1.185 trace)
Captured by patching
AnthropicServing.handle_messagesto dump the raw/v1/messagesbody, then driving a real interactive Claude Code session againstQwen/Qwen3.6-35B-A3B-FP8TP1 + EAGLE spec v2 +--mamba-scheduler-strategy extra_bufferon an H200 devbox.The steer (user typed
sleep 5swhileBash(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
messagesimmediately after the precedingtool_result— not asrole:"user". (A steer typed after a turn completes, with no tool in flight, does arrive asrole:"user"; both shapes need to be handled correctly.)Across an 11-request interactive trace,
role:"system"turns appear atmessagesindices[1, 4, 9]in the raw body. With this PR applied:systemindicessystemindicessystemsglang:dev(hoist)[1, 4, 9][](stripped)[1, 4, 9][1, 4, 9](unchanged)The model follows the steer correctly (e.g. a
continue to sleep 5ssteer issued mid-sleep 12is executed), and#cached-tokenstays high across turns (30K+ prefix reused), confirming the cache is preserved.Verification
test/registered/unit/entrypoints/anthropic/test_serving.py— 59 passed.zai-org/GLM-5.2-FP8→ passthrough ✅Qwen/Qwen2.5-7B-Instruct→ passthrough ✅Qwen/Qwen3-8B→ passthrough ✅raise_exceptions → merge ✅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