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: raise the chat template limit from 64 KiB to 512 KiB (#14934)
Daniel Han85ee7d9032a7
diff --git a/studio/backend/picker/schemas.py b/studio/backend/picker/schemas.pyindex c32cce3065e..ec2866c0add 100644--- a/studio/backend/picker/schemas.py+++ b/studio/backend/picker/schemas.py@@ -5,9 +5,11 @@ from typing import Optionalfrom pydantic import BaseModel, Field, field_validator-# Mirror the frontend's 64 KiB chat-template contract (per-model-config.ts) at the API boundary:-# MaxBodyMiddleware only caps the whole request body, not this field.-MAX_CHAT_TEMPLATE_BYTES = 65_536+# Mirror the frontend's chat-template contract (per-model-config.ts) at the API boundary:+# MaxBodyMiddleware only caps the whole request body, not this field. Community templates+# reach ~230 KB (#14841); the frontend keeps overrides in a 1 MiB per-model storage budget,+# so this stays well under it even after JSON escaping.+MAX_CHAT_TEMPLATE_BYTES = 512 * 1024def chat_template_byte_length(value: str) -> Optional[int]:diff --git a/studio/backend/tests/test_model_picker_regression.py b/studio/backend/tests/test_model_picker_regression.pyindex 95c3824c7b6..befbb67601f 100644--- a/studio/backend/tests/test_model_picker_regression.py+++ b/studio/backend/tests/test_model_picker_regression.py@@ -5,8 +5,10 @@from __future__ import annotations+import mathimport sysimport types+from pathlib import Pathimport pytest@@ -176,6 +178,54 @@ def test_chat_template_over_byte_limit_is_rejected():_load_request(chat_template_override = multibyte)+def _large_community_template(target_bytes: int) -> str:+ # Shaped like the large community templates in #14841: one long chain of role branches.+ branch = (+ "{%- elif message['role'] == 'persona_{i}' -%}"+ "{{ '<|im_start|>persona_{i}\\n' + message['content'] | trim + '<|im_end|>\\n' }}\n"+ )+ body, i = [], 0+ while sum(map(len, body)) < target_bytes:+ body.append(branch.replace("{i}", str(i)))+ i += 1+ return (+ "{%- for message in messages -%}\n"+ "{%- if message['role'] == 'system' -%}{{ message['content'] }}\n"+ + "".join(body)+ + "{%- endif -%}{%- endfor -%}"+ )+++def test_large_community_chat_template_is_accepted_end_to_end():+ from picker.schemas import ValidateChatTemplateRequest+ from picker.service import validate_chat_template+ from utils import openai_auto_switch_settings as settings++ template = _large_community_template(230 * 1024)+ assert len(template.encode("utf-8")) > 230 * 1024+ assert _load_request(chat_template_override = template).chat_template_override == template+ assert ValidateChatTemplateRequest(template = template).template == template+ assert validate_chat_template(template).valid+ stored = settings.normalize_model_override({"chat_template_override": template})+ assert stored["chat_template_override"] == template+++def test_frontend_chat_template_limit_matches_backend():+ import re++ from utils import openai_auto_switch_settings as settings++ ts = (+ Path(__file__).resolve().parents[2]+ / "frontend/src/features/model-picker/model-config/per-model-config.ts"+ ).read_text(encoding = "utf-8")+ match = re.search(r"export const MAX_CHAT_TEMPLATE_BYTES = ([0-9_ *]+);", ts)+ assert match is not None+ frontend_limit = math.prod(int(part) for part in match.group(1).replace("_", "").split("*"))+ assert frontend_limit == MAX_CHAT_TEMPLATE_BYTES+ assert settings.MAX_CHAT_TEMPLATE_OVERRIDE_BYTES == MAX_CHAT_TEMPLATE_BYTES++def test_read_bounded_text_reads_within_limit(tmp_path):p = tmp_path / "t.json"p.write_text("hello", encoding = "utf-8")diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.pyindex 341c0399c17..e37778525ce 100644--- a/studio/backend/utils/openai_auto_switch_settings.py+++ b/studio/backend/utils/openai_auto_switch_settings.py@@ -12,6 +12,7 @@ import threadingimport timefrom typing import Any, Mapping, Optional+from picker.schemas import MAX_CHAT_TEMPLATE_BYTESfrom utils.reasoning_budget import validate_reasoning_budget_messagefrom utils.account_context import OWNER, AccountContext, current_account, is_owner_context, run_as@@ -389,7 +390,7 @@ BATCH_SIZE_MIN = 1BATCH_SIZE_MAX = 65536MAX_SEQ_LENGTH_CEILING = 1048576-MAX_CHAT_TEMPLATE_OVERRIDE_BYTES = 65_536+MAX_CHAT_TEMPLATE_OVERRIDE_BYTES = MAX_CHAT_TEMPLATE_BYTES# Highest device index a gpu_ids entry may name; also bounds how many ids one entry holds.MAX_GPU_ID = 1024diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.tsindex 1e37b14c4c9..609412e285b 100644--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts@@ -456,7 +456,8 @@ const PRE_EXTRA_ARGS_SCHEMA_VERSION = 2;const PRE_BATCH_SCHEMA_VERSION = 1;const MAX_ENTRIES = 500;const MAX_PER_MODEL_CONFIG_STORAGE_BYTES = 1024 * 1024;-export const MAX_CHAT_TEMPLATE_BYTES = 65_536;+// Mirrors MAX_CHAT_TEMPLATE_BYTES in backend/picker/schemas.py.+export const MAX_CHAT_TEMPLATE_BYTES = 512 * 1024;export const MAX_REASONING_BUDGET_MESSAGE_BYTES = 8_192;export function isReasoningBudgetMessageValid(value: string): boolean {diff --git a/studio/frontend/tests/chat-template-size-limit.test.ts b/studio/frontend/tests/chat-template-size-limit.test.tsnew file mode 100644index 00000000000..ad17a814511--- /dev/null+++ b/studio/frontend/tests/chat-template-size-limit.test.ts@@ -0,0 +1,80 @@+// 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 {+ installLocalStorageFake,+ registerStoreStubResolver,+} from "./helpers/kit.ts";++registerStoreStubResolver();+const { store } = installLocalStorageFake();+const {+ DEFAULT_PER_MODEL_CONFIG,+ MAX_CHAT_TEMPLATE_BYTES,+ isChatTemplateWithinLimit,+ resolveInitialConfig,+ savePerModelConfig,+} = await import(+ "../src/features/model-picker/model-config/per-model-config.ts"+);++const MODEL = "DavidAU/custom-template-GGUF";+const VARIANT = "Q4_K_M";++function templateOfBytes(bytes: number, unit: string): string {+ return unit.repeat(Math.ceil(bytes / unit.length)).slice(0, bytes);+}++test("a ~230 KB community chat template saves and reloads (#14841)", () => {+ store.clear();+ const template = templateOfBytes(+ 230 * 1024,+ "{%- if message['role'] == 'user' -%}{{ message['content'] }}{%- endif -%}\n",+ );+ assert.equal(isChatTemplateWithinLimit(template), true);+ assert.equal(+ savePerModelConfig(MODEL, VARIANT, {+ ...DEFAULT_PER_MODEL_CONFIG,+ chatTemplateOverride: template,+ }),+ true,+ );+ assert.equal(+ resolveInitialConfig(MODEL, VARIANT).config.chatTemplateOverride,+ template,+ );+});++test("a template at the cap still fits the storage budget after JSON escaping", () => {+ store.clear();+ // Newlines and double quotes grow when serialized; single quotes do not.+ const template = templateOfBytes(+ MAX_CHAT_TEMPLATE_BYTES,+ '{{- "<|im_start|>" + message["role"] + "\\n" -}}\n',+ );+ assert.equal(+ savePerModelConfig(MODEL, VARIANT, {+ ...DEFAULT_PER_MODEL_CONFIG,+ chatTemplateOverride: template,+ }),+ true,+ );+ assert.equal(+ resolveInitialConfig(MODEL, VARIANT).config.chatTemplateOverride,+ template,+ );+});++test("a template over the cap is still refused", () => {+ const template = "a".repeat(MAX_CHAT_TEMPLATE_BYTES + 1);+ assert.equal(isChatTemplateWithinLimit(template), false);+ assert.equal(+ savePerModelConfig(MODEL, VARIANT, {+ ...DEFAULT_PER_MODEL_CONFIG,+ chatTemplateOverride: template,+ }),+ false,+ );+});