Repository navigation
studio: per-model inference defaults, GGUF slider fix, reasoning toggle - #4325
Conversation
When HuggingFace API doesn't return totalParams for a model, extract the param count from the model name (e.g. "Qwen3-0.6B" -> "0.6B", "Llama-3.2-1B-Instruct" -> "1B"). Applied to both the recommended list and HF search results.
- Fast GGUF metadata reader (~30-55ms) parses only KV header, skips tensor data and large arrays (tokenizer vocab etc) - Extracts context_length and chat_template from GGUF metadata - Returns context_length in LoadResponse for frontend to use - Frontend sets maxTokens to actual context_length for GGUFs (e.g. 262144 for Qwen3.5-9B, 131072 for Qwen2.5-7B) - Max Tokens slider shows "Max" and is locked for GGUFs - Auto-load path also uses actual context_length from load response - Toast auto-dismiss (5s) and close button for auto-load toast
Add GGUF TTS audio generation via llama-server. When a GGUF model loads, the backend probes its vocabulary to detect audio codecs (SNAC/BiCodec/DAC/CSM/Whisper). If detected, the codec is pre-loaded and the model is reported as audio to the frontend. During chat, TTS models route to the audio generation path which sends a per-codec prompt to llama-server's /completion endpoint, extracts generated tokens/text, and decodes to WAV using AudioCodecManager. Also strips base64 audio data from prior assistant messages to prevent context overflow. Co-authored-by: Manan Shah <[email protected]>
…toggle - Add inference_defaults.json with per-model-family sampling parameters for ~50 families (Qwen3.5, Qwen3, Gemma-3, Llama-3, DeepSeek, etc.). Values sourced from unslothai/docs and Ollama params blobs. - Family-based lookup in inference_config.py: extracts model family from identifier, matches against patterns (longest match first), merges with priority: model-specific YAML > family JSON > default.yaml. - Fix GGUF Max Tokens slider locked at "Max": store ggufContextLength separately from maxTokens so the slider is adjustable (step=64). - Fix Ministral YAML: top_p was literal string "default", now 0.95. - Add reasoning toggle for thinking models (Qwen3.5, Qwen3, DeepSeek-R1, DeepSeek-V3.1, etc.): detect enable_thinking support from GGUF chat template metadata, pass --jinja to llama-server, send chat_template_kwargs per-request. Frontend shows "Reasoning is ON/OFF" pill button next to attachment button in composer.
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request significantly enhances the Studio's model inference capabilities and user experience. It introduces a robust system for applying model-specific inference parameters, ensuring that GGUF models are loaded with optimized settings rather than generic defaults. Furthermore, it addresses a critical UI bug with the GGUF Max Tokens slider and integrates a new 'reasoning mode' toggle for models that support advanced thinking capabilities, providing users with more control over model behavior. These changes collectively improve the accuracy and flexibility of model interactions within the Studio. Highlights
Changelog
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
Backend was injecting "You are a helpful AI assistant." when no system prompt was provided. Neither unslothai/docs nor Ollama specify a default system prompt for most models. Now defaults to empty string, letting the model's own chat template handle system behavior.
There was a problem hiding this comment.
Code Review
This pull request introduces several significant enhancements, including per-model-family inference defaults via a new inference_defaults.json, a fix for the GGUF Max Tokens slider, and a new reasoning/thinking mode toggle for supported models. The backend changes are extensive, notably in llama_cpp.py which now parses GGUF metadata to extract context length and detect features. The frontend is updated accordingly to use this new information, fixing the slider and adding the reasoning toggle UI. The changes are well-structured and address the stated goals. I have one minor suggestion to improve code style.
| self._port = None | ||
| self._healthy = False | ||
| self._context_length = None | ||
| self._chat_template = None |
There was a problem hiding this comment.
According to PEP 8, imports should generally be at the top of the file. The torch module is imported multiple times within different methods in this file (here in unload_model, and also in init_audio_codec and generate_audio_response). To improve code style and clarity, please move import torch to the top of the file (e.g., after import struct) and remove these inline imports.
References
- PEP 8: E402 module level import not at top of file. Imports should be at the top of the file, just after any module comments and docstrings, and before module globals and constants. (link)
Lightbulb on when thinking enabled, lightbulb-off when disabled. Label is just "Think" in both states; grayed out styling when off.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 74c7684292
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| normalized_id = (self._model_identifier or "").lower() | ||
| if "deepseek" in normalized_id: | ||
| self._supports_reasoning = True |
There was a problem hiding this comment.
Use requested model id when detecting DeepSeek reasoning support
_read_gguf_metadata() uses self._model_identifier to detect DeepSeek templates that expose thinking instead of enable_thinking, but load_model() calls metadata parsing before assigning the new model identifier. In the common unload→load path this field is None, so DeepSeek GGUFs never get supports_reasoning=true, which hides the reasoning toggle and prevents enable_thinking kwargs from being sent.
Useful? React with 👍 / 👎.
| const store = useChatRuntimeStore.getState(); | ||
| store.setCheckpoint(repo.repo_id, variant.quant); | ||
| store.setParams({ ...store.params, maxTokens: loadResp.context_length ?? 131072 }); |
There was a problem hiding this comment.
Populate GGUF feature flags in auto-load path
When autoLoadSmallestModel() loads a GGUF, it updates only checkpoint and maxTokens, but never writes the new GGUF metadata fields (ggufContextLength, supportsReasoning, reasoningEnabled). In the “no model selected” first-message flow, this leaves reasoning support disabled in the UI and causes GGUF token controls to fall back as if context metadata were missing.
Useful? React with 👍 / 👎.
Replace SimpleTextAttachmentAdapter with custom TextAttachmentAdapter (excludes text/html) and HtmlAttachmentAdapter that strips tags via DOMParser, removing scripts/styles and extracting readable text content instead of dumping raw HTML markup into the conversation.
Display the model's Jinja2 chat template in a new "Chat Template" section under Settings (now open by default). For GGUFs, reads from GGUF metadata; for safetensors, reads from tokenizer.chat_template. Template is editable with a "Restore default chat template" button that appears when modified. Section only shows when a model with a chat template is loaded.
Chat template section now functional: - Editing the template shows "Apply & Reload" (reloads model with custom template) and "Revert changes" buttons - For GGUFs: writes template to temp .jinja file, passes --chat-template-file to llama-server on reload - For non-GGUF: passes chat_template_override in load request - Settings section now open by default - selectModel supports forceReload to reload same model
|
/gemini review |
- Set _model_identifier before _read_gguf_metadata so DeepSeek "thinking" template detection works (was always None before) - Populate ggufContextLength, supportsReasoning, reasoningEnabled, defaultChatTemplate in autoLoadSmallestModel GGUF path
Add gap-1.5 on the logo Link container to space the BETA label from the wordmark. Co-authored-by: Imagineer99 <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces several significant features and fixes, including per-model inference defaults, a reasoning toggle for supported models, and a fix for the GGUF max tokens slider. The changes are extensive, touching both backend and frontend, and are generally well-implemented. I've provided a couple of suggestions to improve maintainability by reducing code duplication.
| # Pick backend — both return (wav_bytes, sample_rate) | ||
| llama_backend = get_llama_cpp_backend() | ||
| if llama_backend.is_loaded and getattr(llama_backend, "_is_audio", False): | ||
| model_name = llama_backend.model_identifier | ||
| gen = lambda: llama_backend.generate_audio_response( | ||
| text = text, | ||
| audio_type = llama_backend._audio_type, | ||
| temperature = payload.temperature, | ||
| top_p = payload.top_p, | ||
| top_k = payload.top_k, | ||
| min_p = payload.min_p, | ||
| max_new_tokens = payload.max_tokens or 2048, | ||
| repetition_penalty = payload.repetition_penalty, | ||
| ) | ||
|
|
||
| audio_b64 = base64.b64encode(wav_bytes).decode("ascii") | ||
| completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}" | ||
|
|
||
| return JSONResponse( | ||
| content = { | ||
| "id": completion_id, | ||
| "object": "chat.completion.audio", | ||
| "model": backend.active_model_name, | ||
| "audio": { | ||
| "data": audio_b64, | ||
| "format": "wav", | ||
| "sample_rate": sample_rate, | ||
| }, | ||
| "choices": [ | ||
| { | ||
| "index": 0, | ||
| "message": { | ||
| "role": "assistant", | ||
| "content": f'[Generated audio from: "{text[:100]}"]', | ||
| }, | ||
| "finish_reason": "stop", | ||
| } | ||
| ], | ||
| } | ||
| else: | ||
| backend = get_inference_backend() | ||
| if not backend.active_model_name: | ||
| raise HTTPException(status_code = 400, detail = "No model loaded.") | ||
| model_info = backend.models.get(backend.active_model_name, {}) | ||
| if not model_info.get("is_audio"): | ||
| raise HTTPException( | ||
| status_code = 400, detail = "Active model is not an audio model." | ||
| ) | ||
| model_name = backend.active_model_name | ||
| gen = lambda: backend.generate_audio_response( | ||
| text = text, | ||
| temperature = payload.temperature, | ||
| top_p = payload.top_p, | ||
| top_k = payload.top_k, | ||
| min_p = payload.min_p, | ||
| max_new_tokens = payload.max_tokens or 2048, | ||
| repetition_penalty = payload.repetition_penalty, | ||
| use_adapter = payload.use_adapter, | ||
| ) |
There was a problem hiding this comment.
The logic for selecting the backend and preparing the generation function gen is duplicated. The arguments passed to generate_audio_response are almost identical for both backends. This can be refactored to reduce code duplication and improve maintainability by creating a shared dictionary of arguments.
# Pick backend — both return (wav_bytes, sample_rate)
gen_kwargs = {
"text": text,
"temperature": payload.temperature,
"top_p": payload.top_p,
"top_k": payload.top_k,
"min_p": payload.min_p,
"max_new_tokens": payload.max_tokens or 2048,
"repetition_penalty": payload.repetition_penalty,
}
llama_backend = get_llama_cpp_backend()
if llama_backend.is_loaded and getattr(llama_backend, "_is_audio", False):
model_name = llama_backend.model_identifier
gen_kwargs["audio_type"] = llama_backend._audio_type
gen = lambda: llama_backend.generate_audio_response(**gen_kwargs)
else:
backend = get_inference_backend()
if not backend.active_model_name:
raise HTTPException(status_code=400, detail="No model loaded.")
model_info = backend.models.get(backend.active_model_name, {})
if not model_info.get("is_audio"):
raise HTTPException(
status_code=400, detail="Active model is not an audio model."
)
model_name = backend.active_model_name
gen_kwargs["use_adapter"] = payload.use_adapter
gen = lambda: backend.generate_audio_response(**gen_kwargs)| {supportsReasoning && ( | ||
| <button | ||
| type="button" | ||
| onClick={() => setReasoningEnabled(!reasoningEnabled)} | ||
| className={cn( | ||
| "flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium transition-colors", | ||
| reasoningEnabled | ||
| ? "bg-primary/10 text-primary hover:bg-primary/20" | ||
| : "bg-muted text-muted-foreground hover:bg-muted-foreground/15", | ||
| )} | ||
| aria-label={reasoningEnabled ? "Disable thinking" : "Enable thinking"} | ||
| > | ||
| {reasoningEnabled ? ( | ||
| <LightbulbIcon className="size-3.5" /> | ||
| ) : ( | ||
| <LightbulbOffIcon className="size-3.5" /> | ||
| )} | ||
| <span>Think</span> | ||
| </button> | ||
| )} |
There was a problem hiding this comment.
This ReasoningToggle button implementation is duplicated from studio/frontend/src/components/assistant-ui/thread.tsx. To improve maintainability and reduce code duplication, you should extract the ReasoningToggle component from thread.tsx into a shared components directory (e.g., src/components/assistant-ui/) and reuse it here.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 54cf25bbc5
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } | ||
| # Pass enable_thinking per-request for reasoning models | ||
| if self._supports_reasoning and enable_thinking is not None: | ||
| payload["chat_template_kwargs"] = {"enable_thinking": enable_thinking} |
There was a problem hiding this comment.
Use
thinking key for DeepSeek reasoning toggle
_read_gguf_metadata() explicitly marks DeepSeek templates as reasoning-capable when they expose thinking (not enable_thinking), but generate_chat_completion() always sends chat_template_kwargs with only enable_thinking. For DeepSeek GGUFs, the Think toggle will not actually switch reasoning mode because the template variable name does not match what is sent.
Useful? React with 👍 / 👎.
| self._model_identifier = model_identifier | ||
|
|
||
| # Read GGUF metadata (context_length, chat_template) -- fast, header only | ||
| self._read_gguf_metadata(model_path) |
There was a problem hiding this comment.
Reset GGUF metadata state before parsing a new model
load_model() reuses the backend instance and calls _read_gguf_metadata() without clearing _supports_reasoning, _chat_template, or _context_length first. When /inference/load is used to switch GGUF models directly (without a prior /unload), stale metadata from the previous model can leak into the new one, causing incorrect capability reporting and request kwargs.
Useful? React with 👍 / 👎.
| is_lora: isLora, | ||
| gguf_variant: ggufVariant ?? null, | ||
| trust_remote_code: paramsBeforeLoad.trustRemoteCode ?? false, | ||
| chat_template_override: chatTemplateOverride, |
There was a problem hiding this comment.
Apply chat template override only on explicit reload
selectModel() always forwards chat_template_override from global store on every model load, even normal model switches. If a user edits template text for model A but then selects model B without pressing “Apply & Reload”, model B is loaded with A’s template override, which can break formatting or fail generation for the wrong model family.
Useful? React with 👍 / 👎.
…le (unslothai#4325) * studio: extract param count from model name as fallback When HuggingFace API doesn't return totalParams for a model, extract the param count from the model name (e.g. "Qwen3-0.6B" -> "0.6B", "Llama-3.2-1B-Instruct" -> "1B"). Applied to both the recommended list and HF search results. * studio: read GGUF context_length via fast header parser, set max tokens - Fast GGUF metadata reader (~30-55ms) parses only KV header, skips tensor data and large arrays (tokenizer vocab etc) - Extracts context_length and chat_template from GGUF metadata - Returns context_length in LoadResponse for frontend to use - Frontend sets maxTokens to actual context_length for GGUFs (e.g. 262144 for Qwen3.5-9B, 131072 for Qwen2.5-7B) - Max Tokens slider shows "Max" and is locked for GGUFs - Auto-load path also uses actual context_length from load response - Toast auto-dismiss (5s) and close button for auto-load toast * studio: GGUF TTS audio support (from PR unslothai#4318) Add GGUF TTS audio generation via llama-server. When a GGUF model loads, the backend probes its vocabulary to detect audio codecs (SNAC/BiCodec/DAC/CSM/Whisper). If detected, the codec is pre-loaded and the model is reported as audio to the frontend. During chat, TTS models route to the audio generation path which sends a per-codec prompt to llama-server's /completion endpoint, extracts generated tokens/text, and decodes to WAV using AudioCodecManager. Also strips base64 audio data from prior assistant messages to prevent context overflow. Co-authored-by: Manan Shah <[email protected]> * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Remove package-lock.json from tracking * studio: per-model inference defaults, GGUF max tokens fix, reasoning toggle - Add inference_defaults.json with per-model-family sampling parameters for ~50 families (Qwen3.5, Qwen3, Gemma-3, Llama-3, DeepSeek, etc.). Values sourced from unslothai/docs and Ollama params blobs. - Family-based lookup in inference_config.py: extracts model family from identifier, matches against patterns (longest match first), merges with priority: model-specific YAML > family JSON > default.yaml. - Fix GGUF Max Tokens slider locked at "Max": store ggufContextLength separately from maxTokens so the slider is adjustable (step=64). - Fix Ministral YAML: top_p was literal string "default", now 0.95. - Add reasoning toggle for thinking models (Qwen3.5, Qwen3, DeepSeek-R1, DeepSeek-V3.1, etc.): detect enable_thinking support from GGUF chat template metadata, pass --jinja to llama-server, send chat_template_kwargs per-request. Frontend shows "Reasoning is ON/OFF" pill button next to attachment button in composer. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: remove default system prompt injection Backend was injecting "You are a helpful AI assistant." when no system prompt was provided. Neither unslothai/docs nor Ollama specify a default system prompt for most models. Now defaults to empty string, letting the model's own chat template handle system behavior. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: use lightbulb icons and "Think" label for reasoning toggle Lightbulb on when thinking enabled, lightbulb-off when disabled. Label is just "Think" in both states; grayed out styling when off. * studio: fix HTML file upload breaking chat Replace SimpleTextAttachmentAdapter with custom TextAttachmentAdapter (excludes text/html) and HtmlAttachmentAdapter that strips tags via DOMParser, removing scripts/styles and extracting readable text content instead of dumping raw HTML markup into the conversation. * studio: show chat template in Configuration panel Display the model's Jinja2 chat template in a new "Chat Template" section under Settings (now open by default). For GGUFs, reads from GGUF metadata; for safetensors, reads from tokenizer.chat_template. Template is editable with a "Restore default chat template" button that appears when modified. Section only shows when a model with a chat template is loaded. * studio: editable chat template with Apply & Reload Chat template section now functional: - Editing the template shows "Apply & Reload" (reloads model with custom template) and "Revert changes" buttons - For GGUFs: writes template to temp .jinja file, passes --chat-template-file to llama-server on reload - For non-GGUF: passes chat_template_override in load request - Settings section now open by default - selectModel supports forceReload to reload same model * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: fix DeepSeek reasoning detection and auto-load metadata - Set _model_identifier before _read_gguf_metadata so DeepSeek "thinking" template detection works (was always None before) - Populate ggufContextLength, supportsReasoning, reasoningEnabled, defaultChatTemplate in autoLoadSmallestModel GGUF path * studio: add spacing before BETA badge in navbar Add gap-1.5 on the logo Link container to space the BETA label from the wordmark. Co-authored-by: Imagineer99 <[email protected]> * studio: vertically center BETA badge with logo --------- Co-authored-by: Manan Shah <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Imagineer99 <[email protected]>
Summary
Add per-model-family inference parameter defaults (
inference_defaults.json) covering ~50 model families. Values sourced from unslothai/docs tutorials and Ollama params blobs. When a GGUF model loads, it now gets the right temperature/top_p/top_k/min_p for its family (e.g., Qwen3.5 gets temp=1.0/top_p=0.95/top_k=20, Gemma-3 gets temp=1.0/top_k=64, etc.) instead of falling through to generic defaults.Fix GGUF Max Tokens slider that was locked at "Max" and unmovable. The slider step was set to the max value itself. Now stores
ggufContextLengthseparately so the slider works with step=64 and shows "Max" only when at the top.Fix
unsloth_Ministral-3-3B-Instruct-2512.yamlwheretop_p: defaultwas a literal string instead of a number.Add reasoning toggle for thinking models. Detects
enable_thinkingsupport from GGUF chat template metadata, always passes--jinjato llama-server, and sendschat_template_kwargsper-request for on-the-fly toggling. Frontend shows a "Reasoning is ON" / "Reasoning is OFF" pill button next to the attachment button in the composer. Only visible for models that support thinking mode (Qwen3.5, Qwen3, DeepSeek-R1, DeepSeek-V3.1, etc.).Test plan
<think>blocks in response