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 read web search and tool results on safetensors (#13096)
Nilay20e12f5b5871
diff --git a/studio/backend/core/inference/chat_template_helpers.py b/studio/backend/core/inference/chat_template_helpers.pyindex a46e0c54bcd..a917290a1db 100644--- a/studio/backend/core/inference/chat_template_helpers.py+++ b/studio/backend/core/inference/chat_template_helpers.py@@ -3501,7 +3501,7 @@ def render_native_template(exc,)return None- if with_tools == no_tools:+ if tools and with_tools == no_tools:return Noneif return_metadata:return ChatTemplateRenderResult(@@ -3509,11 +3509,7 @@ def render_native_template(_detect_reasoning_channel_markers_from_templates(_selected_template_strings_from_value(native_tpl, tools)),- # The NATIVE profile decided this render's catalog: it can drop a tool the active profile kept, so callers- # must gate healing and tool execution on this list rather than on the one they sanitized themselves. With- # *tools*, matching the render above: a named native template selects "tool_use" for a tool-calling turn,- # and profiling it without them read "default" instead, so a tool the render dropped was reported as- # advertised (#7066).+ # gate healing and execution on NATIVE: "default" can advertise tools dropped by "tool_use" (#7066).neutralize_tool_descriptions(tools, None, markup_for_tokenizer(render_tokenizer, tools)),diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex cd1a398df98..dd22856ca8d 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -1520,41 +1520,61 @@ class InferenceBackend:f"one via tokenizer.chat_template before inference.")reasoning_channel_markers = None- formatted_prompt = self._apply_chat_template_for_generation(- tokenizer,- template_messages,- tools = tools,- enable_thinking = enable_thinking,- reasoning_effort = reasoning_effort,- preserve_thinking = preserve_thinking,- continue_final_message = continue_final_message,- )-- # If tools were requested but the (possibly overridden) template ignored- # them, fall back to the model's native template (shared with MLX).from core.inference.chat_template_helpers import (+ messages_have_tool_history,+ render_native_template,render_with_native_template_fallback,)- render_result = render_with_native_template_fallback(- formatted_prompt = formatted_prompt,- tokenizer = tokenizer,- model_info = model_info,- active_model_name = self.active_model_name,- messages = template_messages,- tools = tools,- enable_thinking = enable_thinking,- reasoning_effort = reasoning_effort,- preserve_thinking = preserve_thinking,- continue_final_message = continue_final_message,- apply_fn = self._apply_chat_template_for_generation,- hf_token = model_info.get("hf_token"),- return_metadata = True,- )+ try:+ formatted_prompt = self._apply_chat_template_for_generation(+ tokenizer,+ template_messages,+ tools = tools,+ enable_thinking = enable_thinking,+ reasoning_effort = reasoning_effort,+ preserve_thinking = preserve_thinking,+ continue_final_message = continue_final_message,+ )+ except Exception:+ if not messages_have_tool_history(template_messages):+ raise+ render_result = render_native_template(+ model_info = model_info,+ active_model_name = self.active_model_name,+ messages = template_messages,+ tools = tools,+ enable_thinking = enable_thinking,+ reasoning_effort = reasoning_effort,+ preserve_thinking = preserve_thinking,+ continue_final_message = continue_final_message,+ apply_fn = self._apply_chat_template_for_generation,+ hf_token = model_info.get("hf_token"),+ return_metadata = True,+ )+ if render_result is None:+ raise+ else:+ # use the native template shared with MLX when an override ignores requested tools.+ render_result = render_with_native_template_fallback(+ formatted_prompt = formatted_prompt,+ tokenizer = tokenizer,+ model_info = model_info,+ active_model_name = self.active_model_name,+ messages = template_messages,+ tools = tools,+ enable_thinking = enable_thinking,+ reasoning_effort = reasoning_effort,+ preserve_thinking = preserve_thinking,+ continue_final_message = continue_final_message,+ apply_fn = self._apply_chat_template_for_generation,+ hf_token = model_info.get("hf_token"),+ return_metadata = True,+ )formatted_prompt = render_result.promptreasoning_channel_markers = render_result.reasoning_channel_markersreasoning_channel_markers_resolved = True- # Suppress the tokenizer's BOS only when the template already emitted one.+ # suppress the tokenizer's BOS only when the template already emitted one.add_special_tokens = not _prompt_already_has_bos(tokenizer, formatted_prompt)logger.debug(f"Formatted prompt: {formatted_prompt[:200]}...")diff --git a/studio/backend/tests/test_gemma4_safetensors_tool_turns.py b/studio/backend/tests/test_gemma4_safetensors_tool_turns.pynew file mode 100644index 00000000000..aceb2099901--- /dev/null+++ b/studio/backend/tests/test_gemma4_safetensors_tool_turns.py@@ -0,0 +1,98 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import sys+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++MODEL = "unsloth/gemma-4-E2B-it"+NATIVE = (_BACKEND / "assets" / "chat_templates" / "gemma-4-edge.jinja").read_text(encoding = "utf-8")+RESULT = "Estonia won 0 gold, 1 silver and 0 bronze medals."+WEB_SEARCH = {+ "type": "function",+ "function": {+ "name": "web_search",+ "description": "Search the web.",+ "parameters": {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ },+}+MESSAGES = [+ {"role": "user", "content": "What medals did Estonia win at the 2026 Winter Olympics?"},+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "call_0",+ "type": "function",+ "function": {+ "name": "web_search",+ "arguments": {"query": "Estonia medals 2026 Winter Olympics"},+ },+ }+ ],+ },+ {"role": "tool", "tool_call_id": "call_0", "name": "web_search", "content": RESULT},+]+++def _tokenizer():+ from tokenizers import Tokenizer, models, pre_tokenizers+ from transformers import PreTrainedTokenizerFast++ vocab = {"<pad>": 0, "<eos>": 1, "<bos>": 2, "<unk>": 3, "<|turn>": 4, "<turn|>": 5}+ backend = Tokenizer(models.WordLevel(vocab, unk_token = "<unk>"))+ backend.pre_tokenizer = pre_tokenizers.Whitespace()+ tokenizer = PreTrainedTokenizerFast(+ tokenizer_object = backend,+ unk_token = "<unk>",+ bos_token = "<bos>",+ eos_token = "<eos>",+ pad_token = "<pad>",+ )+ tokenizer.chat_template = NATIVE+ return tokenizer+++def _prompt(monkeypatch, tools):+ try:+ from core.inference import inference+ except (ImportError, RuntimeError) as exc:+ pytest.skip(f"full inference backend unavailable ({type(exc).__name__}: {exc})")+ if getattr(inference.get_chat_template, "__module__", None) != "unsloth.chat_templates":+ pytest.skip("inference module is bound to a stubbed unsloth.chat_templates")+ backend = inference.InferenceBackend.__new__(inference.InferenceBackend)+ backend.active_model_name = MODEL+ backend.models = {+ MODEL: {"tokenizer": _tokenizer(), "is_vision": False, "native_chat_template": NATIVE}+ }+ prompts = []+ monkeypatch.setattr(+ backend,+ "generate_stream",+ lambda prompt, *a, **k: prompts.append(prompt) or iter(()),+ raising = False,+ )+ list(+ backend._generate_chat_response_inner(+ messages = MESSAGES, system_prompt = "Be brief.", tools = tools+ )+ )+ return prompts[0]++[email protected]("tools", [[WEB_SEARCH], None], ids = ["tools", "tool_budget_spent"])+def test_gemma4_tool_result_reaches_the_model(monkeypatch, tools):+ prompt = _prompt(monkeypatch, tools)+ assert RESULT in prompt+ assert "Be brief." in prompt+ assert "What medals did Estonia win" in prompt