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: make MLX and safetensors models call a forced tool (#17241)
Nilay582194f94c69
diff --git a/studio/backend/core/inference/passthrough_healing.py b/studio/backend/core/inference/passthrough_healing.pyindex c74713d864a..09cc789850a 100644--- a/studio/backend/core/inference/passthrough_healing.py+++ b/studio/backend/core/inference/passthrough_healing.py@@ -325,6 +325,29 @@ _NATIVE_TOOL_FORMATS = ()+_FORCED_CALL_OPENERS = {+ "hermes": ('<tool_call>\n{"name":', lambda name: f' {json.dumps(name)}, "arguments":'),+ "qwen3_coder": ("<tool_call>\n<function=", lambda name: f"{name}>\n"),+}+++def forced_call_prefix(names: Optional[set], *templates: Any) -> str:+ """Opening of the model's own call markup for a forced tool_choice (in-process engines have no+ grammar to force one); empty unless every template body with a call format agrees on it."""+ from core.inference.engine_adapters import tool_parser_for_template++ parsers = {+ tool_parser_for_template(body, "vllm")+ for template in templates+ for body in _template_strings(template)+ } - {None}+ opener = _FORCED_CALL_OPENERS.get(parsers.pop()) if len(parsers) == 1 else None+ if not names or opener is None:+ return ""+ head, named = opener+ return head + named(next(iter(names))) if len(names) == 1 else head++def native_tool_format(*templates: Any) -> Optional[NativeToolFormat]:"""The block format the model's chat template writes tool calls in, if it is one of these."""bodies = [body for template in templates for body in _template_strings(template)]diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 56b371d430d..7dc5ff54bc1 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -35301,6 +35301,15 @@ async def produce_openai_chat_completions(if _sf_healelse None)+ _sf_call_prefix = ""+ if _sf_heal and payload.tool_choice not in (None, "auto") and not _sf_continue:+ from core.inference.passthrough_healing import forced_call_prefix+ _sf_call_prefix = forced_call_prefix(+ _sf_heal,+ _sf_image_tpl,+ (_sf_model_info.get("chat_template_info") or {}).get("template"),+ *(getattr(target, "chat_template", None) for target in _sf_chat_targets),+ )if _sf_client_tools:# Re-derive from messages to keep tool history; fold system and developer into one system message; tool_choice none drops tools or markup leaks as prose_sf_tc = payload.tool_choice@@ -35391,6 +35400,8 @@ async def produce_openai_chat_completions(template = _sf_image_tpl,prefer_tool_use = _sf_image_tpl is None,)+ if _sf_call_prefix:+ _sf_reasoning_prefilled = Falseif gen_kwargs.get("response_format") is not None:gen_kwargs["reasoning_is_extracted"] = bool(_sf_parse_think)@@ -35480,6 +35491,16 @@ async def produce_openai_chat_completions("system_prompt": fitted["system_prompt"],}events = fitted.get("events") or ()+ if _sf_call_prefix:+ # After fitting: compaction leaves a prompt ending in a continuation untouched.+ fitted_kwargs = {+ **fitted_kwargs,+ "messages": [+ *(fitted_kwargs.get("messages") or []),+ {"role": "assistant", "content": _sf_call_prefix},+ ],+ "continue_final_message": True,+ }_sf_fit_cache["kwargs"] = fitted_kwargsreturn fitted_kwargs, events@@ -35586,6 +35607,8 @@ async def produce_openai_chat_completions(mark_current_response_failed()api_monitor.finish(monitor_id, "cancelled")return+ if cumulative:+ cumulative = _sf_call_prefix + cumulativenew_text = cumulative[len(prev_text) :]prev_text = cumulativeif not new_text:@@ -35864,6 +35887,9 @@ async def produce_openai_chat_completions(),)raise HTTPException(status_code = 500, detail = _msg)+ if full_text:+ # The prefill alone is no call: an empty or cancelled reply stays empty.+ full_text = _sf_call_prefix + full_text# Heal only visible text so tool markup inside reasoning is never promoted._reasoning_text, _visible_text = _extract_responses_reasoning(@@ -35895,7 +35921,7 @@ async def produce_openai_chat_completions():if _finish != "length":_finish = "tool_calls"- elif nudge_enabled(+ elif not _sf_call_prefix and nudge_enabled(payload.nudge_tool_calls,response_format = _sf_response_format,):diff --git a/studio/backend/tests/test_sf_client_tools_passthrough.py b/studio/backend/tests/test_sf_client_tools_passthrough.pyindex 81fb792fb59..12d66455568 100644--- a/studio/backend/tests/test_sf_client_tools_passthrough.py+++ b/studio/backend/tests/test_sf_client_tools_passthrough.py@@ -550,6 +550,140 @@ def test_forced_tool_choice_narrows_promotion(monkeypatch):assert choice["message"].get("tool_calls") is None+_HERMES_TEMPLATE = (+ "{% if tools %}<tools>{{ tools | tojson }}</tools>\n<tool_call>\n"+ '{"name": <function-name>, "arguments": <args-json-object>}\n</tool_call>{% endif %}'+ "{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{% endfor %}"+)+_QWEN_XML_TEMPLATE = (+ "{% if tools %}<tools>{{ tools | tojson }}</tools>\n<tool_call>\n<function=example>\n"+ "<parameter=example>\nvalue\n</parameter>\n</function>\n</tool_call>"+ "{% for t in tools %}{{ t.arguments }}{% endfor %}{% endif %}"+ "{% for m in messages %}<|im_start|>{{ m.role }}\n{{ m.content }}<|im_end|>\n{% endfor %}"+)+_ARGS = {"lookup": ("q", "cats"), "search": ("query", "dogs")}+++def _model_that_answers_in_prose(messages, tools):+ opener = messages[-1]["content"] if messages[-1]["role"] == "assistant" else ""+ if opener.startswith("<tool_call>\n<function="):+ name = opener[len("<tool_call>\n<function=") :].rstrip(">\n") or "lookup"+ key, value = _ARGS[name]+ body = f"<parameter={key}>\n{value}\n</parameter>\n</function>\n</tool_call>"+ return [body if opener.endswith(">\n") else f"{name}>\n{body}"]+ if not opener.startswith("<tool_call>"):+ return ["Hello!"]+ if opener.endswith('"arguments":'):+ args = '{"q": "cats"}' if '"lookup"' in opener else '{"query": "dogs"}'+ return [f" {args}}}\n</tool_call>"]+ return [' "lookup", "arguments": {"q": "cats"}}\n</tool_call>']+++ "template", [_HERMES_TEMPLATE, _QWEN_XML_TEMPLATE], ids = ["hermes", "qwen_xml"]+)[email protected]("stream", [False, True])+ "tools, tool_choice, forced",+ [+ ([LOOKUP_TOOL], "required", "lookup"),+ ([LOOKUP_TOOL, SEARCH_TOOL], "required", "lookup"),+ (+ [LOOKUP_TOOL, SEARCH_TOOL],+ {"type": "function", "function": {"name": "search"}},+ "search",+ ),+ ],+)+def test_forced_tool_choice_makes_the_model_call_a_tool(+ monkeypatch, template, stream, tools, tool_choice, forced+):+ backend = _ScriptedBackend(_model_that_answers_in_prose)+ backend.models["sf-model"]["chat_template_info"] = {"template": template}+ payload = _request(tools = tools, tool_choice = tool_choice, stream = stream)+ response = _call(payload, monkeypatch, backend)++ if stream:+ choices = [+ o["choices"][0] for o in _sse_objects(_collect_sse(response)) if o.get("choices")+ ]+ deltas = [c.get("delta") or {} for c in choices]+ calls = [tc for d in deltas for tc in d.get("tool_calls") or []]+ finish = [c["finish_reason"] for c in choices if c.get("finish_reason")][-1]+ arguments = "".join(tc["function"].get("arguments") or "" for tc in calls)+ else:+ choice = _json_body(response)["choices"][0]+ calls, finish = choice["message"].get("tool_calls") or [], choice["finish_reason"]+ arguments = "".join(tc["function"]["arguments"] for tc in calls)+ assert finish == "tool_calls"+ assert [call["function"]["name"] for call in calls if call["function"].get("name")] == [forced]+ key, value = _ARGS[forced]+ assert json.loads(arguments) == {key: value}+++def test_auto_tool_choice_leaves_the_reply_to_the_model(monkeypatch):+ backend = _ScriptedBackend(_model_that_answers_in_prose)+ backend.models["sf-model"]["chat_template_info"] = {"template": _HERMES_TEMPLATE}+ payload = _request(tools = [LOOKUP_TOOL], tool_choice = "auto", stream = False)+ choice = _json_body(_call(payload, monkeypatch, backend))["choices"][0]+ assert choice["finish_reason"] == "stop"+ assert choice["message"]["content"] == "Hello!"+ assert backend.calls[0]["messages"][-1]["role"] == "user"++[email protected]("stream", [False, True])+ "template", [_HERMES_TEMPLATE, _QWEN_XML_TEMPLATE], ids = ["hermes", "qwen_xml"]+)+def test_an_empty_reply_to_a_forced_call_is_not_a_call(monkeypatch, template, stream):+ backend = _ScriptedBackend(_fixed(""))+ backend.models["sf-model"]["chat_template_info"] = {"template": template}+ payload = _request(tools = [LOOKUP_TOOL], tool_choice = "required", stream = stream)+ response = _call(payload, monkeypatch, backend)+ if stream:+ choices = [+ o["choices"][0] for o in _sse_objects(_collect_sse(response)) if o.get("choices")+ ]+ assert not [c for c in choices if (c.get("delta") or {}).get("tool_calls")]+ assert [c["finish_reason"] for c in choices if c.get("finish_reason")] == ["stop"]+ else:+ choice = _json_body(response)["choices"][0]+ assert choice["message"].get("tool_calls") is None+ assert choice["finish_reason"] == "stop"+++def test_forced_call_prefix_is_added_after_the_context_fit(monkeypatch):+ backend = _TrimmingBackend(_model_that_answers_in_prose)+ backend.models["sf-model"]["is_mlx"] = True+ backend.models["sf-model"]["chat_template_info"] = {"template": _HERMES_TEMPLATE}+ payload = _overflowing(tools = [LOOKUP_TOOL], tool_choice = "required")+ choice = _json_body(_call(payload, monkeypatch, backend))["choices"][0]+ assert [fit["continue_final_message"] for fit in backend.fits] == [False]+ assert _texts(backend.calls[0]["messages"]) == [+ "new",+ '<tool_call>\n{"name": "lookup", "arguments":',+ ]+ assert choice["finish_reason"] == "tool_calls"+++ "names, templates, expected",+ [+ ({"lookup"}, [_HERMES_TEMPLATE], '<tool_call>\n{"name": "lookup", "arguments":'),+ ({"lookup", "search"}, [_HERMES_TEMPLATE, None], '<tool_call>\n{"name":'),+ ({"lookup"}, [_QWEN_XML_TEMPLATE], "<tool_call>\n<function=lookup>\n"),+ ({"lookup", "search"}, [{"tool_use": _QWEN_XML_TEMPLATE}], "<tool_call>\n<function="),+ # Bodies disagreeing on the format, or a format with no opener, are not forced.+ ({"lookup"}, [_HERMES_TEMPLATE, _QWEN_XML_TEMPLATE], ""),+ ({"lookup"}, ["{% if tools %}[TOOL_CALLS]{% endif %}"], ""),+ (None, [_HERMES_TEMPLATE], ""),+ ],+)+def test_forced_call_prefix(names, templates, expected):+ from core.inference.passthrough_healing import forced_call_prefix+ assert forced_call_prefix(names, *templates) == expected++def test_parallel_cap_non_streaming(monkeypatch):backend = _ScriptedBackend(_fixed(_CALL_XML + _SEARCH_XML))payload = _request(tools = [LOOKUP_TOOL, SEARCH_TOOL], stream = False, parallel_tool_calls = False)