Skip to content

Commit 55d24d7

Browse files
feat(studio): editable context length with Apply/Reset for GGUF settings (#4592)
* feat(studio): editable context length with Apply/Reset for GGUF model settings Previously the Context Length field was read-only and the backend hardcoded `-c 0`, ignoring custom values entirely. KV Cache Dtype also triggered an immediate model reload with no way to cancel. Backend: - llama_cpp.py: pass the actual n_ctx value to `-c` instead of always 0 - models/inference.py: relax max_seq_length to 0..1048576 (0 = model default) so GGUF models with large context windows are supported Frontend: - chat-runtime-store: add customContextLength and loadedKvCacheDtype state fields for dirty tracking - chat-settings-sheet: make Context Length an editable number input, stop KV Cache Dtype from auto-reloading, show Apply/Reset buttons when either setting has been changed - use-chat-model-runtime: send customContextLength as max_seq_length in the load request, reset after successful load * fix: preserve maxSeqLength for non-GGUF models in load request customContextLength ?? 0 sent max_seq_length=0 for non-GGUF models, breaking the finetuning/inference path that needs the slider value. Now uses a three-way branch: - customContextLength set: use it (user edited GGUF context) - GGUF without custom: 0 (model's native context) - Non-GGUF: maxSeqLength from the sampling slider * fix: keep max_seq_length default at 4096 for non-GGUF callers Only relax the bounds (ge=0 for GGUF's "model default" mode, le=1048576 for large context windows). The default stays at 4096 so API callers that omit max_seq_length still get a sane value for non-GGUF models. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix(studio): rename trust remote code toggle and hide when no model selected - Rename "Trust remote code" to "Enable custom code" - Shorten subtitle to "Only enable if sure" - Hide the toggle when no model is loaded (already hidden for GGUFs) * fix: restore ge=128 for max_seq_length validation Keep the minimum at 128 so the API rejects nonsensical values. GGUF path now sends the model's native context length (from ggufContextLength) instead of 0 when the user has not customized it. The upper bound stays at 1048576 for large-context GGUF models. * feat(studio): replace Context Length input with slider Use a ParamSlider (512 to model's native context, step 512) instead of a small number input. Shows "Max" when at the model's native context length. Consistent with the other slider controls in the settings panel. * feat(studio): add editable number input alongside Context Length slider The slider and number input stay synced -- dragging the slider updates the number, typing a number moves the slider. The input also accepts values beyond the slider range for power users who need custom context lengths larger than the model default. * fix(studio): widen context length input and use 1024 step for slider Make the number input wider (100px) so large values like 262144 are fully visible. Change slider step from 512 to 1024 and min from 512 to 1024. * fix(studio): context length number input increments by 1024 * fix(studio): cap context length input at model's native max Adds max attribute and clamps typed/incremented values so the context length cannot exceed the GGUF model's reported context window. * fix(studio): point "What's new" link to changelog page Changed from /blog to /docs/new/changelog. * fix(studio): preserve custom context length after Apply, remove stale subtitle - After a reload with a custom context length, keep the user's value in the UI instead of snapping back to the model's native max. ggufContextLength always reports the model's native metadata value regardless of what -c was passed, so we need to preserve customContextLength when it differs from native. - Remove "Reload to apply." from KV Cache Dtype subtitle since the Apply/Reset buttons now handle this. * feat(studio): auto-enable Search and Code tools when model supports them Previously toolsEnabled and codeToolsEnabled stayed false after loading a model even if it reported supports_tools=true. Now both toggles are automatically enabled when the loaded model supports tool calling, matching the existing behavior for reasoning. * fix(studio): auto-enable tools in autoLoadSmallestModel path The suggestion cards trigger autoLoadSmallestModel which bypasses selectModel entirely. It was hardcoding toolsEnabled: false and codeToolsEnabled: false even when the model supports tool calling. Now both are set from the load response, matching the selectModel behavior. Also sets kvCacheDtype/loadedKvCacheDtype for dirty tracking consistency. * fix(studio): re-read tool flags after auto-loading model The runtime state was captured once at the start of the chat adapter's run(), before autoLoadSmallestModel() executes. After auto-load enables tools in the store, the request was still built with the stale snapshot that had toolsEnabled=false. Now re-reads the store after auto-load so the first message includes tools. * fix(studio): re-read entire runtime state after auto-load, not just tools The runtime snapshot (including params.checkpoint, model id, and all tool/reasoning flags) was captured once before auto-load. After autoLoadSmallestModel sets the checkpoint and enables tools, the request was still built with stale params (empty checkpoint, tools disabled). Now re-reads the full store state after auto-load so the first message has the correct model, tools, and reasoning flags. * feat(studio): add Hugging Face token field in Preferences Adds a password input under Configuration > Preferences for users to enter their HF token. The token is persisted in localStorage and passed to all model validate/load/download calls, replacing the previously hardcoded null. This enables downloading gated and private models. * fix(studio): use model native context for GGUF auto-load, show friendly errors The auto-load paths and selectModel for GGUF were sending max_seq_length=4096 which now actually limits the context window (since we fixed the backend to respect n_ctx). Changed to send 0 for GGUF, which means "use model's native context size". Also replaced generic "An internal error occurred" messages with user-friendly descriptions for known errors like context size exceeded and lost connections. LoadRequest validation changed to ge=0 to allow the GGUF "model default" signal. The frontend slider still enforces min=128 for non-GGUF models. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix(studio): filter out FP8 models from model search results Hide models matching *-FP8-* or *FP8-Dynamic* from both the recommended list and HF search results. These models are not yet supported in the inference UI. --------- Co-authored-by: Daniel Han <danielhanchen@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 6d6008a commit 55d24d7

