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: keep a bare-JSON tool call out of the final answer after the tool loop (#16003)
Daniel Han02854761b996
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 075a7a43cdd..eae69fc736e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -37228,6 +37228,34 @@ class LlamaCppBackend:# Caller's continue_final_message is restored once a turn progresses; forced only to join one answer._final_answer_stripper = _StreamingMarkupStripper(_enabled_names_gate, seg_final = False)+ def _final_answer_visible(+ cleaned: str,+ answer: str,+ *,+ at_end: bool = False,+ ):+ """tool_choice "none" leaves a Llama 3.x bare-JSON call in the answer text: hold while a leading+ ;-chain of objects has an open peer (its name may not have arrived), then drop the enabled calls+ as the tool rounds do. None means hold."""+ if not _enabled_names_gate or not cleaned.endswith(answer):+ return cleaned+ probe = strip_llama3_leading_sentinels(answer.lstrip())+ if not probe.startswith("{"):+ return cleaned+ if not at_end and len(probe) < _MAX_BARE_JSON_BUFFER:+ chain = probe+ while chain.startswith("{"):+ end = _balanced_brace_end(chain, 0)+ if end is None:+ return None+ chain = strip_llama3_leading_sentinels(chain[end + 1 :].lstrip()).lstrip(+ " \t\n\r;"+ )+ kept = strip_leading_bare_json_call(answer, _enabled_names_gate)+ if kept == answer:+ return cleaned+ return cleaned[: len(cleaned) - len(answer)] + kept+def _strip_tool_markup_streaming(text: str, *, force: bool = False) -> str:if not (auto_heal_tool_calls or force):return text@@ -40566,14 +40594,26 @@ class LlamaCppBackend:if auto_heal_tool_callselse cumulative)+ if auto_heal_tool_calls:+ cleaned = _final_answer_visible(cleaned, answer_text)# Emit only when cleaned text grows (monotonic).- if len(cleaned) > len(_last_emitted):+ if cleaned is not None and len(cleaned) > len(+ _last_emitted+ ):_last_emitted = cleanedyield {"type": "content", "text": cleaned}except json.JSONDecodeError:logger.debug(f"Skipping malformed SSE line: {line[:100]}")if _stream_done:break # exit outer for+ if auto_heal_tool_calls and has_content_tokens and not in_thinking:+ # Release an answer still held as a possible bare-JSON call.+ _flushed = _final_answer_visible(+ _final_answer_stripper.strip(cumulative), answer_text, at_end = True+ )+ if len(_flushed) > len(_last_emitted):+ _last_emitted = _flushed+ yield {"type": "content", "text": _flushed}# Commit the candidate only once another stream runs, so usage is not double counted; replay only new text, or the fragment is repeated._shown_this_attempt = _last_emitted[len(_attempt_started_at) :]if (diff --git a/studio/backend/tests/test_llama_final_pass_bare_json_call.py b/studio/backend/tests/test_llama_final_pass_bare_json_call.pynew file mode 100644index 00000000000..c4974b8d203--- /dev/null+++ b/studio/backend/tests/test_llama_final_pass_bare_json_call.py@@ -0,0 +1,107 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""tool_choice "none" leaves a Llama 3.x bare-JSON call in the final-pass text; it must not be shown."""++from __future__ import annotations++import json++import pytest++from .test_llama_cpp_tool_loop import (+ _done,+ _finish,+ _make_backend,+ _record_tool_calls,+ _run_tool_loop,+ _sse,+ _tool_call_sse,+ _web_search_tool,+)+++def _python_tool():+ return {+ "type": "function",+ "function": {+ "name": "python",+ "description": "Run Python.",+ "parameters": {+ "type": "object",+ "properties": {"code": {"type": "string"}},+ "required": ["code"],+ },+ },+ }+++def _content_stream(text: str, step: int = 3) -> list[str]:+ return [_sse({"content": text[i : i + step]}) for i in range(0, len(text), step)] + [+ _finish("stop"),+ _done(),+ ]+++def _final_pass(+ monkeypatch,+ final_text: str,+ tools = None,+ step: int = 3,+):+ payloads: list[dict] = []+ streams = [+ [_tool_call_sse("web_search", {"query": "a"}, "c1"), _finish("tool_calls"), _done()],+ _content_stream(final_text, step),+ ]+ backend = _make_backend(monkeypatch, streams, payloads)+ _record_tool_calls(monkeypatch, "RESULT_OK")+ events = _run_tool_loop(+ backend,+ [{"role": "user", "content": "Search."}],+ tools or [_web_search_tool()],+ max_tool_iterations = 1,+ )+ assert payloads[-1].get("tool_choice") == "none"+ return [e["text"] for e in events if e.get("type") == "content"]+++ "text",+ [+ '{"name": "web_search", "parameters": {"query": "again"}}',+ '{"type": "function", "function": "web_search", "parameters": {"query": "again"}}',+ '{"name": "web_search", "parameters": {"query": "a"}}; {"name": "web_search", "parameters": {"query": "b"}}',+ '{"name": "web_search", "parameters": {"query": "a"}}\n{"name": "web_search", "parameters": {"query": "b"}}',+ ],+)[email protected]("step", [1, 3])+def test_final_pass_does_not_show_a_bare_json_call(monkeypatch, text, step):+ shown = _final_pass(monkeypatch, text, step = step)+ # No fragment either: a chained peer whose name has not arrived yet must not stream.+ assert not any("{" in s or "web_search" in s for s in shown), shown+++ "text",+ [+ "The search found RESULT_OK.",+ '{"answer": 4, "unit": "apples"}',+ 'Here is the JSON: {"name": "web_search", "parameters": {"query": "x"}}',+ ],+)+def test_final_pass_answers_are_unchanged(monkeypatch, text):+ shown = _final_pass(monkeypatch, text)+ assert shown[-1] == text+++def test_final_pass_keeps_blocked_execution_call_visible(monkeypatch):+ text = '{"name": "python", "parameters": {"code": "print(1)"}}'+ shown = _final_pass(monkeypatch, text, tools = [_web_search_tool(), _python_tool()])+ assert shown[-1] == text+++def test_final_pass_releases_unclosed_ordinary_json_at_end(monkeypatch):+ text = '{"answer": [1, 2'+ shown = _final_pass(monkeypatch, text)+ assert shown[-1] == text