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
Studio: let Gemma 4 GGUF models think after a tool call (#13097)
Nilay9e5d03bdb4e7
diff --git a/studio/backend/assets/chat_templates/gemma-4-edge.jinja b/studio/backend/assets/chat_templates/gemma-4-edge.jinjaindex 74fa73ddd32..0c80286b55b 100644--- a/studio/backend/assets/chat_templates/gemma-4-edge.jinja+++ b/studio/backend/assets/chat_templates/gemma-4-edge.jinja@@ -1,17 +1,4 @@-{#-- Gemma 4 chat template (E2B / E4B edge variant), vendored for Unsloth Studio.- Source: google/gemma-4-31B-it HF discussion/PR #118 (adds the preserve_thinking- flag plus null-rendering, string-arguments validation, balanced turn tags, empty- messages handling, and OpenAI image_url/input_audio aliases).- Unsloth-local changes vs PR #118:- 1. preserve_thinking defaults to false (see SETUP block below).- 2. The empty "<|channel>thought\n<channel|>" block on enable_thinking=false is- NOT emitted. Google ships a distinct template for E2B/E4B (google/gemma-4-E2B-it,- google/gemma-4-E4B-it) that omits it; only the 12b/26B-A4B/31B family emits it.- This file matches the E2B/E4B behavior; gemma-4.jinja keeps the larger-model one.- Applied to unsloth/gemma-4-E2B-it-GGUF and unsloth/gemma-4-E4B-it-GGUF so the- embedded GGUF template does not need re-downloading.--#}+{# Google Gemma 4 template for E2B/E4B, which omit empty thought blocks when thinking is off. #}{%- macro format_parameters(properties, required, filter_keys=false) -%}{%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%}{%- set ns = namespace(found_first=false) -%}@@ -188,17 +175,13 @@{{- '<tool_response|>' -}}{%- endmacro -%}-{#- ===== SETUP ===== -#}{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%}{%- set loop_messages = messages -%}{%- set enable_thinking = enable_thinking | default(false) -%}-{#- Unsloth Studio: preserve_thinking defaults OFF (upstream PR #118 defaults true). -#}{%- set preserve_thinking = preserve_thinking | default(false) -%}{{- bos_token -}}-{#- Handle System/Tool Definitions Block -#}{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%}{{- '<|turn>system\n' -}}- {#- Inject Thinking token at the very top of the FIRST system turn -#}{%- if enable_thinking -%}{{- '<|think|>\n' -}}{%- set ns.prev_message_type = 'think' -%}@@ -232,21 +215,19 @@{%- endif -%}{%- endfor -%}-{#- Loop through messages -#}{%- for message in loop_messages -%}{%- if message['role'] != 'tool' -%}{%- set ns.prev_message_type = None -%}{%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}- {#- Detect continuation using tracked state - O(1) instead of O(n) backward scan -#}+ {#- tracked role state avoids an O(n) backward scan -#}{%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%}{%- if not continue_same_model_turn -%}{{- '<|turn>' + role + '\n' }}{%- endif -%}- {#- Render reasoning/reasoning_content as thinking channel (tool-call turns only) -#}{%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%}- {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or preserve_thinking -%}- {%- if thinking_text and thinking_gate and message.get('tool_calls') -%}+ {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%}+ {%- if thinking_text and thinking_gate -%}{{- '<|channel>thought\n' + thinking_text + '\n<channel|>' -}}{%- endif -%}@@ -357,7 +338,6 @@{{- captured_content -}}{%- set has_content = captured_content | trim | length > 0 -%}- {#- Forward-scan: find next non-tool message role for continuation detection -#}{%- set next_nt = namespace(role=None, found=false) -%}{%- for j in range(loop.index0 + 1, loop_messages | length) -%}{%- if not next_nt.found -%}@@ -371,19 +351,18 @@{%- set continues_into_next = (role == 'model'and next_nt.role == 'assistant'- and not message.get('tool_calls')- and not ns_tr_out.flag+ and (not message.get('tool_calls') or ns_tr_out.flag)) -%}{%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%}{{- '<|tool_response>' -}}{%- elif continues_into_next -%}{{- '\n' -}}- {%- elif not (ns_tr_out.flag and not has_content) -%}+ {%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%}{{- '<turn|>\n' -}}+ {%- set ns.prev_message_type = None -%}{%- endif -%}- {#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#}{%- set ns.prev_non_tool_role = message['role'] -%}{%- endif -%}{%- endfor -%}@@ -391,7 +370,7 @@{%- if add_generation_prompt -%}{%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}{{- '<|turn>model\n' -}}+ {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%}+ {{- '<|channel>thought\n' -}}{%- endif -%}- {#- E2B/E4B do NOT emit an empty thought block when enable_thinking is false- (unlike the 12b/26B-A4B/31B family); see header. -#}{%- endif -%}diff --git a/studio/backend/assets/chat_templates/gemma-4.jinja b/studio/backend/assets/chat_templates/gemma-4.jinjaindex cc5f98065fa..fe0f4ba6f36 100644--- a/studio/backend/assets/chat_templates/gemma-4.jinja+++ b/studio/backend/assets/chat_templates/gemma-4.jinja@@ -1,12 +1,4 @@-{#-- Gemma 4 chat template, vendored for Unsloth Studio.- Source: google/gemma-4-31B-it HF discussion/PR #118 (adds the preserve_thinking- flag plus null-rendering, string-arguments validation, balanced turn tags, empty- messages handling, and OpenAI image_url/input_audio aliases).- Unsloth-local change: preserve_thinking defaults to false (see SETUP block below).- Applied to unsloth/gemma-4-*-GGUF models so the embedded GGUF template does not- need re-downloading. Keep in sync with upstream if PR #118 changes.--#}+{# Google Gemma 4 template for larger variants, which emit empty thought blocks when thinking is off. #}{%- macro format_parameters(properties, required, filter_keys=false) -%}{%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%}{%- set ns = namespace(found_first=false) -%}@@ -183,17 +175,13 @@{{- '<tool_response|>' -}}{%- endmacro -%}-{#- ===== SETUP ===== -#}{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%}{%- set loop_messages = messages -%}{%- set enable_thinking = enable_thinking | default(false) -%}-{#- Unsloth Studio: preserve_thinking defaults OFF (upstream PR #118 defaults true). -#}{%- set preserve_thinking = preserve_thinking | default(false) -%}{{- bos_token -}}-{#- Handle System/Tool Definitions Block -#}{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%}{{- '<|turn>system\n' -}}- {#- Inject Thinking token at the very top of the FIRST system turn -#}{%- if enable_thinking -%}{{- '<|think|>\n' -}}{%- set ns.prev_message_type = 'think' -%}@@ -227,21 +215,20 @@{%- endif -%}{%- endfor -%}-{#- Loop through messages -#}{%- for message in loop_messages -%}{%- if message['role'] != 'tool' -%}{%- set ns.prev_message_type = None -%}{%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}- {#- Detect continuation using tracked state - O(1) instead of O(n) backward scan -#}+ {#- tracked state avoids an O(n) backward scan -#}{%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%}{%- if not continue_same_model_turn -%}{{- '<|turn>' + role + '\n' }}+{%- endif -%}- {#- Render reasoning/reasoning_content as thinking channel (tool-call turns only) -#}{%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%}- {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or preserve_thinking -%}- {%- if thinking_text and thinking_gate and message.get('tool_calls') -%}+ {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%}+ {%- if thinking_text and thinking_gate -%}{{- '<|channel>thought\n' + thinking_text + '\n<channel|>' -}}{%- endif -%}@@ -352,7 +339,6 @@{{- captured_content -}}{%- set has_content = captured_content | trim | length > 0 -%}- {#- Forward-scan: find next non-tool message role for continuation detection -#}{%- set next_nt = namespace(role=None, found=false) -%}{%- for j in range(loop.index0 + 1, loop_messages | length) -%}{%- if not next_nt.found -%}@@ -366,19 +352,18 @@{%- set continues_into_next = (role == 'model'and next_nt.role == 'assistant'- and not message.get('tool_calls')- and not ns_tr_out.flag+ and (not message.get('tool_calls') or ns_tr_out.flag)) -%}{%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%}{{- '<|tool_response>' -}}{%- elif continues_into_next -%}{{- '\n' -}}- {%- elif not (ns_tr_out.flag and not has_content) -%}+ {%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%}{{- '<turn|>\n' -}}+ {%- set ns.prev_message_type = None -%}{%- endif -%}- {#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#}{%- set ns.prev_non_tool_role = message['role'] -%}{%- endif -%}{%- endfor -%}@@ -386,12 +371,10 @@{%- if add_generation_prompt -%}{%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}{{- '<|turn>model\n' -}}- {%- endif -%}-- {%- if not enable_thinking -%}- {#- Suppress thinking - but not when awaiting tool responses -#}- {%- if ns.prev_message_type != 'tool_call' -%}+ {%- if not enable_thinking -%}{{- '<|channel>thought\n<channel|>' -}}{%- endif -%}+ {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%}+ {{- '<|channel>thought\n' -}}{%- endif -%}{%- endif -%}diff --git a/studio/backend/tests/test_gemma4_chat_template_override.py b/studio/backend/tests/test_gemma4_chat_template_override.pyindex 9e22a732b59..c9222922bbe 100644--- a/studio/backend/tests/test_gemma4_chat_template_override.py+++ b/studio/backend/tests/test_gemma4_chat_template_override.py@@ -314,21 +314,49 @@ def test_current_tool_reasoning_survives_a_suppressed_call_result(tpl):assert rendered.index("SECRET_THOUGHT") < rendered.index("The duplicate call was not executed.")[email protected]("tpl", [BUNDLED, EDGE])+def test_model_thinks_again_after_a_tool_result(tpl):+ messages = _convo_with_prior_tool_reasoning()[:-1]+ assert _render_with(tpl, messages, enable_thinking = True).endswith(+ "<tool_response|><|channel>thought\n"+ )+ assert _render_with(tpl, messages, enable_thinking = False).endswith("<tool_response|>")++[email protected]("tpl", [BUNDLED, EDGE])+def test_closed_tool_turn_reopens_the_model_turn(tpl):+ messages = _convo_with_prior_tool_reasoning()[:-1]+ messages[1]["content"] = "Let me check."+ assert _render_with(tpl, messages, enable_thinking = True).endswith(+ "Let me check.<turn|>\n<|turn>model\n"+ )++[email protected]("tpl", [BUNDLED, EDGE])+def test_consecutive_assistant_content_keeps_its_separator(tpl):+ messages = [+ {"role": "user", "content": "q"},+ {"role": "assistant", "content": "first"},+ {"role": "assistant", "content": "second"},+ ]+ assert "first\nsecond<turn|>" in _render_with(tpl, messages)++[email protected]("tpl", [BUNDLED, EDGE])+def test_completed_tool_turn_continuation_keeps_its_separator(tpl):+ messages = _convo_with_prior_tool_reasoning()[:-1]+ messages[1]["content"] = "Let me check."+ messages.append({"role": "assistant", "content": "The answer is 42."})+ assert "Let me check.\nThe answer is 42.<turn|>" in _render_with(tpl, messages)++def test_enable_thinking_gates_think_token():assert "<|think|>" in _render([{"role": "user", "content": "hi"}], enable_thinking = True)assert "<|think|>" not in _render([{"role": "user", "content": "hi"}], enable_thinking = False)-# ── Reload dedup interaction (why the route resolves the effective override) ──--def test_already_in_target_state_consistent_with_bundled_override():- """The backend dedup compares the incoming override against the live one.-- The route resolves the bundled template up front so a re-load that omits- ``chat_template_override`` still matches (no spurious reload), while a raw- ``None`` would not.- """+ """the bundled template replaces None before dedup to prevent needless reloads"""LlamaCppBackend, GgufLoadIntent = _import_backend()class _FakeProcess: