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 tool results use the window when auto-compaction is off (#13811)
Daniel Han4dc3f93e1148
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 4408ec8270b..53892591172 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -514,7 +514,10 @@ from core.inference.repetition_guard import is_repetition_dominatedfrom core.inference.mcp_images import (DETACHED_IMAGE_TURN_TEXT as MCP_DETACHED_IMAGE_TURN_TEXT,IMAGE_TURN_TEXT as MCP_IMAGE_TURN_TEXT,+ MAX_MODEL_IMAGES as MCP_MAX_MODEL_IMAGES,+ MAX_TOTAL_MODEL_IMAGES as MCP_MAX_TOTAL_MODEL_IMAGES,append_image_turn as append_mcp_image_turn,+ is_image_tool as mcp_is_image_tool,mentions_images as mcp_images_mentioned_in,)from core.inference.tool_loop_controller import (@@ -2419,6 +2422,19 @@ _CONTINUE_TRUNCATED_ANSWER_STATUS = "Continuing the answer..."# cut, which costs a call and teaches the model nothing. Sized to leave a short line of real# output rather than to guarantee a useful one; the point is to catch the collapse to zero._MIN_USEFUL_RESULT_TOKENS = 64+# llama.cpp's default per-image embedding cap plus mtmd's delimiters, when the admission figure is out of reach.+_FALLBACK_IMAGE_TOKENS = 4096 + 128+++def _mcp_image_tokens(backend) -> int:+ """Per-image KV allowance for the loaded projector, the one admission charges."""+ try:+ from routes.inference import _openai_llama_admission_image_tokens # noqa: PLC0415+ return int(_openai_llama_admission_image_tokens(backend))+ except Exception: # noqa: BLE001 -- sizing must never break a tool call+ return _FALLBACK_IMAGE_TOKENS++# How many times one tool may return a byte-identical result before the model is told the# call is not going to change. Follows OpenClaw's tool-loop detection, which keys on the# RESULT rather than the arguments and never intervenes while results are still changing:@@ -41669,6 +41685,7 @@ class LlamaCppBackend:# run nearer one or two. Under-priced, the first result# is handed room the later ARGUMENTS already occupy._pending_args = 0+ _pending_exact = Trueif _pending_msgs:try:_pending_args = self.count_chat_tokens(@@ -41679,17 +41696,58 @@ class LlamaCppBackend:"result budget: pending call count failed",exc_info = True,)+ _pending_exact = False_pending_args = 2 * estimate_messages_tokens_dense(_pending_msgs)+ # This iteration's cap, not the caller's whole one. A+ # recovery turn with 100 of 1000 tokens left had the+ # result priced as if 1000 were still to come, which+ # reserves room away and can starve a read the request+ # had space for.+ _result_max_tokens = _iteration_max_tokens+ # Auto-compaction off: nothing fits the next prompt to+ # `prompt_budget`, whose quarter-window reply reserve+ # emptied every result from 75% of the window on (#13784).+ # Price to the reply floor the admission gate uses instead,+ # only on an exact count of a thread with no unpriced media:+ # the quarter reserve is what covers either error.+ if (+ context_overflow != "truncate_oldest"+ and (+ _exact_prompt_tokens is not None+ or (_compact_after_execution and _compacted_turn_tokens)+ )+ and _pending_exact+ and messages_without_unpriced_media(conversation)+ is conversation+ ):+ _ctx = self._effective_context_length+ _requested = (+ _iteration_max_tokens+ if _iteration_max_tokens and _iteration_max_tokens > 0+ else _ctx+ )+ _reserve = min(_requested, _reply_floor(_ctx))+ # Images join the thread after the whole batch, unpriced:+ # the ones already collected, and this call's own.+ _images = sum(map(len, batch_mcp_images))+ if (+ mcp_is_image_tool(decision.tool_name)+ and image_share is None+ and self.is_vision+ ):+ _images += MCP_MAX_MODEL_IMAGES+ if _images:+ _reserve += min(+ MCP_MAX_TOTAL_MODEL_IMAGES, _images+ ) * _mcp_image_tokens(self)+ _result_max_tokens = min(+ _reserve, _requested, max(1, _ctx // 4)+ )_result_budget = tool_result_budget(self._effective_context_length,- # This iteration's cap, not the caller's whole- # one. A recovery turn with 100 of 1000 tokens- # left had the result priced as if 1000 were- # still to come, which reserves room away and can- # starve a read the request had space for.- _iteration_max_tokens,+ _result_max_tokens,_spent + _pending_args,) // (len(_pending) + 1)# A budget at or near zero means the call cannot deliver@@ -41744,7 +41802,7 @@ class LlamaCppBackend:# or the rescue is measured against a# different request from the one it is# rescuing.- _iteration_max_tokens,+ _result_max_tokens,_spent_after + _pending_args,) // (len(_pending) + 1)logger.info(diff --git a/studio/backend/tests/test_no_progress_tool_results.py b/studio/backend/tests/test_no_progress_tool_results.pyindex 986d6117e2c..6f6ab0de8da 100644--- a/studio/backend/tests/test_no_progress_tool_results.py+++ b/studio/backend/tests/test_no_progress_tool_results.py@@ -402,6 +402,8 @@ def test_the_budget_rescue_recounts_with_the_stand_in_reply_too(monkeypatch):messages = [_thread[0], *_older, *_thread[1:]],tools = [_WEB_SEARCH_TOOL],max_tool_iterations = 4,+ # The fit target the rescue defends; compaction off prices to the reply floor.+ context_overflow = "truncate_oldest",))diff --git a/studio/backend/tests/test_result_budget_without_compaction.py b/studio/backend/tests/test_result_budget_without_compaction.pynew file mode 100644index 00000000000..2e049d8cfbb--- /dev/null+++ b/studio/backend/tests/test_result_budget_without_compaction.py@@ -0,0 +1,185 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""With auto-compaction off, a tool result may use the window up to the reply floor (#13784).++Reported at a 160K window with Max output tokens: from 120K (75%) on, every MCP result came+back as `(output omitted: N chars, no context room left)`. The result budget reserved+`prompt_budget`'s quarter of the window for the reply, which is the fit compaction trims to;+with compaction off nothing trims, llama-server admits up to the window, and the+pre-execution gate already admits up to the reply floor.+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++import pytest++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)+_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++from core.inference import tools as tools_module # noqa: E402+from core.inference.context_window import _reply_floor # noqa: E402+from test_no_progress_tool_results import ( # noqa: E402+ _WEB_SEARCH_TOOL,+ _done,+ _make_backend,+ _sse,+)++_CTX = 160_000+_SPENT = 120_500+_MCP_TOOL = "mcp__2e0d1d7fd32e4799__execute_code"+_OUTPUT = "print(1)\n" * 170 # 1530 chars, the size from the report+++def _tool(name):+ return {**_WEB_SEARCH_TOOL, "function": {**_WEB_SEARCH_TOOL["function"], "name": name}}+++def _batch(name, calls):+ return _sse(+ {+ "tool_calls": [+ {+ "index": i,+ "id": f"call_{i}",+ "function": {"name": name, "arguments": json.dumps({"query": f"q{i}"})},+ }+ for i in range(calls)+ ]+ }+ )+++def _run_one_call(+ monkeypatch,+ *,+ context_overflow,+ max_tokens = _CTX,+ messages = None,+ tool_name = "web_search",+ vision = False,+ count = lambda *_a, **_k: _SPENT,+ calls = 1,+):+ received: list[object] = []+ results: list[str] = []++ def _execute(_name, _args, **kwargs):+ budget = kwargs.get("result_budget_tokens")+ received.append(budget)+ token = tools_module._REQUEST_RESULT_BUDGET.set(budget)+ try:+ return tools_module._fit_result_to_room(_OUTPUT, _MCP_TOOL)+ finally:+ tools_module._REQUEST_RESULT_BUDGET.reset(token)++ backend = _make_backend(+ monkeypatch,+ [[_batch(tool_name, calls), _done()], [_sse({"content": "Done."}), _done()]],+ [],+ )+ backend._effective_context_length = _CTX+ backend._is_vision = vision+ backend._mmproj_accepts_image = vision+ monkeypatch.setattr(backend, "count_chat_tokens", count)+ monkeypatch.setattr("core.inference.tools.execute_tool", _execute)++ events = list(+ backend.generate_chat_completion_with_tools(+ messages = messages or [{"role": "user", "content": "Run the script"}],+ tools = [_WEB_SEARCH_TOOL, _tool(tool_name)],+ max_tool_iterations = 4,+ max_tokens = max_tokens,+ context_overflow = context_overflow,+ )+ )+ results = [e.get("result", "") for e in events if e.get("type") == "tool_end"]+ assert received, "the tool never ran"+ return received[0], results+++# None is what the route sends with the switch off; "error" is the frontend's own field.[email protected]("context_overflow", [None, "error"])+def test_compaction_off_prices_the_result_to_the_reply_floor(monkeypatch, context_overflow):+ budget, results = _run_one_call(monkeypatch, context_overflow = context_overflow)++ assert budget == int((_CTX - _reply_floor(_CTX)) * 0.99) - _SPENT+ assert results and "no context room left" not in results[0]+ assert "No room in the window" not in results[0]+ assert _OUTPUT in results[0]+++def test_compaction_off_still_honours_a_smaller_output_cap(monkeypatch):+ budget, _ = _run_one_call(monkeypatch, context_overflow = None, max_tokens = 4096)++ assert budget == int((_CTX - 4096) * 0.99) - _SPENT+++def test_compaction_on_keeps_the_fit_target(monkeypatch):+ budget, _ = _run_one_call(monkeypatch, context_overflow = "truncate_oldest")++ # 0.99 * 120K - 120.5K: the fit compaction trims to, unchanged.+ assert budget == 0+++def test_compaction_off_keeps_the_reserve_while_media_is_unpriced(monkeypatch):+ # The count strips images, so only the quarter reserve stands between the result and them.+ image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}}+ budget, _ = _run_one_call(+ monkeypatch,+ context_overflow = None,+ messages = [{"role": "user", "content": [{"type": "text", "text": "Run it"}, image]}],+ )++ assert budget == 0+++def test_compaction_off_keeps_the_reserve_without_an_exact_count(monkeypatch):+ # The fallback estimate undercounts dense text; the quarter reserve absorbs that.+ def _fails(*_a, **_k):+ raise RuntimeError("tokenizer unavailable")++ off, _ = _run_one_call(monkeypatch, context_overflow = None, count = _fails)+ on, _ = _run_one_call(monkeypatch, context_overflow = "truncate_oldest", count = _fails)++ assert off == on++[email protected]("tool_name", [_MCP_TOOL, "view_image", "browser_screenshot"])+def test_compaction_off_reserves_the_images_a_result_can_add(monkeypatch, tool_name):+ from core.inference.llama_cpp import _FALLBACK_IMAGE_TOKENS+ from core.inference.mcp_images import MAX_MODEL_IMAGES++ reserve = _reply_floor(_CTX) + MAX_MODEL_IMAGES * _FALLBACK_IMAGE_TOKENS+ vision, _ = _run_one_call(monkeypatch, context_overflow = None, tool_name = tool_name, vision = True)+ text_only, _ = _run_one_call(monkeypatch, context_overflow = None, tool_name = tool_name)++ assert vision == int((_CTX - reserve) * 0.99) - _SPENT+ assert text_only == int((_CTX - _reply_floor(_CTX)) * 0.99) - _SPENT+++def test_compaction_off_keeps_the_reserve_when_pending_calls_are_estimated(monkeypatch):+ # The thread counts exactly but the batch's pending arguments do not.+ def _count(+ messages,+ _unused = None,+ tools = None,+ **_k,+ ):+ if tools is None and all(m.get("role") == "assistant" for m in messages):+ raise RuntimeError("template rejects adjacent assistant turns")+ return _SPENT++ off, _ = _run_one_call(monkeypatch, context_overflow = None, count = _count, calls = 2)+ on, _ = _run_one_call(monkeypatch, context_overflow = "truncate_oldest", count = _count, calls = 2)++ assert off == ondiff --git a/studio/backend/tests/test_tool_call_cap_notice_extra.py b/studio/backend/tests/test_tool_call_cap_notice_extra.pyindex 0f229763c71..f216ad53318 100644--- a/studio/backend/tests/test_tool_call_cap_notice_extra.py+++ b/studio/backend/tests/test_tool_call_cap_notice_extra.py@@ -282,6 +282,7 @@ def test_skipped_arguments_are_reserved_in_result_budgets(monkeypatch, backend):import randomimport stringfrom core.inference.context_window import (+ _reply_floor,estimate_messages_tokens_conservative,prompt_budget,)@@ -347,4 +348,6 @@ def test_skipped_arguments_are_reserved_in_result_budgets(monkeypatch, backend):assert json.dumps({"code": code}) in notice["content"]spent = estimate_messages_tokens_conservative(seen[1])spent += estimate_messages_tokens_conservative(tools)- assert spent <= prompt_budget(4096, 3500)+ # Compaction off: GGUF prices results to the reply floor (#13784).+ reply = min(3500, _reply_floor(4096)) if backend == "gguf" else 3500+ assert spent <= prompt_budget(4096, reply)