Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Keep Mistral Small 3.2 tool definitions in training rows (#13597)
Daniel Han44b55b81c6ad
diff --git a/tests/python/fixtures/mistral_small_3_2_tools_2025.jinja b/tests/python/fixtures/mistral_small_3_2_tools_2025.jinjanew file mode 100644index 00000000000..f4ee32d18e5--- /dev/null+++ b/tests/python/fixtures/mistral_small_3_2_tools_2025.jinja@@ -0,0 +1,158 @@+{#- Tool handling of the 2025 Unsloth Mistral Small 3.2 chat_template.jinja (date / default system prompt block trimmed). #}+{%- set default_system_message = "DEFAULT" %}++{{- bos_token }}++{%- if messages[0]['role'] == 'system' %}+ {%- if messages[0]['content'] is string %}+ {%- set system_message = messages[0]['content'] %}+ {%- elif messages[0]['content'] is iterable %}+ {%- set system_message = messages[0]['content'][0]['text'] %}+ {%- else %}+ {%- set system_message = messages[0]['content']|string %}+ {%- endif %}+ {%- set loop_messages = messages[1:] %}+{%- else %}+ {%- set system_message = default_system_message %}+ {%- set loop_messages = messages %}+{%- endif %}+{{- '[SYSTEM_PROMPT]' + system_message + '[/SYSTEM_PROMPT]' }}+++{#- Tool description appended ONLY to last user message. Edits made by Unsloth #}+{#- Tool description appended also if last message is tool. Edits made by Unsloth #}+{%- set tools_description = "" %}+{%- set has_tools = false %}+{#- Cannot use set append_tools_index = loop.index0 since temporary variable - must use namespace #}+{%- set ns = namespace(append_tools_index=0, append_tools=false) %}++{%- if tools is defined and tools is not none and tools|length > 0 %}++ {%- set has_tools = true %}+ {%- set tools_description = "[AVAILABLE_TOOLS]" + (tools | tojson) + "[/AVAILABLE_TOOLS]" %}++ {#- If User,Assistant,Tool,Tool we also need to append tools_description to last assistant WITHOUT tool_calls defined. Edits made by Unsloth #}+ {%- if (loop_messages|last)['role'] == 'tool' %}++ {#- Find last assistant WITHOUT tool_calls defined #}+ {%- set ns.append_tools = true %}+ {%- for message in loop_messages %}+ {%- if message['role'] == 'assistant' %}++ {#- Cannot use set append_tools_index = loop.index0 since temporary variable - must use namespace #}++ {%- if message['tool_calls'] is not defined or message['tool_calls'] is none %}+ {%- set ns.append_tools_index = loop.index0 %}+ {%- endif %}++ {%- endif %}+ {%- endfor %}++ {%- endif %}++{%- endif %}++{%- for message in loop_messages %}+ {%- if message['role'] == 'user' %}++ {%- if has_tools and loop.last %}+ {{- tools_description }}+ {%- endif %}++ {#- If directly called tools in first turn, prepend to user #}+ {%- if ns.append_tools and ns.append_tools_index == 0 %}+ {{- tools_description }}+ {%- endif %}++ {%- if message['content'] is string %}+ {{- '[INST]' + message['content'] + '[/INST]' }}+ {%- else %}+ {{- '[INST]' }}+ {%- for block in message['content'] %}+ {%- if block['type'] == 'text' %}++ {#- Original did not have content which is weird. Added by Un-sloth. #}+ {%- if block['text'] is defined %}+ {{- block['text'] }}+ {%- else %}+ {{- block['content'] }}+ {%- endif %}++ {%- elif block['type'] in ['image', 'image_url'] %}+ {{- '[IMG]' }}+ {%- else %}+ {{- raise_exception('Only text and image blocks are supported in message content!') }}+ {%- endif %}+ {%- endfor %}+ {{- '[/INST]' }}+ {%- endif %}++ {%- elif message['role'] == 'system' %}+ {%- if message['content'] is string %}+ {{- '[SYSTEM_PROMPT]' + message['content'] + '[/SYSTEM_PROMPT]' }}+ {%- elif message['content'] is iterable %}+ {{- '[SYSTEM_PROMPT]' + message['content'][0]['text'] + '[/SYSTEM_PROMPT]' }}+ {%- else %}+ {{- '[SYSTEM_PROMPT]' + message['content']|string + '[/SYSTEM_PROMPT]' }}+ {%- endif %}+++ {%- elif message['role'] == 'assistant' %}+ {%- if message['content'] is string %}+ {{- message['content'] }}+ {%- elif message['content'] is iterable %}+ {{- message['content'][0]['text'] }}+ {%- else %}+ {{- message['content']|string }}+ {%- endif %}++ {#- If User,Assistant,Tool,Tool we also need to append tools_description. Edits made by Unsloth #}++ {%- if has_tools and (loop.index0 == ns.append_tools_index) %}+ {{- eos_token }}+ {{- tools_description }}+ {%- endif %}++ {%- if message['tool_calls'] is defined and message['tool_calls'] is not none %}+ {%- for tool in message['tool_calls'] %}+ {%- if tool['id'] is not defined %}+ {{- raise_exception('Tool ID must be provided!') }}+ {%- endif %}+ {%- set tool_call_id = tool['id'] %}+ {%- if tool_call_id is not string or tool_call_id|length < 9 %}+ {{- raise_exception("Tool call IDs should be alphanumeric strings with length >= 9!") }}+ {%- endif %}+ {%- set arguments = tool['function']['arguments'] %}+ {%- if arguments is not string %}+ {%- set arguments = arguments|tojson %}+ {%- endif %}+ {#- Must list tool calls AFTER assistant. Edits made by Un-sloth #}+ {{- "[TOOL_CALLS]" + tool['function']['name'] + "[CALL_ID]" + tool_call_id + "[ARGS]" + arguments }}+ {%- endfor %}+ {%- endif %}++ {#- Must not add EOS if added tools_description. Unsloth edits. #}+ {%- if (loop.index0 != ns.append_tools_index) %}+ {{- eos_token }}+ {%- endif %}++ {%- elif message["role"] == "tool_results" or message["role"] == "tool" %}+ {%- if message.content is defined and message.content.content is defined %}+ {%- set content = message.content.content %}+ {%- else %}+ {%- set content = message.content %}+ {%- endif %}+ {%- if message['tool_call_id'] is not defined %}+ {{- raise_exception('tool_call_id must be provided!') }}+ {%- endif %}+ {%- set tool_call_id = message['tool_call_id'] %}+ {%- if tool_call_id is not string or tool_call_id|length < 9 %}+ {{- raise_exception("Tool call IDs should be alphanumeric strings with length >= 9!") }}+ {%- endif %}+ {{- "[TOOL_RESULTS]" + tool_call_id + "[TOOL_CONTENT]" + content|string + "[/TOOL_RESULTS]" }}++ {%- else %}+ {{- raise_exception('Only user, systemm assistant and tool roles are supported in the custom template made by Unsloth!') }}+ {%- endif %}+{%- endfor %}+{#- Copyright 2025-present Unsloth. Apache 2.0 License. #}\ No newline at end of filediff --git a/tests/python/test_mistral_tools_chat_template.py b/tests/python/test_mistral_tools_chat_template.pynew file mode 100644index 00000000000..12b2ef23603--- /dev/null+++ b/tests/python/test_mistral_tools_chat_template.py@@ -0,0 +1,157 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Mistral Small 3.2 tool definitions must survive training-shaped rows (unslothai/unsloth#3096).++The 2025 Unsloth template only emitted [AVAILABLE_TOOLS] when the conversation ended on a user or+tool turn, so every SFT row ending in an assistant reply silently dropped the tool list.+mistral_common places it before the last user message in both serving and finetuning mode.+"""++import copy+import json+from pathlib import Path++import pytest++import unsloth.tokenizer_utils as tu++jinja2 = pytest.importorskip("jinja2")++OLD = (Path(__file__).parent / "fixtures" / "mistral_small_3_2_tools_2025.jinja").read_text(+ encoding = "utf-8"+)+TOOLS = [+ {+ "type": "function",+ "function": {+ "name": "get_weather",+ "description": "Get weather",+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}},+ },+ }+]+TOOLS_TEXT = "[AVAILABLE_TOOLS]" + json.dumps(TOOLS) + "[/AVAILABLE_TOOLS]"+S = {"role": "system", "content": "sys"}+++def U(t):+ return {"role": "user", "content": t}+++def A(t):+ return {"role": "assistant", "content": t}+++def TC(i):+ call = {+ "id": i,+ "type": "function",+ "function": {"name": "get_weather", "arguments": {"city": "X"}},+ }+ return {"role": "assistant", "content": "", "tool_calls": [call]}+++def TR(i):+ return {"role": "tool", "tool_call_id": i, "content": "22C"}+++TRAIN = {+ "text reply": [S, U("q"), A("a")],+ "tool call, result, reply": [S, U("q"), TC("abc123def"), TR("abc123def"), A("a")],+ "ends in tool call": [S, U("q"), TC("abc123def")],+ "multi-turn": [S, U("hi"), A("hello"), U("q"), TC("abc123def"), TR("abc123def"), A("a")],+ "tool turn then plain turn": [+ S,+ U("q"),+ TC("abc123def"),+ TR("abc123def"),+ A("a"),+ U("thx"),+ A("np"),+ ],+}+SERVE = {+ "user": [S, U("q")],+ "after tool result": [S, U("q"), TC("abc123def"), TR("abc123def")],+ "multi-turn": [S, U("hi"), A("hello"), U("q")],+ "multi-turn after tool result": [+ S,+ U("hi"),+ A("hello"),+ U("q"),+ TC("abc123def"),+ TR("abc123def"),+ ],+ "after a full tool turn": [S, U("q"), TC("abc123def"), TR("abc123def"), A("a"), U("thx")],+}+++def render(template, messages, tools):+ env = jinja2.Environment(extensions = ["jinja2.ext.loopcontrols"])+ env.policies["json.dumps_kwargs"] = {"sort_keys": False}++ def raise_exception(msg):+ raise jinja2.exceptions.TemplateError(msg)++ return env.from_string(template).render(+ messages = copy.deepcopy(messages),+ tools = tools,+ bos_token = "<s>",+ eos_token = "</s>",+ raise_exception = raise_exception,+ )+++def expected_tools_position(text):+ # mistral_common: the tool list sits immediately before the last [INST].+ return text.count(TOOLS_TEXT) == 1 and text.rfind("[INST]") == text.find(TOOLS_TEXT) + len(+ TOOLS_TEXT+ )+++NEW = tu._rewrite_mistral_tools_chat_template(OLD)+++def test_rewrite_applies_and_is_idempotent():+ assert NEW is not OLD+ assert "append_tools" not in NEW+ assert tu._rewrite_mistral_tools_chat_template(NEW) is NEW++[email protected]("name", list(TRAIN))+def test_training_rows_keep_tools(name):+ assert TOOLS_TEXT not in render(OLD, TRAIN[name], TOOLS)+ assert expected_tools_position(render(NEW, TRAIN[name], TOOLS))++[email protected]("name", list(SERVE))+def test_serving_prompts_unchanged(name):+ old = render(OLD, SERVE[name], TOOLS)+ assert old == render(NEW, SERVE[name], TOOLS)+ assert expected_tools_position(old)++[email protected]("messages", list(TRAIN.values()) + list(SERVE.values()))+def test_no_tools_unchanged(messages):+ assert render(OLD, messages, None) == render(NEW, messages, None)+++def test_other_templates_untouched():+ for template in (+ None,+ "",+ "{{ messages }}",+ OLD.replace("{#- If directly called tools in first turn, prepend to user #}", ""),+ ):+ assert tu._rewrite_mistral_tools_chat_template(template) is template+++def test_fixes_processor_and_inner_tokenizer():+ class Obj:+ pass++ proc, inner = Obj(), Obj()+ proc.tokenizer, proc.chat_template, inner.chat_template = inner, OLD, OLD+ tu._fix_mistral_tools_chat_template(proc)+ assert proc.chat_template == NEW and inner.chat_template == NEWdiff --git a/unsloth/tokenizer_utils.py b/unsloth/tokenizer_utils.pyindex 9b0cb93f85d..f16ea6d6605 100644--- a/unsloth/tokenizer_utils.py+++ b/unsloth/tokenizer_utils.py@@ -346,6 +346,100 @@ def _repair_tokenizer_backend_from_json(return tokenizer+def _literal_regex(text):+ return r"\s*".join(re.escape(part) for part in text.split())+++# Unsloth's 2025 Mistral Small 3.2 template emitted [AVAILABLE_TOOLS] only when the last message was a+# user or tool turn, so training rows ending in an assistant reply lost the tool list. mistral_common+# (serving and finetuning) puts it before the last user message; rewrite to that (unslothai/unsloth#3096).+_MISTRAL_TOOLS_REWRITES = (+ (+ re.compile(+ _literal_regex(+ "{#- Tool description appended ONLY to last user message. Edits made by Unsloth #}"+ )+ + r".*?(?="+ + _literal_regex(+ "{%- for message in loop_messages %} {%- if message['role'] == 'user' %}"+ )+ + r")",+ re.S,+ ),+ '{%- set tools_description = "" %}\n'+ "{%- set has_tools = false %}\n"+ "{%- set ns = namespace(last_user_index=-1) %}\n"+ "{%- if tools is defined and tools is not none and tools|length > 0 %}\n"+ " {%- set has_tools = true %}\n"+ ' {%- set tools_description = "[AVAILABLE_TOOLS]" + (tools | tojson) + "[/AVAILABLE_TOOLS]" %}\n'+ " {%- for message in loop_messages %}\n"+ " {%- if message['role'] == 'user' %}\n"+ " {%- set ns.last_user_index = loop.index0 %}\n"+ " {%- endif %}\n"+ " {%- endfor %}\n"+ "{%- endif %}\n\n",+ ),+ (+ re.compile(+ _literal_regex(+ "{%- if has_tools and loop.last %} {{- tools_description }} {%- endif %} "+ "{#- If directly called tools in first turn, prepend to user #} "+ "{%- if ns.append_tools and ns.append_tools_index == 0 %} {{- tools_description }} {%- endif %}"+ )+ ),+ "{%- if has_tools and loop.index0 == ns.last_user_index %}\n"+ " {{- tools_description }}\n"+ " {%- endif %}",+ ),+ (+ re.compile(+ _literal_regex(+ "{#- If User,Assistant,Tool,Tool we also need to append tools_description. Edits made by Unsloth #} "+ "{%- if has_tools and (loop.index0 == ns.append_tools_index) %} {{- eos_token }} {{- tools_description }} {%- endif %}"+ )+ + r"\s*"+ ),+ "",+ ),+ (+ re.compile(+ _literal_regex(+ "{#- Must not add EOS if added tools_description. Unsloth edits. #} "+ "{%- if (loop.index0 != ns.append_tools_index) %} {{- eos_token }} {%- endif %}"+ )+ ),+ "{{- eos_token }}",+ ),+)+++def _rewrite_mistral_tools_chat_template(template):+ if not isinstance(template, str) or "ns.append_tools_index" not in template:+ return template+ new = template+ for pattern, replacement in _MISTRAL_TOOLS_REWRITES:+ new, n = pattern.subn(lambda _: replacement, new)+ if n != 1:+ return template+ if "append_tools" in new:+ return template+ try:+ import jinja2+ jinja2.Environment(extensions = ["jinja2.ext.loopcontrols"]).parse(new)+ except Exception:+ return template+ return new+++def _fix_mistral_tools_chat_template(tokenizer):+ for obj in _tokenizer_objects(tokenizer):+ template = getattr(obj, "chat_template", None)+ new = _rewrite_mistral_tools_chat_template(template)+ if new is not template:+ obj.chat_template = new+ return tokenizer++def _apply_post_load_tokenizer_fixes(tokenizer,fix_tokenizer = True,@@ -361,6 +455,7 @@ def _apply_post_load_tokenizer_fixes(if not fix_tokenizer:return tokenizertokenizer = _fix_gemma4_base_bos_token(tokenizer, config = config)+ tokenizer = _fix_mistral_tools_chat_template(tokenizer)return _fix_post_load_chat_template(tokenizer)@@ -998,6 +1093,8 @@ def load_correct_tokenizer()pass+ if fix_tokenizer:+ chat_template = _rewrite_mistral_tools_chat_template(chat_template)tokenizer.chat_template = chat_template# Saving restores sentencepiece assets from the repo name alone, which carries no branch, so stamp it for the save path. Imported late to break a circular import.from .models.loader_utils import _mark_loaded_revision