Fix chat template: make user/assistant alternation check tool-aware

#2

Summary

This mirrors the upstream fix proposed in
mistralai/Devstral-Small-2-24B-Instruct-2512 (discussion #30).

The chat template rejects a valid multi-turn tool-use conversation in which a
user message follows a tool round (assistant tool call + tool result) without
an intervening assistant text message, e.g.:

user -> assistant(tool_calls) -> tool -> user

The alternation check counts user and assistant-without-tool_calls messages
and requires strict user/assistant alternation, silently skipping tool-call and
tool messages. This puts the follow-up user on the wrong parity and raises:

After the optional system message, conversation roles must alternate user and assistant roles except for tool calls and results.

OpenAI-compatible servers that use this template (e.g. mlx-lm) wrap the template
exception as an HTTP error, so this surfaces as confusing failures downstream
(e.g. HTTP 404 "model not found") during agent tool loops.

Fix

Make the check tool-aware: tool calls and tool results now reset the
alternation state instead of being skipped. A user (or assistant) turn may
follow a tool round, while genuinely malformed conversations (two consecutive
user messages, or two consecutive assistant text messages, with no tool
activity between) are still rejected. The error message and message rendering
are unchanged.

Ready to merge
This branch is ready to get merged automatically.

Sign up or log in to comment