10 files changed

Lines changed: 208 additions & 47 deletions

File tree

studio/backend/core/inference/llama_cpp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -848,7 +848,7 @@ def load_model(
848848
"--port",
849849
str(self._port),
850850
"-c",
851-
"0", # 0 = use model's native context size
851+
str(n_ctx) if n_ctx > 0 else "0", # 0 = model's native context size
852852
"--parallel",
853853
"1", # Single-user studio, saves VRAM
854854
"--flash-attn",

studio/backend/models/inference.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@ class LoadRequest(BaseModel):
2222
None, description = "HuggingFace token for gated models"
2323
)
2424
max_seq_length: int = Field(
25-
4096, ge = 128, le = 32768, description = "Maximum sequence length"
25+
0,
26+
ge = 0,
27+
le = 1048576,
28+
description = "Maximum sequence length (0 = model default for GGUF)",
2629
)
2730
load_in_4bit: bool = Field(True, description = "Load model in 4-bit quantization")
2831
is_lora: bool = Field(False, description = "Whether this is a LoRA adapter")

studio/backend/routes/inference.py

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,27 @@
1919
import threading
2020

2121

22+
import re as _re
23+
24+
25+
def _friendly_error(exc: Exception) -> str:
26+
"""Extract a user-friendly message from known llama-server errors."""
27+
msg = str(exc)
28+
m = _re.search(
29+
r"request \((\d+) tokens?\) exceeds the available context size \((\d+) tokens?\)",
30+
msg,
31+
)
32+
if m:
33+
return (
34+
f"Message too long: {m.group(1)} tokens exceeds the {m.group(2)}-token "
35+
f"context window. Try increasing the Context Length in Model settings, "
36+
f"or shorten the conversation."
37+
)
38+
if "Lost connection to llama-server" in msg:
39+
return "Lost connection to the model server. It may have crashed -- try reloading the model."
40+
return "An internal error occurred"
41+
42+
2243
# Add backend directory to path
2344
backend_path = Path(__file__).parent.parent.parent
2445
if str(backend_path) not in sys.path:
@@ -550,7 +571,7 @@ async def stream():
550571
except Exception as e:
551572
backend.reset_generation_state()
552573
logger.error(f"Error during generation: {e}", exc_info = True)
553-
yield f"data: {json.dumps({'error': 'An internal error occurred'})}\n\n"
574+
yield f"data: {json.dumps({'error': _friendly_error(e)})}\n\n"
554575

