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: copy tool schemas without deepcopy in the tool loop controller (#16306)
Daniel Han446155b290bf
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 04ffcf4eb1f..28e14da5e96 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -40022,7 +40022,7 @@ class LlamaCppBackend:# Loop-ending turn offers no tools, so this notice must not ask for a retry; it rides the result._over_cap_final = bool(_over_cap) and (tool_controller.force_final_answer- or not tool_controller.active_tools()+ or not tool_controller.has_active_tools()or (_turn_executed_real_tool and _tool_iters_done + 1 >= max_tool_iterations)# Fold feedback only into a result from the SAME tool, since templates label the block with the tool name; a retry notice for skipped calls is never folded.or iteration + 1 >= max_tool_iterations + _extra + _continuation_credits@@ -40155,7 +40155,7 @@ class LlamaCppBackend:# Clear tool status badge before next generation/final pass.yield {"type": "status", "text": ""}- if tool_controller.force_final_answer or not tool_controller.active_tools():+ if tool_controller.force_final_answer or not tool_controller.has_active_tools():_append_budget_exhausted_nudge = Falsebreak# Only real tool turns use the cap, so reserved re-prompt slots never add rounds (GGUF parity).diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.pyindex 335ae534297..e85cf4c1449 100644--- a/studio/backend/core/inference/safetensors_agentic.py+++ b/studio/backend/core/inference/safetensors_agentic.py@@ -1675,7 +1675,7 @@ def run_safetensors_tool_loop(# The turn that ends the loop offers no tools again, so do not ask for a retry there.over_cap_final = bool(over_cap) and (tool_controller.force_final_answer- or (not unrestricted_tools and not tool_controller.active_tools())+ or (not unrestricted_tools and not tool_controller.has_active_tools())or (_turn_executed_real_tool and _executed_tool_iters + 1 >= max_tool_iterations))if over_cap:@@ -1721,7 +1721,7 @@ def run_safetensors_tool_loop(if tool_controller.force_final_answer:final_attempt_done = Truecontinue- if not unrestricted_tools and not tool_controller.active_tools():+ if not unrestricted_tools and not tool_controller.has_active_tools():final_attempt_done = Truecontinue# Only real tool turns count against the cap, so a no-op correction turn is free (GGUF parity).diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.pyindex 21e436c6eab..2e21b914c49 100644--- a/studio/backend/core/inference/tool_loop_controller.py+++ b/studio/backend/core/inference/tool_loop_controller.py@@ -1195,6 +1195,24 @@ def _noop_result(reason: NoopReason, tool_name: str) -> str:)+_SCHEMA_ATOMS = (str, int, float, bool, type(None))+++def _copy_schema(value: Any) -> Any:+ """copy.deepcopy for JSON schemas minus its memo: no alias or cycle tracking; non-plain nodes still deepcopy."""+ kind = type(value)+ if kind is dict:+ return {+ key: item if type(item) in _SCHEMA_ATOMS else _copy_schema(item)+ for key, item in value.items()+ }+ if kind is list:+ return [item if type(item) in _SCHEMA_ATOMS else _copy_schema(item) for item in value]+ if kind in _SCHEMA_ATOMS:+ return value+ return copy.deepcopy(value)++class ToolLoopController:"""Per-response ledger for local agentic tool loops."""@@ -1212,7 +1230,7 @@ class ToolLoopController:self._session_id = session_idself._thread_id = thread_idself._restrict_to_allowed = tools is not None- self._tools = [copy.deepcopy(dict(tool)) for tool in (tools or [])]+ self._tools = [_copy_schema(dict(tool)) for tool in (tools or [])]self._allowed_tool_names = {name for name in (_tool_name_from_schema(tool) for tool in self._tools) if name}@@ -1242,6 +1260,13 @@ class ToolLoopController:"""True once a terminal no-op should transition to a no-tools pass."""return self._force_final_answer+ def has_active_tools(self) -> bool:+ """bool(active_tools()) without copying a schema."""+ return not self._force_final_answer and any(+ _tool_name_from_schema(tool) not in self._completed_one_shot_tools+ for tool in self._tools+ )+def active_tools(self) -> list[dict[str, Any]]:"""Return tools still worth advertising to the next model call."""if self._force_final_answer:@@ -1251,7 +1276,7 @@ class ToolLoopController:name = _tool_name_from_schema(tool)if name in self._completed_one_shot_tools:continue- active.append(copy.deepcopy(tool))+ active.append(_copy_schema(tool))return activedef prepare_call(@@ -1425,7 +1450,7 @@ class ToolLoopController:if _tool_name_from_schema(s) not in fresh_names])- self._mcp_loaded = [copy.deepcopy(s) for s in reversed(kept)]+ self._mcp_loaded = [_copy_schema(s) for s in reversed(kept)]self._tools = listed + self._mcp_loadedself._allowed_tool_names = {name for name in (_tool_name_from_schema(tool) for tool in self._tools) if namediff --git a/studio/backend/tests/test_tool_loop_controller.py b/studio/backend/tests/test_tool_loop_controller.pyindex 30297004574..0a68bcba33b 100644--- a/studio/backend/tests/test_tool_loop_controller.py+++ b/studio/backend/tests/test_tool_loop_controller.py@@ -1005,3 +1005,44 @@ def test_a_hard_cap_below_the_window_cap_leaves_truncated_terminal_output_alone(controller.prepare_call(_call("terminal", {"command": "yes t"})), already)assert completion.tool_message()["content"] == already+++def test_active_tools_are_private_copies_of_every_nested_schema_node():+ """Each call hands out its own copy: a caller rewriting one cannot reach the ledger or a later call."""+ from collections import OrderedDict++ source = {+ "type": "function",+ "function": {+ "name": "lookup",+ "description": "d",+ "parameters": OrderedDict(+ type = "object",+ properties = {+ "mode": {"type": "string", "enum": ["a", "b"]},+ "limit": {"type": "integer", "minimum": 1.0, "default": True},+ "pairs": {"type": "array", "items": {"enum": (1, [2])}},+ },+ ),+ },+ }+ controller = ToolLoopController(tools = [source])+ first = controller.active_tools()+ assert repr(first) == repr([source])+ first[0]["function"]["parameters"]["properties"]["mode"]["enum"].append("c")+ first[0]["function"]["parameters"]["properties"]["pairs"]["items"]["enum"][1].append(3)+ first[0]["function"]["name"] = "renamed"+ assert repr(controller.active_tools()) == repr([source])+ assert source["function"]["parameters"]["properties"]["mode"]["enum"] == ["a", "b"]+ assert source["function"]["parameters"]["properties"]["pairs"]["items"]["enum"] == (1, [2])+++def test_has_active_tools_matches_active_tools_without_copying():+ controller = ToolLoopController(tools = [_tool("web_search"), _tool("python")])+ assert controller.has_active_tools() is bool(controller.active_tools()) is True+ assert ToolLoopController(tools = []).has_active_tools() is False+ controller._completed_one_shot_tools.update({"web_search", "python"})+ assert controller.has_active_tools() is bool(controller.active_tools()) is False+ controller._completed_one_shot_tools.clear()+ controller._force_final_answer = True+ assert controller.has_active_tools() is bool(controller.active_tools()) is False