Skip to content

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.

Studio: add a tool output length setting to Settings > Chat (#13228)

Daniel Han67717d281474
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 7eb620751b0..02732b444b1 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -177,10 +177,11 @@ def _truncate_for_model(
joiner: str = "\n",
) -> str:
"""Hold a hosted result to the same cap a local result gets. Read off ``tools`` rather than
- copied, so an install that lowers ``UNSLOTH_TOOL_RESULT_MAX_CHARS`` gets the lower cap here
- too."""
+ copied, so an install that lowers ``UNSLOTH_TOOL_RESULT_MAX_CHARS`` (or the Settings > Chat
+ limit) gets the lower cap here too. A raised setting is not applied: the provider's window is
+ unknown here."""
if limit is None:
- limit = tools_module._MAX_OUTPUT_CHARS
+ limit = min(tools_module._tool_result_max_chars(), tools_module._MAX_OUTPUT_CHARS)
if len(text) <= limit:
return text
return text[:limit] + f"{joiner}... [truncated, {len(text) - limit} more characters]"
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 74a626b047e..9ce71eb923a 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -91,7 +91,7 @@ from core.inference.mcp_client import (
from storage import mcp_servers_db
from utils.account_context import account_thread, current_account_id, is_owner_context
from utils.current_date_prompt_settings import strip_current_date_update_note
-from utils import sandbox_memory_limit
+from utils import sandbox_memory_limit, tool_result_limit
from core.inference.tool_confinement import ToolConfinementUnavailable, account_confinement
from pathlib import Path
from utils.paths.storage_roots import RetiredAccountError, ensure_dir
@@ -174,7 +174,17 @@ def _env_int(name: str, default: int) -> int:
# Model-visible cap on python/terminal tool results. The live UI stream is capped separately and higher, so
# _truncate's notice stays mode-neutral (tool_stream_exec.TOOL_OUTPUT_STREAM_MAX_CHARS).
-_MAX_OUTPUT_CHARS = _env_int("UNSLOTH_TOOL_RESULT_MAX_CHARS", 16000)
+_MAX_OUTPUT_CHARS = _env_int(tool_result_limit.MAX_CHARS_ENV, tool_result_limit.DEFAULT_MAX_CHARS)
+
+
+def _tool_result_max_chars() -> int:
+ """The cap before the window lowers it: Settings > Chat, unless the env var decides. Read per call so a save
+ applies to the next tool call; no saved value keeps `_MAX_OUTPUT_CHARS`."""
+ if tool_result_limit.locked_by_environment():
+ return _MAX_OUTPUT_CHARS
+ return tool_result_limit.saved_max_chars() or _MAX_OUTPUT_CHARS
+
+
_BLOCKED_COMMANDS_COMMON = frozenset(
{
"rm",
@@ -13615,7 +13625,7 @@ def mcp_tool_input_schema(name) -> dict | None:
def _mcp_schema_page(prefix: str, text: str, offset: int) -> str:
- page_chars = _tool_result_char_budget()
+ page_chars = _other_tool_result_char_budget()
while True:
end = min(offset + page_chars, len(text))
page = prefix + text[offset:end]
@@ -16580,6 +16590,16 @@ def _result_char_budget(cap: int) -> int:
def _tool_result_char_budget() -> int:
"""The terminal/python cap, sized to the window. See `_result_char_budget`."""
+ cap = _tool_result_max_chars()
+ if not _request_context_tokens():
+ # Unknown window (an external provider, possibly a small local server): a raised setting is not applied blind.
+ cap = min(cap, _MAX_OUTPUT_CHARS)
+ return _result_char_budget(cap)
+
+
+def _other_tool_result_char_budget() -> int:
+ """Non-code tools keep the install cap: the setting names Python and Terminal, and these results have no spill to
+ page back through."""
return _result_char_budget(_MAX_OUTPUT_CHARS)
@@ -21144,7 +21164,7 @@ def _fit_result_to_room(text, name = None):
body, suffix = _split_frontend_suffix(text, name)
if not body:
return text
- fitted = _truncate(body)
+ fitted = _truncate(body, _other_tool_result_char_budget())
return fitted + suffix if fitted is not body else text
@@ -21176,7 +21196,7 @@ _TOOL_TEXT_READERS = frozenset({"terminal", "python"})
def _hard_cap_chars() -> int:
"""Never below the window-aware cap plus its notice, so output `_truncate` already cut (and
spilled) passes through with its own spill reference intact."""
- return max(MAX_TOOL_TEXT_CHARS, _MAX_OUTPUT_CHARS + 4_000)
+ return max(MAX_TOOL_TEXT_CHARS, max(_MAX_OUTPUT_CHARS, _tool_result_max_chars()) + 4_000)
def _tool_text_notice_head() -> str:
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 52a246ed961..bac81f1f1da 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -89,7 +89,7 @@ from utils.helper_precache_settings import (
helper_model_disabled_by_env,
set_helper_precache_enabled,
)
-from utils import sandbox_memory_limit, systemone_settings
+from utils import sandbox_memory_limit, systemone_settings, tool_result_limit
from utils.download_transport_settings import (
get_download_transport_mode,
set_download_transport_mode,
@@ -583,6 +583,21 @@ class UploadLimitResponse(BaseModel):
max_allowed_upload_size_mb: int = MAX_UPLOAD_LIMIT_MB
+class ToolResultLimitPayload(BaseModel):
+ max_chars: StrictInt = Field(
+ ..., ge = tool_result_limit.MIN_MAX_CHARS, le = tool_result_limit.MAX_MAX_CHARS
+ )
+
+
+class ToolResultLimitResponse(BaseModel):
+ # The cap before a small context window lowers it.
+ max_chars: int
+ default_chars: int = tool_result_limit.DEFAULT_MAX_CHARS
+ min_chars: int = tool_result_limit.MIN_MAX_CHARS
+ max_allowed_chars: int = tool_result_limit.MAX_MAX_CHARS
+ locked_by_environment: bool = False
+
+
class HuggingFaceTokenPayload(BaseModel):
token: str = Field(..., min_length = 1, max_length = 512)
@@ -1486,6 +1501,46 @@ def update_upload_limit(
return _upload_limit_response(limit_mb)
+def _tool_result_limit_response() -> ToolResultLimitResponse:
+ return ToolResultLimitResponse(
+ max_chars = tool_result_limit.effective_max_chars(),
+ locked_by_environment = tool_result_limit.locked_by_environment(),
+ )
+
+
+@_shared_settings_router.get("/tool-result-limit", response_model = ToolResultLimitResponse)
+def get_tool_result_limit(
+ current_subject: str = Depends(get_current_subject),
+) -> ToolResultLimitResponse:
+ return _tool_result_limit_response()
+
+
+@_owner_settings_router.put("/tool-result-limit", response_model = ToolResultLimitResponse)
+def update_tool_result_limit(
+ payload: ToolResultLimitPayload, current_subject: str = Depends(get_current_subject)
+) -> ToolResultLimitResponse:
+ """Save how many characters of one tool result the model reads. Applies from the next tool call."""
+ if tool_result_limit.locked_by_environment():
+ raise HTTPException(
+ status_code = 409,
+ detail = f"{tool_result_limit.MAX_CHARS_ENV} is set in the environment Unsloth runs in, which decides this.",
+ )
+ try:
+ max_chars = tool_result_limit.set_max_chars(payload.max_chars)
+ except ValueError as exc:
+ raise log_and_http_error(
+ exc,
+ 400,
+ safe_error_detail(exc, fallback = "Invalid tool output limit."),
+ event = "settings.update_tool_result_limit_failed",
+ log = logger,
+ ) from exc
+ logger.info(
+ "settings.tool_result_limit_updated subject=%s max_chars=%s", current_subject, max_chars
+ )
+ return _tool_result_limit_response()
+
+
@_shared_settings_router.get("/helper-precache", response_model = HelperPrecacheResponse)
def get_helper_precache(
current_subject: str = Depends(get_current_subject),
diff --git a/studio/backend/tests/test_account_chat_settings.py b/studio/backend/tests/test_account_chat_settings.py
index e1a0de88fa2..6493fc58f3a 100644
--- a/studio/backend/tests/test_account_chat_settings.py
+++ b/studio/backend/tests/test_account_chat_settings.py
@@ -360,6 +360,7 @@ OWNER_PATHS = [
"/hugging-face-cache": ("GET", "PUT"),
"/llama-cpp-path": ("GET", "PUT"),
"/upload-limit": ("PUT",),
+ "/tool-result-limit": ("PUT",),
"/helper-precache": ("PUT",),
"/download-transport": ("PUT",),
"/xet-notice/reserve": ("POST",),
diff --git a/studio/backend/tests/test_tool_result_limit_setting.py b/studio/backend/tests/test_tool_result_limit_setting.py
new file mode 100644
index 00000000000..e222872c452
--- /dev/null
+++ b/studio/backend/tests/test_tool_result_limit_setting.py
@@ -0,0 +1,199 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Settings > Chat tool output limit (#10349, #10135): env first, then the owner's saved value, then 16,000; a small
+context window still lowers it."""
+
+from pathlib import Path
+import sys
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+import routes.settings as settings
+from core.inference import studio_tool_loop, tools
+from storage import studio_db
+from utils import tool_result_limit as limit
+from utils.account_context import OWNER, AccountContext, bind_account, reset_account
+
+ALICE = AccountContext("a" * 32, "alice")
+# 625 lines, 50,000 characters: the reporter's ~50k file.
+FILE_50K = ("x" * 79 + "\n") * 625
+
+
[email protected](autouse = True)
+def isolated(monkeypatch, tmp_path):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.setattr(studio_db, "_schema_ready", set())
+ monkeypatch.delenv(limit.MAX_CHARS_ENV, raising = False)
+ monkeypatch.setattr(tools, "_MAX_OUTPUT_CHARS", limit.DEFAULT_MAX_CHARS)
+ monkeypatch.setattr(tools, "_loaded_context_tokens", lambda: None)
+ token = tools._REQUEST_CONTEXT_TOKENS.set(tools._UNSET_CONTEXT_TOKENS)
+ yield
+ tools._REQUEST_CONTEXT_TOKENS.reset(token)
+
+
+def _client(account):
+ app = FastAPI()
+ app.include_router(settings.router)
+
+ async def subject():
+ token = bind_account(account)
+ try:
+ yield account.username
+ finally:
+ reset_account(token)
+
+ app.dependency_overrides[settings.get_current_subject] = subject
+ return TestClient(app, raise_server_exceptions = False)
+
+
+def test_default_is_unchanged():
+ assert limit.saved_max_chars() is None
+ assert limit.effective_max_chars() == 16000
+ assert tools._tool_result_max_chars() == 16000
+ out = tools._truncate(FILE_50K)
+ assert "truncated to 16000 chars for the model" in out
+
+
+def test_a_saved_value_raises_the_cap_and_saving_again_is_a_no_op(tmp_path):
+ for _ in range(2):
+ assert limit.set_max_chars(64000) == 64000
+ assert tools._tool_result_max_chars() == 64000
+ tools._REQUEST_CONTEXT_TOKENS.set(131072)
+ assert tools._truncate(FILE_50K, workdir = str(tmp_path)) == FILE_50K
+
+
[email protected]("unknown", [None, 0], ids = ["no-probe", "external-provider"])
+def test_a_raise_is_not_applied_where_the_window_is_unknown(unknown):
+ """An external provider's window cannot be measured and may be a small local server."""
+ limit.set_max_chars(64000)
+ tools._REQUEST_CONTEXT_TOKENS.set(unknown)
+ assert tools._tool_result_char_budget() == 16000
+ assert "truncated to 16000 chars for the model" in tools._truncate(FILE_50K)
+ assert len(studio_tool_loop._truncate_for_model(FILE_50K)) < 16100
+
+
+def test_a_saved_value_can_lower_the_cap_too():
+ limit.set_max_chars(4000)
+ assert "truncated to 4000 chars for the model" in tools._truncate(FILE_50K)
+ assert len(studio_tool_loop._truncate_for_model(FILE_50K)) < 4100
+
+
+def test_a_small_window_still_lowers_a_raised_cap():
+ limit.set_max_chars(200000)
+ tools._REQUEST_CONTEXT_TOKENS.set(8192)
+ # 8192 tokens * 4 chars * 0.35 share.
+ assert tools._tool_result_char_budget() == 11468
+
+
+def test_the_hard_cap_never_cuts_below_the_saved_cap(monkeypatch):
+ monkeypatch.setattr(tools, "MAX_TOOL_TEXT_CHARS", 10000)
+ limit.set_max_chars(50000)
+ assert tools._hard_cap_chars() == 54000
+
+
+def test_a_lowered_setting_does_not_lower_the_hard_cap_for_other_tools(monkeypatch):
+ monkeypatch.setattr(tools, "MAX_TOOL_TEXT_CHARS", 10000)
+ limit.set_max_chars(4000)
+ assert tools._hard_cap_chars() == 20000
+ page = "x" * 15000
+ assert tools.cap_tool_text(page) == page
+
+
[email protected]("value, expected", [("32000", 32000), ("abc", 16000), ("-5", 16000)])
+def test_a_set_environment_variable_decides_as_before(monkeypatch, value, expected):
+ limit.set_max_chars(64000)
+ monkeypatch.setenv(limit.MAX_CHARS_ENV, value)
+ monkeypatch.setattr(tools, "_MAX_OUTPUT_CHARS", tools._env_int(limit.MAX_CHARS_ENV, 16000))
+ assert limit.locked_by_environment() is True
+ assert limit.effective_max_chars() == expected
+ assert tools._tool_result_max_chars() == expected
+
+
+def test_an_environment_raise_still_applies_where_the_window_is_unknown(monkeypatch):
+ monkeypatch.setenv(limit.MAX_CHARS_ENV, "64000")
+ monkeypatch.setattr(tools, "_MAX_OUTPUT_CHARS", 64000)
+ assert tools._tool_result_char_budget() == 64000
+ assert studio_tool_loop._truncate_for_model(FILE_50K) == FILE_50K
+
+
+def test_an_empty_environment_variable_does_not_lock(monkeypatch):
+ monkeypatch.setenv(limit.MAX_CHARS_ENV, "")
+ limit.set_max_chars(64000)
+ assert limit.locked_by_environment() is False
+ assert tools._tool_result_max_chars() == 64000
+
+
[email protected]("value", [1999, 200001, True, None, "x", 1.5])
+def test_setter_rejects_out_of_range(value):
+ with pytest.raises(ValueError):
+ limit.set_max_chars(value)
+
+
+def test_an_unreadable_store_keeps_the_default(monkeypatch):
+ def boom(*_args, **_kwargs):
+ raise RuntimeError("database is locked")
+
+ monkeypatch.setattr(studio_db, "get_app_setting", boom)
+ assert tools._tool_result_max_chars() == 16000
+
+
+def test_a_managed_account_tool_call_reads_the_owner_value():
+ limit.set_max_chars(48000)
+ token = bind_account(ALICE)
+ try:
+ assert tools._tool_result_max_chars() == 48000
+ finally:
+ reset_account(token)
+
+
+def test_route_reads_and_saves():
+ with _client(OWNER) as client:
+ body = client.get("/tool-result-limit").json()
+ assert body == {
+ "max_chars": 16000,
+ "default_chars": 16000,
+ "min_chars": 2000,
+ "max_allowed_chars": 200000,
+ "locked_by_environment": False,
+ }
+ for _ in range(2):
+ response = client.put("/tool-result-limit", json = {"max_chars": 64000})
+ assert response.status_code == 200, response.text
+ assert response.json()["max_chars"] == 64000
+ assert client.get("/tool-result-limit").json()["max_chars"] == 64000
+ assert tools._tool_result_max_chars() == 64000
+
+
[email protected]("value", [1999, 200001, "64000", 1.5, True])
+def test_route_refuses_out_of_range(value):
+ with _client(OWNER) as client:
+ assert client.put("/tool-result-limit", json = {"max_chars": value}).status_code == 422
+ assert limit.saved_max_chars() is None
+
+
+def test_route_refuses_a_save_the_environment_decides(monkeypatch):
+ monkeypatch.setenv(limit.MAX_CHARS_ENV, "32000")
+ with _client(OWNER) as client:
+ body = client.get("/tool-result-limit").json()
+ assert body["max_chars"] == 32000 and body["locked_by_environment"] is True
+ response = client.put("/tool-result-limit", json = {"max_chars": 64000})
+ assert response.status_code == 409
+ assert limit.MAX_CHARS_ENV in response.json()["detail"]
+ assert limit.saved_max_chars() is None
+
+
[email protected]("saved", [4000, 64000])
+def test_non_code_tools_keep_the_install_cap(monkeypatch, saved):
+ """MCP, web and edit results have no spill file, and the row names Python and Terminal only."""
+ limit.set_max_chars(saved)
+ tools._REQUEST_CONTEXT_TOKENS.set(131072)
+ monkeypatch.setattr(tools, "_request_result_room", lambda: 10**9)
+ out = tools._fit_result_to_room(FILE_50K, "mcp__server__tool")
+ assert "truncated to 16000 chars for the model" in out
diff --git a/studio/backend/utils/tool_result_limit.py b/studio/backend/utils/tool_result_limit.py
new file mode 100644
index 00000000000..16225602455
--- /dev/null
+++ b/studio/backend/utils/tool_result_limit.py
@@ -0,0 +1,75 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Settings > Chat tool output limit: how many characters of one tool result the model reads; a set env var wins."""
+
+from __future__ import annotations
+
+import os
+from typing import Any
+
+MAX_CHARS_ENV = "UNSLOTH_TOOL_RESULT_MAX_CHARS"
+MAX_CHARS_SETTING_KEY = "tool_result_max_chars"
+DEFAULT_MAX_CHARS = 16000
+MIN_MAX_CHARS = 2000
+# Below UNSLOTH_TOOL_RESULT_HARD_CAP_CHARS (256,000), so a saved value never outgrows the floor cap on every tool.
+MAX_MAX_CHARS = 200000
+
+
+def _coerce_chars(value: Any) -> int | None:
+ if isinstance(value, bool):
+ return None
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError):
+ return None
+ if parsed < MIN_MAX_CHARS or parsed > MAX_MAX_CHARS:
+ return None
+ return parsed
+
+
+def locked_by_environment() -> bool:
+ # Empty counts as unset, as tools._env_int reads it.
+ return bool(os.environ.get(MAX_CHARS_ENV))
+
+
+def environment_max_chars() -> int:
+ """The env value as tools._env_int reads it: garbage or non-positive falls back to the default."""
+ try:
+ value = int(os.environ.get(MAX_CHARS_ENV, "") or DEFAULT_MAX_CHARS)
+ except (TypeError, ValueError):
+ return DEFAULT_MAX_CHARS
+ return value if value > 0 else DEFAULT_MAX_CHARS
+
+
+def saved_max_chars() -> int | None:
+ """The owner's saved value, or None when there is none (or the store cannot be read)."""
+ try:
+ from storage.studio_db import get_app_setting
+ from utils.account_context import OWNER, run_as
+
+ # Installation-wide: the owner's store, whichever account's tool call is asking.
+ stored = run_as(OWNER, get_app_setting, MAX_CHARS_SETTING_KEY, None)
+ except Exception: # noqa: BLE001 - an unreadable store keeps the shipped default
+ return None
+ return _coerce_chars(stored)
+
+
+def effective_max_chars() -> int:
+ """The cap before a small context window lowers it."""
+ if locked_by_environment():
+ return environment_max_chars()
+ return saved_max_chars() or DEFAULT_MAX_CHARS
+
+
+def set_max_chars(value: Any) -> int:
+ parsed = _coerce_chars(value)
+ if parsed is None:
+ raise ValueError(
+ f"Tool output limit must be a whole number from {MIN_MAX_CHARS} to {MAX_MAX_CHARS} characters."
+ )
+ from storage.studio_db import upsert_app_settings
+ from utils.account_context import OWNER, run_as
+
+ run_as(OWNER, upsert_app_settings, {MAX_CHARS_SETTING_KEY: parsed})
+ return parsed
diff --git a/studio/frontend/src/features/settings/api/tool-result-limit.ts b/studio/frontend/src/features/settings/api/tool-result-limit.ts
new file mode 100644
index 00000000000..893eba08a7e
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/tool-result-limit.ts
@@ -0,0 +1,85 @@
+// 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 { authFetch } from "@/features/auth";
+import { readFastApiError } from "@/lib/format-fastapi-error";
+
+const ROUTE = "/api/settings/tool-result-limit";
+
+export const DEFAULT_TOOL_RESULT_MAX_CHARS = 16000;
+
+// Offered in Settings > Chat; a value saved through the API or set by the env var is shown beside them.
+export const TOOL_RESULT_LIMIT_CHOICES = [
+ 4000, 8000, 16000, 32000, 64000, 128000, 200000,
+] as const;
+
+export type ToolResultLimitSettings = {
+ maxChars: number;
+ defaultChars: number;
+ minChars: number;
+ maxAllowedChars: number;
+ lockedByEnvironment: boolean;
+};
+
+type ApiToolResultLimitSettings = {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ max_chars: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ default_chars?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ min_chars?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ max_allowed_chars?: number;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ locked_by_environment?: boolean;
+};
+
+export function toolResultLimitFromApi(
+ settings: ApiToolResultLimitSettings,
+): ToolResultLimitSettings {
+ return {
+ maxChars: settings.max_chars,
+ defaultChars: settings.default_chars ?? DEFAULT_TOOL_RESULT_MAX_CHARS,
+ minChars: settings.min_chars ?? 2000,
+ maxAllowedChars: settings.max_allowed_chars ?? 200000,
+ lockedByEnvironment: settings.locked_by_environment ?? false,
+ };
+}
+
+/** The presets inside the server's range, plus the current value when it is not one of them. */
+export function toolResultLimitChoices(
+ settings: ToolResultLimitSettings,
+): number[] {
+ const choices: number[] = TOOL_RESULT_LIMIT_CHOICES.filter(
+ (choice) =>
+ choice >= settings.minChars && choice <= settings.maxAllowedChars,
+ );
+ if (!choices.includes(settings.maxChars)) choices.push(settings.maxChars);
+ return choices.sort((a, b) => a - b);
+}
+
+export async function loadToolResultLimit(
+ fallbackMessage: string,
+): Promise<ToolResultLimitSettings> {
+ const res = await authFetch(ROUTE);
+ if (!res.ok) {
+ throw new Error(await readFastApiError(res, fallbackMessage));
+ }
+ return toolResultLimitFromApi(await res.json());
+}
+
+export async function updateToolResultLimit(
+ maxChars: number,
+ fallbackMessage: string,
+): Promise<ToolResultLimitSettings> {
+ const res = await authFetch(ROUTE, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ // biome-ignore lint/style/useNamingConvention: API schema
+ body: JSON.stringify({ max_chars: maxChars }),
+ });
+ if (!res.ok) {
+ throw new Error(await readFastApiError(res, fallbackMessage));
+ }
+ return toolResultLimitFromApi(await res.json());
+}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 87b7bfe2dff..74fee4555b1 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -127,6 +127,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.chat.projectAttachments",
"settings.chat.rememberParamsPerModel",
"settings.chat.autoCompact",
+ "settings.chat.toolResultLimit",
"settings.chat.autoScroll",
"settings.chat.scrollToBottomButton",
"settings.profile.greetingSloth",
@@ -384,6 +385,7 @@ const OWNER_ONLY_ENTRIES: ReadonlySet<TranslationKey> = new Set([
"settings.sandbox.python",
"settings.sandbox.terminal",
"settings.apiKeys.mcp.title",
+ "settings.chat.toolResultLimit",
]);
export function renderedSearchEntries(
@@ -422,6 +424,7 @@ export const SETTINGS_SEARCH_KEYWORDS: Partial<
"settings.resources.modelMemory.noRamReserve":
"settings.resources.modelMemory.modelMemoryKeywords",
"settings.chat.autoCompact": "settings.chat.autoCompactKeywords",
+ "settings.chat.toolResultLimit": "settings.chat.toolResultLimitKeywords",
// match action verbs omitted from these descriptive labels.
"settings.chat.thinking.visibility": "settings.chat.visibilityKeywords",
"settings.chat.tools.visibility": "settings.chat.visibilityKeywords",
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index e6f90857224..c6dddc4062e 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -24,6 +24,7 @@ import {
import { PASTED_TEXT_THRESHOLD_CHOICES } from "@/features/chat/utils/pasted-text";
import { refreshContextUsage } from "@/features/chat/utils/refresh-context-usage";
import { formatBindingLabel, isMacPlatform } from "../lib/keyboard-shortcuts";
+import { useIsAccountOwner } from "@/features/auth";
import { useUserProfileStore } from "@/features/profile";
import { type TranslationKey, useT } from "@/i18n";
import { toast } from "@/lib/toast";
@@ -47,6 +48,12 @@ import {
loadCurrentDatePrompt,
updateCurrentDatePrompt,
} from "../api/current-date-prompt";
+import {
+ type ToolResultLimitSettings,
+ loadToolResultLimit,
+ toolResultLimitChoices,
+ updateToolResultLimit,
+} from "../api/tool-result-limit";
import { SettingsRow } from "../components/settings-row";
import { ComposerSettings } from "../components/composer-settings";
import { SettingsSection } from "../components/settings-section";
@@ -133,7 +140,119 @@ const PLUS_MENU_SETTINGS: {
},
];
+// Install-wide, so owner-only: how much of one tool result the model reads.
+function ToolResultLimitRow() {
+ const t = useT();
+ const [settings, setSettings] = useState<ToolResultLimitSettings | null>(
+ null,
+ );
+ const [error, setError] = useState<string | null>(null);
+ const [saving, setSaving] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ void loadToolResultLimit(t("settings.chat.toolResultLimitLoadError"))
+ .then((loaded) => {
+ if (cancelled) return;
+ setSettings(loaded);
+ setError(null);
+ })
+ .catch((loadError) => {
+ if (cancelled) return;
+ setError(
+ loadError instanceof Error
+ ? loadError.message
+ : t("settings.chat.toolResultLimitLoadError"),
+ );
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [t]);
+
+ const save = async (maxChars: number) => {
+ setSaving(true);
+ setError(null);
+ try {
+ setSettings(
+ await updateToolResultLimit(
+ maxChars,
+ t("settings.chat.toolResultLimitSaveError"),
+ ),
+ );
+ } catch (saveError) {
+ setError(
+ saveError instanceof Error
+ ? saveError.message
+ : t("settings.chat.toolResultLimitSaveError"),
+ );
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const note = settings?.lockedByEnvironment
+ ? t("settings.chat.toolResultLimitLocked")
+ : error;
+ return (
+ <SettingsRow
+ label={t("settings.chat.toolResultLimit")}
+ description={t("settings.chat.toolResultLimitDescription", {
+ count: (
+ settings?.defaultChars ?? 16000
+ ).toLocaleString(),
+ })}
+ hint={t("settings.chat.toolResultLimitHint")}
+ below={
+ note ? (
+ <span
+ role={settings?.lockedByEnvironment ? undefined : "alert"}
+ className={cn(
+ "max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs",
+ settings?.lockedByEnvironment
+ ? "text-muted-foreground"
+ : "text-destructive",
+ )}
+ >
+ {note}
+ </span>
+ ) : null
+ }
+ >
+ <Select
+ value={settings ? String(settings.maxChars) : undefined}
+ disabled={!settings || saving || settings.lockedByEnvironment}
+ onValueChange={(value) => {
+ const next = Number(value);
+ if (settings && next !== settings.maxChars) void save(next);
+ }}
+ >
+ <SelectTrigger
+ className="w-44"
+ aria-label={t("settings.chat.toolResultLimit")}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {settings
+ ? toolResultLimitChoices(settings).map((choice) => (
+ <SelectItem key={choice} value={String(choice)}>
+ {choice === settings.defaultChars
+ ? t("settings.chat.toolResultLimitDefault", {
+ count: choice.toLocaleString(),
+ })
+ : choice.toLocaleString()}
+ </SelectItem>
+ ))
+ : null}
+ </SelectContent>
+ </Select>
+ </SettingsRow>
+ );
+}
+
export function ChatTab() {
+ const isOwner = useIsAccountOwner();
const t = useT();
const navigate = useNavigate();
const plusPins = usePlusMenuPrefsStore((state) => state.pins);
@@ -373,6 +492,7 @@ export function ChatTab() {
onCheckedChange={setAutoCompactEnabled}
/>
</SettingsRow>
+ {isOwner ? <ToolResultLimitRow /> : null}
<SettingsRow
label={t("settings.chat.autoScroll")}
description={t("settings.chat.autoScrollDescription")}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index bc5099ff338..22ce20f19f2 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -2489,6 +2489,15 @@ export const ar = {
"تنتقل الأدوار الأقدم إلى أرشيف قابل للبحث عندما تمتلئ نافذة سياق المحادثة.",
autoCompactKeywords:
"ضغط تلقائي سياق نافذة اقتطاع منزلقة نقطة تحقق هامش أرشيف استرجاع بحث compaction rolling checkpoint headroom archive retrieval rag",
+ toolResultLimit: "طول مخرجات الأدوات",
+ toolResultLimitDescription: "عدد أحرف نتيجة Python أو Terminal الواحدة التي يقرأها النموذج. القيمة الافتراضية {count}.",
+ toolResultLimitHint: "تُحفظ المخرجات الأطول في ملف يمكن للنموذج قراءته على أجزاء. ينطبق الحد الأعلى على النماذج التي تعمل في Unsloth، وتظل نوافذ السياق الصغيرة تحصل على أقل. تحتفظ نماذج API بالقيمة الافتراضية ما لم تخفضها.",
+ toolResultLimitDefault: "{count} (افتراضي)",
+ toolResultLimitLocked: "مضبوط بواسطة UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "تعذر تحميل طول مخرجات الأدوات.",
+ toolResultLimitSaveError: "تعذر حفظ طول مخرجات الأدوات.",
+ toolResultLimitKeywords:
+ "مخرجات نتيجة اقتطاع حد أحرف طول tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "مطوي",
auto: "التوسيع أثناء التشغيل",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 0739b989f27..b02defe0fa6 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -2527,6 +2527,15 @@ export const de = {
"Ältere Runden wandern in ein durchsuchbares Archiv, wenn ein Chat voll läuft.",
autoCompactKeywords:
"Komprimierung automatisch Kontext Fenster kürzen gleitend Prüfpunkt Reserve Archiv Abruf Suche compaction rolling checkpoint headroom archive retrieval rag",
+ toolResultLimit: "Länge der Tool-Ausgabe",
+ toolResultLimitDescription: "Zeichen eines Python- oder Terminal-Ergebnisses, die das Modell liest. Standard ist {count}.",
+ toolResultLimitHint: "Längere Ausgaben werden in einer Datei gespeichert, die das Modell in Teilen lesen kann. Ein höheres Limit gilt für Modelle, die in Unsloth laufen, und kleine Kontextfenster erhalten weiterhin weniger. API-Modelle behalten den Standard, außer du senkst ihn.",
+ toolResultLimitDefault: "{count} (Standard)",
+ toolResultLimitLocked: "Festgelegt durch UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "Die Länge der Tool-Ausgabe konnte nicht geladen werden.",
+ toolResultLimitSaveError: "Die Länge der Tool-Ausgabe konnte nicht gespeichert werden.",
+ toolResultLimitKeywords:
+ "Ausgabe Ergebnis abschneiden gekürzt Grenze Zeichen Länge tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "Eingeklappt",
auto: "Während der Ausführung ausklappen",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 9b7d6634299..9ce5398580d 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2525,6 +2525,15 @@ export const en = {
"Older turns move to a searchable archive when a chat fills its context.",
autoCompactKeywords:
"compaction compact auto-compact context window truncate rolling checkpoint headroom archive retrieval recall rag search",
+ toolResultLimit: "Tool output length",
+ toolResultLimitDescription: "Characters of one Python or Terminal result the model reads. Default is {count}.",
+ toolResultLimitHint: "Longer output is saved to a file the model can read in parts. A higher limit applies to models running in Unsloth, and small context windows still get less. API models keep the default unless you lower it.",
+ toolResultLimitDefault: "{count} (default)",
+ toolResultLimitLocked: "Set by UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "Failed to load the tool output length.",
+ toolResultLimitSaveError: "Failed to save the tool output length.",
+ toolResultLimitKeywords:
+ "tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "Collapsed",
auto: "Expand while running",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index e341211d012..4c28e53939a 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -2518,6 +2518,15 @@ export const es = {
"Los turnos antiguos pasan a un archivo consultable al llenarse el contexto de un chat.",
autoCompactKeywords:
"compactación compactar automáticamente contexto ventana truncar deslizante checkpoint margen archivo recuperación búsqueda compaction rolling headroom archive retrieval rag",
+ toolResultLimit: "Longitud de la salida de herramientas",
+ toolResultLimitDescription: "Caracteres de un resultado de Python o Terminal que lee el modelo. El valor predeterminado es {count}.",
+ toolResultLimitHint: "La salida más larga se guarda en un archivo que el modelo puede leer por partes. Un límite mayor se aplica a los modelos que se ejecutan en Unsloth, y las ventanas de contexto pequeñas siguen recibiendo menos. Los modelos de API mantienen el valor predeterminado salvo que lo bajes.",
+ toolResultLimitDefault: "{count} (predeterminado)",
+ toolResultLimitLocked: "Definido por UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "No se pudo cargar la longitud de la salida de herramientas.",
+ toolResultLimitSaveError: "No se pudo guardar la longitud de la salida de herramientas.",
+ toolResultLimitKeywords:
+ "salida resultado truncar recortar límite caracteres longitud tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "Contraído",
auto: "Expandir mientras se ejecuta",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 0fdc1b3fb12..2fb7c7eb283 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -2524,6 +2524,15 @@ export const fr = {
"Les anciens échanges vont dans une archive consultable quand un chat sature son contexte.",
autoCompactKeywords:
"compaction automatique contexte fenêtre tronquer glissante point de contrôle marge archive récupération recherche rolling checkpoint headroom retrieval rag",
+ toolResultLimit: "Longueur de la sortie des outils",
+ toolResultLimitDescription: "Caractères d'un résultat Python ou Terminal que le modèle lit. Par défaut : {count}.",
+ toolResultLimitHint: "Une sortie plus longue est enregistrée dans un fichier que le modèle peut lire par parties. Une limite plus élevée s'applique aux modèles exécutés dans Unsloth, et les petites fenêtres de contexte reçoivent toujours moins. Les modèles d'API gardent la valeur par défaut sauf si vous la baissez.",
+ toolResultLimitDefault: "{count} (par défaut)",
+ toolResultLimitLocked: "Défini par UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "Impossible de charger la longueur de la sortie des outils.",
+ toolResultLimitSaveError: "Impossible d'enregistrer la longueur de la sortie des outils.",
+ toolResultLimitKeywords:
+ "sortie résultat tronquer tronqué limite caractères longueur tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "Replié",
auto: "Déplier pendant l’exécution",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index f5e73249a6b..518480741c3 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -2593,6 +2593,15 @@ export const he = {
"סבבים ישנים יותר עוברים לארכיון הניתן לחיפוש כאשר צ'אט ממלא את ההקשר שלו.",
autoCompactKeywords:
"compaction compact auto-compact context window truncate rolling checkpoint headroom archive retrieval recall rag search כיווץ קיצוץ הקשר חלון ארכיון אחזור חיפוש",
+ toolResultLimit: "אורך פלט הכלים",
+ toolResultLimitDescription: "מספר התווים מתוצאה אחת של Python או Terminal שהמודל קורא. ברירת המחדל היא {count}.",
+ toolResultLimitHint: "פלט ארוך יותר נשמר בקובץ שהמודל יכול לקרוא בחלקים. מגבלה גבוהה יותר חלה על מודלים שרצים ב-Unsloth, וחלונות הקשר קטנים עדיין מקבלים פחות. מודלי API נשארים בברירת המחדל אלא אם תוריד אותה.",
+ toolResultLimitDefault: "{count} (ברירת מחדל)",
+ toolResultLimitLocked: "מוגדר על ידי UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "טעינת אורך פלט הכלים נכשלה.",
+ toolResultLimitSaveError: "שמירת אורך פלט הכלים נכשלה.",
+ toolResultLimitKeywords:
+ "פלט תוצאה קיצוץ מגבלה תווים אורך tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "מכווץ",
auto: "מורחב בזמן ריצה",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 52a0d3a5181..69b5ca50634 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -2495,6 +2495,15 @@ export const hi = {
"चैट का कॉन्टेक्स्ट भरने पर पुराने टर्न खोजे जा सकने वाले आर्काइव में चले जाते हैं।",
autoCompactKeywords:
"कॉम्पैक्शन कॉम्पैक्ट कॉन्टेक्स्ट विंडो ट्रंकेट स्लाइडिंग चेकपॉइंट हेडरूम आर्काइव पुनर्प्राप्ति खोज compaction rolling checkpoint headroom archive retrieval rag",
+ toolResultLimit: "टूल आउटपुट की लंबाई",
+ toolResultLimitDescription: "Python या Terminal के एक परिणाम के कितने अक्षर मॉडल पढ़ता है। डिफ़ॉल्ट {count} है।",
+ toolResultLimitHint: "लंबा आउटपुट एक फ़ाइल में सहेजा जाता है जिसे मॉडल हिस्सों में पढ़ सकता है। ऊँची सीमा Unsloth में चल रहे मॉडल पर लागू होती है, और छोटी कॉन्टेक्स्ट विंडो को अब भी कम मिलता है। API मॉडल डिफ़ॉल्ट पर रहते हैं, जब तक आप इसे कम न करें।",
+ toolResultLimitDefault: "{count} (डिफ़ॉल्ट)",
+ toolResultLimitLocked: "UNSLOTH_TOOL_RESULT_MAX_CHARS द्वारा सेट",
+ toolResultLimitLoadError: "टूल आउटपुट की लंबाई लोड नहीं हो सकी।",
+ toolResultLimitSaveError: "टूल आउटपुट की लंबाई सहेजी नहीं जा सकी।",
+ toolResultLimitKeywords:
+ "आउटपुट परिणाम काटना सीमा अक्षर लंबाई tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "संक्षिप्त",
auto: "चलने के दौरान विस्तृत करें",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index f67384867a1..7d10eb441b4 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2485,6 +2485,15 @@ export const it = {
"I turni più vecchi passano in un archivio consultabile quando una chat riempie il contesto.",
autoCompactKeywords:
"compattazione automatica contesto finestra troncare scorrevole checkpoint margine archivio recupero ricerca compaction rolling headroom archive retrieval rag",
+ toolResultLimit: "Lunghezza dell'output degli strumenti",
+ toolResultLimitDescription: "Caratteri di un risultato Python o Terminale che il modello legge. Il valore predefinito è {count}.",
+ toolResultLimitHint: "L'output più lungo viene salvato in un file che il modello può leggere a parti. Un limite più alto si applica ai modelli eseguiti in Unsloth, e le finestre di contesto piccole ricevono comunque meno. I modelli API mantengono il valore predefinito a meno che tu non lo abbassi.",
+ toolResultLimitDefault: "{count} (predefinito)",
+ toolResultLimitLocked: "Impostato da UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "Impossibile caricare la lunghezza dell'output degli strumenti.",
+ toolResultLimitSaveError: "Impossibile salvare la lunghezza dell'output degli strumenti.",
+ toolResultLimitKeywords:
+ "output risultato troncare troncato limite caratteri lunghezza tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "Compresso",
auto: "Espandi durante l’esecuzione",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index e852d7529df..1a56c3d1c03 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -2472,6 +2472,15 @@ export const ja = {
"チャットの文脈が満杯になると、古いターンは検索可能なアーカイブに移ります。",
autoCompactKeywords:
"圧縮 自動圧縮 コンテキスト ウィンドウ 切り詰め スライディング チェックポイント 余裕 アーカイブ 検索 取得 compaction rolling headroom archive retrieval rag",
+ toolResultLimit: "ツール出力の長さ",
+ toolResultLimitDescription: "Python またはターミナルの結果 1 件のうち、モデルが読む文字数です。既定値は {count} です。",
+ toolResultLimitHint: "これより長い出力はファイルに保存され、モデルは分割して読めます。上限を上げると Unsloth で動作するモデルに適用され、コンテキストウィンドウが小さい場合は引き続き少なくなります。API モデルは、下げない限り既定値のままです。",
+ toolResultLimitDefault: "{count}(既定)",
+ toolResultLimitLocked: "UNSLOTH_TOOL_RESULT_MAX_CHARS で設定されています",
+ toolResultLimitLoadError: "ツール出力の長さを読み込めませんでした。",
+ toolResultLimitSaveError: "ツール出力の長さを保存できませんでした。",
+ toolResultLimitKeywords:
+ "出力 結果 切り詰め 上限 文字数 長さ tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "折りたたむ",
auto: "実行中は展開",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 2d670abeac4..e9bd7e8a7f8 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -2482,6 +2482,15 @@ export const ko = {
"채팅이 컨텍스트를 모두 채우면 오래된 턴은 검색 가능한 보관소로 옮겨집니다.",
autoCompactKeywords:
"압축 자동 컨텍스트 윈도우 자르기 슬라이딩 체크포인트 여유 보관 검색 회수 compaction rolling checkpoint headroom archive retrieval rag",
+ toolResultLimit: "도구 출력 길이",
+ toolResultLimitDescription: "모델이 읽는 Python 또는 터미널 결과 하나의 문자 수입니다. 기본값은 {count}입니다.",
+ toolResultLimitHint: "더 긴 출력은 모델이 나눠서 읽을 수 있는 파일에 저장됩니다. 더 높은 제한은 Unsloth에서 실행되는 모델에 적용되며, 컨텍스트 창이 작으면 여전히 더 적게 받습니다. API 모델은 낮추지 않는 한 기본값을 유지합니다.",
+ toolResultLimitDefault: "{count} (기본값)",
+ toolResultLimitLocked: "UNSLOTH_TOOL_RESULT_MAX_CHARS로 설정됨",
+ toolResultLimitLoadError: "도구 출력 길이를 불러오지 못했습니다.",
+ toolResultLimitSaveError: "도구 출력 길이를 저장하지 못했습니다.",
+ toolResultLimitKeywords:
+ "출력 결과 잘림 제한 문자 길이 tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "접힘",
auto: "실행 중 펼치기",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 4e9c1919b01..16ddb7da6b2 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -2505,6 +2505,15 @@ export const ptBR = {
"Os turnos antigos vão para um arquivo pesquisável quando um chat enche o contexto.",
autoCompactKeywords:
"compactação compactar automaticamente contexto janela truncar deslizante checkpoint margem arquivo recuperação busca compaction rolling headroom archive retrieval rag",
+ toolResultLimit: "Tamanho da saída das ferramentas",
+ toolResultLimitDescription: "Caracteres de um resultado de Python ou Terminal que o modelo lê. O padrão é {count}.",
+ toolResultLimitHint: "Saídas mais longas são salvas em um arquivo que o modelo pode ler em partes. Um limite maior vale para modelos executados no Unsloth, e janelas de contexto pequenas continuam recebendo menos. Modelos de API mantêm o padrão, a menos que você o reduza.",
+ toolResultLimitDefault: "{count} (padrão)",
+ toolResultLimitLocked: "Definido por UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "Não foi possível carregar o tamanho da saída das ferramentas.",
+ toolResultLimitSaveError: "Não foi possível salvar o tamanho da saída das ferramentas.",
+ toolResultLimitKeywords:
+ "saída resultado truncar cortado limite caracteres tamanho tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "Recolhido",
auto: "Expandir durante a execução",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index eb03f048db5..1bc9be93a4c 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -2501,6 +2501,15 @@ export const ru = {
"Старые ходы уходят в доступный для поиска архив, когда чат заполняет контекст.",
autoCompactKeywords:
"сжатие автоматически контекст окно обрезка скользящее контрольная точка запас архив поиск извлечение compaction rolling checkpoint headroom archive retrieval rag",
+ toolResultLimit: "Длина вывода инструментов",
+ toolResultLimitDescription: "Сколько символов одного результата Python или Терминала читает модель. По умолчанию {count}.",
+ toolResultLimitHint: "Более длинный вывод сохраняется в файл, который модель может читать по частям. Более высокий лимит действует для моделей, запущенных в Unsloth, а маленькие окна контекста по-прежнему получают меньше. API-модели сохраняют значение по умолчанию, если вы его не уменьшите.",
+ toolResultLimitDefault: "{count} (по умолчанию)",
+ toolResultLimitLocked: "Задано через UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "Не удалось загрузить длину вывода инструментов.",
+ toolResultLimitSaveError: "Не удалось сохранить длину вывода инструментов.",
+ toolResultLimitKeywords:
+ "вывод результат обрезка обрезан лимит символы длина tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "Свёрнуто",
auto: "Разворачивать во время работы",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index 1631b36ef30..0ee1be9a3cd 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -2674,6 +2674,15 @@ export const sv = {
"Äldre turer flyttas till ett sökbart arkiv när en chatt fyller sin kontext.",
autoCompactKeywords:
"komprimering komprimera autokomprimering kontextfönster trunkera rullande kontrollpunkt marginal arkiv hämtning återkallning rag sök compaction compact auto-compact context window truncate rolling checkpoint headroom archive retrieval recall search",
+ toolResultLimit: "Längd på verktygsutdata",
+ toolResultLimitDescription: "Tecken i ett Python- eller Terminal-resultat som modellen läser. Standard är {count}.",
+ toolResultLimitHint: "Längre utdata sparas i en fil som modellen kan läsa i delar. En högre gräns gäller modeller som körs i Unsloth, och små kontextfönster får fortfarande mindre. API-modeller behåller standardvärdet om du inte sänker det.",
+ toolResultLimitDefault: "{count} (standard)",
+ toolResultLimitLocked: "Anges av UNSLOTH_TOOL_RESULT_MAX_CHARS",
+ toolResultLimitLoadError: "Det gick inte att läsa in längden på verktygsutdata.",
+ toolResultLimitSaveError: "Det gick inte att spara längden på verktygsutdata.",
+ toolResultLimitKeywords:
+ "utdata resultat trunkera avkortad gräns tecken längd tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "Hopfälld",
auto: "Fäll ut medan den körs",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 908d4a9c0a4..d591034a765 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -2449,6 +2449,15 @@ export const zhCN = {
"聊天填满上下文时,较早的轮次会转入可检索的归档。",
autoCompactKeywords:
"压缩 自动压缩 上下文 窗口 截断 滑动 检查点 余量 归档 检索 搜索 compaction rolling checkpoint headroom archive retrieval rag",
+ toolResultLimit: "工具输出长度",
+ toolResultLimitDescription: "模型读取的单个 Python 或终端结果的字符数。默认值为 {count}。",
+ toolResultLimitHint: "更长的输出会保存到文件中,模型可以分段读取。更高的上限适用于在 Unsloth 中运行的模型,上下文窗口较小时仍会获得更少的内容。API 模型保持默认值,除非你将其调低。",
+ toolResultLimitDefault: "{count}(默认)",
+ toolResultLimitLocked: "由 UNSLOTH_TOOL_RESULT_MAX_CHARS 设置",
+ toolResultLimitLoadError: "无法加载工具输出长度。",
+ toolResultLimitSaveError: "无法保存工具输出长度。",
+ toolResultLimitKeywords:
+ "输出 结果 截断 限制 字符 长度 tool output result truncate truncated truncation limit cap characters chars length terminal python",
visibility: {
collapsed: "折叠",
auto: "运行时展开",
diff --git a/studio/frontend/tests/settings-search.test.ts b/studio/frontend/tests/settings-search.test.ts
index bc7412102f1..9259616e92e 100644
--- a/studio/frontend/tests/settings-search.test.ts
+++ b/studio/frontend/tests/settings-search.test.ts
@@ -149,3 +149,18 @@ test("agent access (MCP) is found by the protocol and the agents' names, by the
),
);
});
+
+const TOOL_RESULT_LIMIT_ENTRY = "settings.chat.toolResultLimit";
+
+test("the tool output length is found by truncate and limit, by the owner only", () => {
+ const index = createSettingsSearchIndex({ desktop: false, closeToTray: false });
+ assert.ok(index.chat.includes(TOOL_RESULT_LIMIT_ENTRY));
+ const haystack =
+ `${en.settings.chat.toolResultLimit} ${en.settings.chat.toolResultLimitKeywords}`.toLowerCase();
+ for (const term of ["truncat", "limit", "tool output", "characters"]) {
+ assert.ok(haystack.includes(term), `search matches "${term}"`);
+ }
+ assert.ok(!haystack.split(/\s+/).includes("mcp"), "MCP results keep the install cap");
+ assert.ok(renderedSearchEntries(index, "chat", "huggingface", true).includes(TOOL_RESULT_LIMIT_ENTRY));
+ assert.ok(!renderedSearchEntries(index, "chat", "huggingface", false).includes(TOOL_RESULT_LIMIT_ENTRY));
+});
diff --git a/studio/frontend/tests/tool-result-limit-setting.test.ts b/studio/frontend/tests/tool-result-limit-setting.test.ts
new file mode 100644
index 00000000000..52971d84ddf
--- /dev/null
+++ b/studio/frontend/tests/tool-result-limit-setting.test.ts
@@ -0,0 +1,112 @@
+// 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 assert from "node:assert/strict";
+import test from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Settings = {
+ maxChars: number;
+ defaultChars: number;
+ minChars: number;
+ maxAllowedChars: number;
+ lockedByEnvironment: boolean;
+};
+
+type Api = {
+ loadToolResultLimit: (fallback: string) => Promise<Settings>;
+ updateToolResultLimit: (maxChars: number, fallback: string) => Promise<Settings>;
+ toolResultLimitChoices: (settings: Settings) => number[];
+};
+
+type Call = { url: string; init?: RequestInit };
+
+function loadApi(respond: (call: Call) => Response): { api: Api; calls: Call[] } {
+ const calls: Call[] = [];
+ const api = loadWithStubs<Api>(
+ new URL("../src/features/settings/api/tool-result-limit.ts", import.meta.url),
+ {
+ "@/features/auth": {
+ authFetch: async (url: string, init?: RequestInit) => {
+ const call = { url, init };
+ calls.push(call);
+ return respond(call);
+ },
+ },
+ "@/lib/format-fastapi-error": {
+ readFastApiError: async (response: Response, fallback: string) => {
+ const body = (await response.json().catch(() => null)) as {
+ detail?: string;
+ } | null;
+ return body?.detail ?? fallback;
+ },
+ },
+ },
+ { relativePassthrough: true },
+ );
+ return { api, calls };
+}
+
+const json = (body: unknown, status = 200) =>
+ new Response(JSON.stringify(body), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+
+const API_BODY = {
+ max_chars: 16000,
+ default_chars: 16000,
+ min_chars: 2000,
+ max_allowed_chars: 200000,
+ locked_by_environment: false,
+};
+
+test("loads the limit from the settings route", async () => {
+ const { api, calls } = loadApi(() => json(API_BODY));
+ const settings = await api.loadToolResultLimit("fallback");
+ assert.equal(calls[0].url, "/api/settings/tool-result-limit");
+ assert.deepEqual(settings, {
+ maxChars: 16000,
+ defaultChars: 16000,
+ minChars: 2000,
+ maxAllowedChars: 200000,
+ lockedByEnvironment: false,
+ });
+});
+
+test("saves with a PUT of max_chars", async () => {
+ const { api, calls } = loadApi(() => json({ ...API_BODY, max_chars: 64000 }));
+ const settings = await api.updateToolResultLimit(64000, "fallback");
+ assert.equal(calls[0].init?.method, "PUT");
+ assert.deepEqual(JSON.parse(String(calls[0].init?.body)), { max_chars: 64000 });
+ assert.equal(settings.maxChars, 64000);
+});
+
+test("a refused save surfaces the server's reason", async () => {
+ const { api } = loadApi(() =>
+ json({ detail: "UNSLOTH_TOOL_RESULT_MAX_CHARS is set" }, 409),
+ );
+ await assert.rejects(
+ api.updateToolResultLimit(64000, "fallback"),
+ /UNSLOTH_TOOL_RESULT_MAX_CHARS is set/,
+ );
+});
+
+test("choices keep the presets in range and add a value that is not one", () => {
+ const { api } = loadApi(() => json(API_BODY));
+ const base = {
+ maxChars: 16000,
+ defaultChars: 16000,
+ minChars: 2000,
+ maxAllowedChars: 200000,
+ lockedByEnvironment: false,
+ };
+ assert.deepEqual(api.toolResultLimitChoices(base), [
+ 4000, 8000, 16000, 32000, 64000, 128000, 200000,
+ ]);
+ assert.deepEqual(
+ api.toolResultLimitChoices({ ...base, maxChars: 50000, lockedByEnvironment: true }),
+ [4000, 8000, 16000, 32000, 50000, 64000, 128000, 200000],
+ );
+});