555576
return StreamingResponse(
556577
stream(),
@@ -944,7 +965,7 @@ async def audio_input_stream():
944965
logger.error(
945966
f"Error during audio input streaming: {e}", exc_info = True
946967
)
947-
yield f"data: {json.dumps({'error': {'message': 'An internal error occurred', 'type': 'server_error'}})}\n\n"
968+
yield f"data: {json.dumps({'error': {'message': _friendly_error(e), 'type': 'server_error'}})}\n\n"
948969

949970
return StreamingResponse(
950971
audio_input_stream(),
@@ -1176,7 +1197,7 @@ async def gguf_tool_stream():
11761197
logger.error(f"Error during GGUF tool streaming: {e}\n{tb}")
11771198
error_chunk = {
11781199
"error": {
1179-
"message": "An internal error occurred",
1200+
"message": _friendly_error(e),
11801201
"type": "server_error",
11811202
},
11821203
}
@@ -1314,7 +1335,7 @@ async def gguf_stream_chunks():
13141335
logger.error(f"Error during GGUF streaming: {e}", exc_info = True)
13151336
error_chunk = {
13161337
"error": {
1317-
"message": "An internal error occurred",
1338+
"message": _friendly_error(e),
13181339
"type": "server_error",
13191340
},
13201341
}
@@ -1495,7 +1516,7 @@ async def stream_chunks():
14951516
logger.error(f"Error during OpenAI streaming: {e}", exc_info = True)
14961517
error_chunk = {
14971518
"error": {
1498-
"message": "An internal error occurred",
1519+
"message": _friendly_error(e),
14991520
"type": "server_error",
15001521
},
15011522
}

studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,8 @@ export function HubModelPicker({
454454
const recommendedIds = useMemo(() => {
455455
const all = dedupe([...models.map((model) => model.id), value ?? ""])
456456
.filter((id) => !downloadedSet.has(id.toLowerCase()))
457-
.filter((id) => !chatOnly || isGgufRepo(id));
457+
.filter((id) => !chatOnly || isGgufRepo(id))
458+
.filter((id) => !/-FP8[-.]|FP8-Dynamic/i.test(id));
458459
// Sort: GGUFs first, then hub models
459460
const gguf: string[] = [];
460461
const hub: string[] = [];
@@ -498,7 +499,8 @@ export function HubModelPicker({
498499
return results
499500
.map((result) => result.id)
500501
.filter((id) => !recommendedSet.has(id))
501-
.filter((id) => !chatOnly || isGgufRepo(id));
502+
.filter((id) => !chatOnly || isGgufRepo(id))
503+
.filter((id) => !/-FP8[-.]|FP8-Dynamic/i.test(id));
502504
}, [recommendedSet, results, showHfSection, chatOnly]);
503505

504506
const metricsById = useMemo(

studio/frontend/src/features/chat/api/chat-adapter.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ function waitForModelReady(abortSignal?: AbortSignal): Promise<void> {
253253
* falls back to smallest cached safetensors model.
254254
*/
255255
async function autoLoadSmallestModel(): Promise<boolean> {
256+
const hfToken = useChatRuntimeStore.getState().hfToken || null;
256257
const toastId = toast("Loading a model…", {
257258
description: "Auto-selecting the smallest downloaded model.",
258259
duration: 5000,
@@ -278,8 +279,8 @@ async function autoLoadSmallestModel(): Promise<boolean> {
278279
const variant = downloaded[0];
279280
const loadResp = await loadModel({
280281
model_path: repo.repo_id,
281-
hf_token: null,
282-
max_seq_length: 4096,
282+
hf_token: hfToken,
283+
max_seq_length: 0,
283284
load_in_4bit: true,
284285
is_lora: false,
285286
gguf_variant: variant.quant,
@@ -308,8 +309,10 @@ async function autoLoadSmallestModel(): Promise<boolean> {
308309
supportsReasoning: loadResp.supports_reasoning ?? false,
309310
reasoningEnabled: loadResp.supports_reasoning ?? false,
310311
supportsTools: loadResp.supports_tools ?? false,
311-
toolsEnabled: false,
312-
codeToolsEnabled: false,
312+
toolsEnabled: loadResp.supports_tools ?? false,
313+
codeToolsEnabled: loadResp.supports_tools ?? false,
314+
kvCacheDtype: loadResp.cache_type_kv ?? null,
315+
loadedKvCacheDtype: loadResp.cache_type_kv ?? null,
313316
defaultChatTemplate: loadResp.chat_template ?? null,
314317
chatTemplateOverride: null,
315318
});
@@ -329,7 +332,7 @@ async function autoLoadSmallestModel(): Promise<boolean> {
329332
try {
330333
const sfLoadResp = await loadModel({
331334
model_path: repo.repo_id,
332-
hf_token: null,
335+
hf_token: hfToken,
333336
max_seq_length: 4096,
334337
load_in_4bit: true,
335338
is_lora: false,
@@ -366,8 +369,8 @@ async function autoLoadSmallestModel(): Promise<boolean> {
366369
try {
367370
const loadResp = await loadModel({
368371
model_path: "unsloth/Qwen3.5-4B-GGUF",
369-
hf_token: null,
370-
max_seq_length: 4096,
372+
hf_token: hfToken,
373+
max_seq_length: 0,
371374
load_in_4bit: true,
372375
is_lora: false,
373376
gguf_variant: "UD-Q4_K_XL",
@@ -391,7 +394,10 @@ async function autoLoadSmallestModel(): Promise<boolean> {
391394
supportsReasoning: loadResp.supports_reasoning ?? false,
392395
reasoningEnabled: loadResp.supports_reasoning ?? false,
393396
supportsTools: loadResp.supports_tools ?? false,
394-
toolsEnabled: false,
397+
toolsEnabled: loadResp.supports_tools ?? false,
398+
codeToolsEnabled: loadResp.supports_tools ?? false,
399+
kvCacheDtype: loadResp.cache_type_kv ?? null,
400+
loadedKvCacheDtype: loadResp.cache_type_kv ?? null,
395401
defaultChatTemplate: loadResp.chat_template ?? null,
396402
chatTemplateOverride: null,
397403
});
@@ -410,8 +416,7 @@ async function autoLoadSmallestModel(): Promise<boolean> {
410416
export function createOpenAIStreamAdapter(): ChatModelAdapter {
411417
return {
412418
async *run({ messages, abortSignal, unstable_threadId }) {
413-
const runtime = useChatRuntimeStore.getState();
414-
const { params } = runtime;
419+
let runtime = useChatRuntimeStore.getState();
415420

416421
// Wait for in-progress model load to finish before inferring
417422
if (runtime.modelLoading) {
@@ -430,6 +435,9 @@ export function createOpenAIStreamAdapter(): ChatModelAdapter {
430435
}
431436
}
432437

438+
// Re-read store after potential auto-load / model ready wait
439+
runtime = useChatRuntimeStore.getState();
440+
const { params } = runtime;
433441
const {
434442
supportsTools,
435443
toolsEnabled,

studio/frontend/src/features/chat/chat-settings-sheet.tsx

Lines changed: 90 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,14 @@ export function ChatSettingsPanel({
279279
const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);
280280
const kvCacheDtype = useChatRuntimeStore((s) => s.kvCacheDtype);
281281
const setKvCacheDtype = useChatRuntimeStore((s) => s.setKvCacheDtype);
282+
const loadedKvCacheDtype = useChatRuntimeStore((s) => s.loadedKvCacheDtype);
283+
const customContextLength = useChatRuntimeStore((s) => s.customContextLength);
284+
const setCustomContextLength = useChatRuntimeStore((s) => s.setCustomContextLength);
285+
286+
const ctxDisplayValue = customContextLength ?? ggufContextLength ?? "";
287+
const kvDirty = kvCacheDtype !== loadedKvCacheDtype;
288+
const ctxDirty = customContextLength !== null;
289+
const modelSettingsDirty = kvDirty || ctxDirty;
282290
const [customPresets, setCustomPresets] = useState<Preset[]>(() =>
283291
loadSavedCustomPresets(),
284292
);
@@ -467,32 +475,53 @@ export function ChatSettingsPanel({
467475
<div className="flex flex-col gap-3 py-1">
468476
{isGguf && (
469477
<>
470-
<div className="flex items-center justify-between gap-3">
471-
<div className="min-w-0">
472-
<div className="text-xs font-medium">Context Length</div>
473-
<div className="text-[11px] text-muted-foreground">
474-
Reported by the loaded GGUF model.
475-
</div>
478+
<div className="space-y-2">
479+
<div className="flex items-center justify-between">
480+
<span className="text-xs font-medium">Context Length</span>
481+
<Input
482+
type="number"
483+
value={typeof ctxDisplayValue === "number" ? ctxDisplayValue : (ggufContextLength ?? "")}
484+
placeholder="..."
485+
min={128}
486+
max={ggufContextLength ?? undefined}
487+
step={1024}
488+
className="h-6 w-[100px] text-right text-xs tabular-nums"
489+
onChange={(e) => {
490+
const raw = e.target.value;
491+
if (raw === "") {
492+
setCustomContextLength(null);
493+
return;
494+
}
495+
const v = parseInt(raw, 10);
496+
if (!Number.isNaN(v) && v >= 0) {
497+
const maxCtx = ggufContextLength ?? Infinity;
498+
const clamped = Math.min(v, maxCtx);
499+
setCustomContextLength(clamped === (ggufContextLength ?? 0) ? null : clamped);
500+
}
501+
}}
502+
/>
476503
</div>
477-
<Input
478-
value={ggufContextLength ?? ""}
479-
placeholder="Loading..."
480-
disabled={true}
481-
className="h-7 w-[90px] text-xs"
504+
<Slider
505+
min={1024}
506+
max={ggufContextLength ?? 4096}
507+
step={1024}
508+
value={[Math.min(typeof ctxDisplayValue === "number" ? ctxDisplayValue : (ggufContextLength ?? 4096), ggufContextLength ?? 4096)]}
509+
onValueChange={([v]) => {
510+
setCustomContextLength(v === (ggufContextLength ?? 0) ? null : v);
511+
}}
482512
/>
483513
</div>
484514
<div className="flex items-center justify-between gap-3">
485515
<div className="min-w-0">
486516
<div className="text-xs font-medium">KV Cache Dtype</div>
487517
<div className="text-[11px] text-muted-foreground">
488-
Quantize KV cache to reduce VRAM. Reload to apply.
518+
Quantize KV cache to reduce VRAM.
489519
</div>
490520
</div>
491521
<Select
492522
value={kvCacheDtype ?? "f16"}
493523
onValueChange={(v) => {
494524
setKvCacheDtype(v === "f16" ? null : v);
495-
onReloadModel?.();
496525
}}
497526
>
498527
<SelectTrigger className="h-7 w-[90px] text-xs">
@@ -507,14 +536,35 @@ export function ChatSettingsPanel({
507536
</SelectContent>
508537
</Select>
509538
</div>
539+
{modelSettingsDirty && (
540+
<div className="flex flex-wrap gap-1.5 pt-1">
541+
<button
542+
type="button"
543+
onClick={() => onReloadModel?.()}
544+
className="rounded-md bg-primary px-2.5 py-1 text-[11px] font-medium text-primary-foreground transition-colors hover:bg-primary/90"
545+
>
546+
Apply
547+
</button>
548+
<button
549+
type="button"
550+
onClick={() => {
551+
setCustomContextLength(null);
552+
setKvCacheDtype(loadedKvCacheDtype);
553+
}}
554+
className="rounded-md border px-2.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent"
555+
>
556+
Reset
557+
</button>
558+
</div>
559+
)}
510560
</>
511561
)}
512-
{!isGguf && (
562+
{!isGguf && params.checkpoint && (
513563
<div className="flex items-center justify-between gap-3">
514564
<div className="min-w-0">
515-
<div className="text-xs font-medium">Trust remote code</div>
565+
<div className="text-xs font-medium">Enable custom code</div>
516566
<div className="text-[11px] text-muted-foreground">
517-
Allow models with custom code (e.g. Nemotron). Only enable for repos you trust.
567+
Allow models with custom code (e.g. Nemotron). Only enable if sure.
518568
</div>
519569
</div>
520570
<Switch
@@ -632,6 +682,7 @@ export function ChatSettingsPanel({
632682
onCheckedChange={onAutoTitleChange}
633683
/>
634684
</div>
685+
<HfTokenField />
635686
</div>
636687
</CollapsibleSection>
637688

@@ -775,6 +826,29 @@ function AutoHealToolCallsToggle() {
775826
);
776827
}
777828

829+
function HfTokenField() {
830+
const hfToken = useChatRuntimeStore((s) => s.hfToken);
831+
const setHfToken = useChatRuntimeStore((s) => s.setHfToken);
832+
833+
return (
834+
<div className="flex flex-col gap-1.5">
835+
<div className="min-w-0">
836+
<div className="text-xs font-medium">Hugging Face Token</div>
837+
<div className="text-[11px] text-muted-foreground">
838+
For downloading gated or private models.
839+
</div>
840+
</div>
841+
<Input
842+
type="password"
843+
value={hfToken}
844+
placeholder="hf_..."
845+
className="h-7 text-xs font-mono"
846+
onChange={(e) => setHfToken(e.target.value)}
847+
/>
848+
</div>
849+
);
850+
}
851+
778852
function ChatTemplateSection({
779853
onReloadModel,
780854
}: {

0 commit comments

Comments
 (0)