Chat template rejects consecutive leading system messages ("System message must be at the beginning.")

#75
by jlapenna - opened

Summary

The chat template raises System message must be at the beginning. for every system message except messages[0]. That includes a second system message that directly follows the first. A request that starts with several system messages is valid OpenAI Chat Completions input, and agent clients send them. On vLLM and SGLang the request fails with HTTP 400 before it reaches the model.

Where

The rule is in chat_template.jinja (the same string is in tokenizer_config.json → chat_template), lines 104-106 at de4b8e4:

{%- if message.role == "system" %}
    {%- if not loop.first %}
        {{- raise_exception('System message must be at the beginning.') }}

Only messages[0] is rendered into the system block (lines 69-74 and 77-86). This exact template also ships, byte-identical, in Qwen/Qwen3.8-Flash-Next-FP8 and nvidia/Qwen3.8-Flash-Next-NVFP4 (fc694b5).

Real-world case

OpenCode 1.19.3 sends one system message for each entry in experimental.chat.system.transform (instruction and plugin sources). One request captured between OpenCode and the gateway had roles ["system", "system", "user", "user"]. The setup was vllm serve nvidia/Qwen3.8-Flash-Next-NVFP4 with no --chat-template override, behind LiteLLM:

HTTP 400  litellm.BadRequestError: OpenAIException - System message must be at the beginning.

When the same text is merged into one system message, the request returns HTTP 200.

Offline reproduction (transformers 5.20.1)

from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained("Qwen/Qwen3.8-Flash-Next")
messages = [
    {"role": "system", "content": "You are a coding agent."},
    {"role": "system", "content": "Project rules: run tests before committing."},
    {"role": "user", "content": "Hello"},
]
try:
    tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
except Exception as e:
    print(f"{type(e).__name__}: {e}")
TemplateError: System message must be at the beginning.

Proposed fix

The fix is in PR #76. It collects the contiguous run of leading system messages, trims each one as the template already does, skips any that are empty, joins them with "\n\n", and renders the result where messages[0]'s content is rendered today. The output keeps a single <|im_start|>system block. For conversations with zero or one system message the output is byte-identical, and the tool-definition block does not change.

The script below runs the original and fixed templates through plain jinja2, set up the way transformers configures it:

repro_leading_system.py
"""Render the Qwen3.8-Flash-Next chat template with consecutive leading system messages.

Usage: python repro_leading_system.py ORIGINAL.jinja [FIXED.jinja]

The Jinja environment matches transformers' chat-template renderer
(ImmutableSandboxedEnvironment, trim_blocks, lstrip_blocks, loopcontrols,
raise_exception, tojson). vLLM renders through the same transformers path.
"""

import json
import sys

from jinja2 import TemplateError
from jinja2.ext import loopcontrols
from jinja2.sandbox import ImmutableSandboxedEnvironment


def raise_exception(message):
    raise TemplateError(message)


def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
    return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys)


def load(path):
    env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True, extensions=[loopcontrols])
    env.filters["tojson"] = tojson
    env.globals["raise_exception"] = raise_exception
    with open(path) as f:
        return env.from_string(f.read())


def render(template, messages, tools=None):
    try:
        return template.render(messages=messages, tools=tools, add_generation_prompt=True)
    except TemplateError as e:
        return f"TemplateError: {e}"


TOOLS = [{"type": "function", "function": {"name": "read", "description": "Read a file",
          "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}}]

# Shape OpenCode 1.19.3 sends: one system message per system-transform entry.
TWO_SYSTEM = [
    {"role": "system", "content": "You are a coding agent."},
    {"role": "system", "content": "Project rules: run tests before committing."},
    {"role": "user", "content": "Hello"},
]

# Inputs the original template already accepts (or rejects); the fix must not change them.
TOOL_TURN = [
    {"role": "user", "content": "Read a.txt"},
    {"role": "assistant", "content": "", "reasoning_content": "Need to read.",
     "tool_calls": [{"type": "function", "function": {"name": "read", "arguments": {"path": "a.txt"}}}]},
    {"role": "tool", "content": "hello"},
]
UNCHANGED = {
    "no system": [{"role": "user", "content": "Hi"}],
    "one system": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "Hi"}],
    "empty system": [{"role": "system", "content": "  "}, {"role": "user", "content": "Hi"}],
    "one system + tool turn": [{"role": "system", "content": "Be brief."}] + TOOL_TURN,
    "system list content": [{"role": "system", "content": [{"type": "text", "text": "Be brief."}]},
                            {"role": "user", "content": "Hi"}],
    "system after user (still rejected)": [{"role": "system", "content": "A"}, {"role": "user", "content": "Hi"},
                                           {"role": "system", "content": "B"}, {"role": "user", "content": "Hi"}],
}


def main():
    original = load(sys.argv[1])
    fixed = load(sys.argv[2]) if len(sys.argv) > 2 else None

    for label, tools in (("no tools", None), ("with tools", TOOLS)):
        print(f"=== [system, system, user], {label}")
        print("--- original:")
        print(render(original, TWO_SYSTEM, tools))
        if fixed:
            print("--- fixed:")
            print(render(fixed, TWO_SYSTEM, tools))

    if fixed:
        print("=== previously handled inputs: original vs fixed")
        ok = True
        for name, messages in UNCHANGED.items():
            for tools in (None, TOOLS):
                same = render(original, messages, tools) == render(fixed, messages, tools)
                ok &= same
                print(f"{'identical' if same else 'DIFFERENT'}: {name}{' + tools' if tools else ''}")
        print("all identical" if ok else "REGRESSION")
        sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
Output: python repro_leading_system.py original.jinja fixed.jinja
=== [system, system, user], no tools
--- original:
TemplateError: System message must be at the beginning.
--- fixed:
<|im_start|>system
Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.

You are a coding agent.

Project rules: run tests before committing.<|im_end|>
<|im_start|>user
Hello<|im_end|>
<|im_start|>assistant
<think>

=== [system, system, user], with tools
--- original:
TemplateError: System message must be at the beginning.
--- fixed:
<|im_start|>system
Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.

# Tools

You have access to the following functions:

<tools>
{"type": "function", "function": {"name": "read", "description": "Read a file", "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}}
</tools>

If you choose to call a function ONLY reply in the following format with NO suffix:

<tool_call>
<function=example_function_name>
<parameter=example_parameter_1>
value_1
</parameter>
<parameter=example_parameter_2>
This is the value for the second parameter
that can span
multiple lines
</parameter>
</function>
</tool_call>

<IMPORTANT>
Reminder:
- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags
- Required parameters MUST be specified
- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after
- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls
</IMPORTANT>

You are a coding agent.

Project rules: run tests before committing.<|im_end|>
<|im_start|>user
Hello<|im_end|>
<|im_start|>assistant
<think>

=== previously handled inputs: original vs fixed
identical: no system
identical: no system + tools
identical: one system
identical: one system + tools
identical: empty system
identical: empty system + tools
identical: one system + tool turn
identical: one system + tool turn + tools
identical: system list content
identical: system list content + tools
identical: system after user (still rejected)
identical: system after user (still rejected) + tools
all identical

Out of scope: system messages after the conversation starts

A system message that comes after a user, assistant or tool message is still rejected. Some agent frameworks insert those mid-session. Whether they should become a later system turn, be merged into the first one, or stay rejected depends on how the model was trained, so that is the Qwen team's call. The PR leaves that behaviour unchanged.

Sign up or log in to comment