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: keep llama.cpp and vLLM connections' default system prompt (#14043)
Nilay638f1345dedc
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex b70741288d8..fc87e702568 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -55,6 +55,7 @@ _SERVED_WINDOW_PROVIDERS = frozenset({"vllm", "llama_cpp", "custom"})_SERVED_WINDOW_TTL_S = 60.0_SERVED_WINDOW_TIMEOUT_S = 5.0_served_windows: dict[tuple[str, str, str], tuple[float, Optional[int]]] = {}+_served_templates: dict[tuple[str, str, str], tuple[float, Optional[str]]] = {}_served_versions: dict[tuple[str, str], tuple[float, bool]] = {}@@ -852,6 +853,25 @@ _LOCAL_SERVER_EFFORT_ALIASES = {"minimal": "low", "xhigh": "high", "max": "high"_VLLM_FULL_EFFORT_RELEASE = "0.21.0"+def llama_cpp_template_controls(+ enable_thinking: Optional[bool],+ reasoning_effort: Optional[str],+ preserve_thinking: Optional[bool],+) -> tuple:+ """The template variables stream_chat_completion sends llama-server for these controls."""+ controls: dict[str, Any] = {}+ if preserve_thinking is not None:+ controls["preserve_thinking"] = preserve_thinking+ effort = (reasoning_effort or "").strip().lower()+ effort = _LOCAL_SERVER_EFFORT_ALIASES.get(effort, effort)+ thinking = False if effort == "none" else enable_thinking+ if thinking is not None:+ controls["enable_thinking"] = bool(thinking)+ if effort in ("minimal", "low", "medium", "high", "xhigh", "max"):+ controls["reasoning_effort"] = effort+ return tuple(sorted(controls.items()))++def _vllm_takes_full_effort(version: Any) -> bool:"""A pre-release or unparsable version keeps the low | medium | high subset."""from packaging.version import InvalidVersion, Version@@ -7719,6 +7739,41 @@ class ExternalProviderClient:_served_windows[key] = (now + _SERVED_WINDOW_TTL_S, window)return window+ async def served_chat_template(self, model: str) -> Optional[str]:+ """llama-server's chat template from /props, cached for a minute like the served window."""+ if self.provider_type != "llama_cpp":+ return None+ now = time.monotonic()+ key = (self.base_url, hashlib.sha256((self.api_key or "").encode()).hexdigest(), model)+ cached = _served_templates.get(key)+ if cached is not None and cached[0] > now:+ return cached[1]+ template = None+ try:+ response = await _client().get(+ f"{self.base_url.removesuffix('/v1')}/props",+ params = {"model": model},+ headers = self._auth_headers(),+ timeout = _SERVED_WINDOW_TIMEOUT_S,+ )+ response.raise_for_status()+ body = response.json()+ value = body.get("chat_template") if isinstance(body, dict) else None+ template = value if isinstance(value, str) and value.strip() else None+ except httpx.ConnectError as exc:+ logger.info(+ "No served chat template from %s: %s", self.provider_type, type(exc).__name__+ )+ return None+ except (httpx.HTTPError, ValueError) as exc:+ logger.info(+ "No served chat template from %s: %s", self.provider_type, type(exc).__name__+ )+ for stale in [k for k, (expiry, _) in _served_templates.items() if expiry <= now]:+ del _served_templates[stale]+ _served_templates[key] = (now + _SERVED_WINDOW_TTL_S, template)+ return template+@staticmethoddef _parse_gemini_models(payload: Any) -> list[dict[str, Any]]:"""map Gemini models to OpenAI entries and exclude advertised embedding-only models."""diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex afa37aa6737..8ed88aabfbd 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -4087,6 +4087,7 @@ from core.inference.providers import ()from core.inference.external_provider import (ExternalProviderClient,+ llama_cpp_template_controls,_is_kimi_k3,_is_openai_family_cloud,compacts_server_side,@@ -7063,8 +7064,8 @@ def _audio_input_system_prompt(system_prompt: str, request: Any) -> str:# Ollama applies the Modelfile SYSTEM only when `req.Messages[0].Role != "system"` (its# server/routes.go ChatHandler, which /v1/chat/completions also routes into), so only a turn at-# index 0 displaces it.-_MODELFILE_SYSTEM_PROVIDERS = frozenset({"ollama"})+# index 0 displaces it. llama-server, vLLM and Lemonade drop the template's default the same way.+_SERVER_SYSTEM_PROMPT_PROVIDERS = frozenset({"ollama", "llama_cpp", "vllm", "lemonade"})def _prepend_current_date_to_messages(@@ -7073,13 +7074,18 @@ def _prepend_current_date_to_messages(*,include_api_key: bool = False,provider_type: str | None = None,+ served_template: str | None = None,+ tools: bool = False,+ controls: tuple = (),) -> list[dict]:"""Apply the date to an already-built message list for a provider Studio proxies to.The local path prefixes ``system_prompt`` before the messages exist; an external payload isassembled first, so the date goes onto its leading system turn instead. When there is no- such turn one is synthesized, except for ``_MODELFILE_SYSTEM_PROVIDERS``, where it is- dropped: the caller's silence is what lets the server's own prompt apply.+ such turn one is synthesized, except for ``_SERVER_SYSTEM_PROMPT_PROVIDERS``, where it is+ dropped: the caller's silence is what lets the server's own prompt apply. When the server's+ template is known (``served_template``), the turn is synthesized as the local path does,+ carrying the template's default along."""if _date_gate_blocks(request, include_api_key):return messages@@ -7118,13 +7124,31 @@ def _prepend_current_date_to_messages(return copiedmsg["content"] = [{"type": "text", "text": date_line}, *copied_parts]return copied- if provider_type in _MODELFILE_SYSTEM_PROVIDERS:- # Synthesizing here is what costs an Ollama caller the Modelfile SYSTEM (#10436). Do not- # claim this exemption when something later will synthesize a system turn regardless.- return messages+ if provider_type in _SERVER_SYSTEM_PROMPT_PROVIDERS:+ if served_template is None:+ # Synthesizing here is what costs the caller the server's own system prompt (#10436). Do+ # not claim this exemption when something later will synthesize a system turn regardless.+ return messages+ from datetime import date++ today = date.fromisoformat(date_line[len(CURRENT_DATE_PROMPT_PREFIX) : -1])+ takes_turn, default = template_system_turn(served_template, today, tools, controls)+ if not takes_turn or default is None:+ return messages+ if default:+ date_line = f"{date_line}\n\n{default}"return [{"role": "system", "content": date_line}, *copied]+def _date_a_fitted_system_turn(+ messages: list[dict], request: Any, include_api_key: bool+) -> list[dict]:+ # a checkpoint block the fit prepended displaces the server's prompt anyway, so it takes the date.+ if not any(m.get("role") in ("system", "developer") for m in messages):+ return messages+ return _prepend_current_date_to_messages(messages, request, include_api_key = include_api_key)++# Strip leaked tool-call markup: every shared-parser format plus the leak shapes# llama_cpp.py's speculative buffer splits across the visible/DRAIN boundary:# 1. well-formed `<tool_call>...</tool_call>` / `<function=...>...</function>`@@ -29724,7 +29748,7 @@ async def _proxy_to_external_provider(_reject_confirm_gate_without_channel(payload, _ui_events, monitor_id, _catalog_names(external_studio_tools))- # Built before the date, because whether a nudge exists decides whether the Modelfile+ # Built before the date, because whether a nudge exists decides whether the server prompt# exemption is worth claiming: _append_to_system_message below displaces that prompt anyway.# Full access disables the sandbox, so the schemas say so; the general nudge stays off this path._external_nudge = ""@@ -29735,11 +29759,25 @@ async def _proxy_to_external_provider(full_access = bool(payload.bypass_permissions),full_access_only = True,)+ _served_template = None+ if (+ provider_type == "llama_cpp"+ and not _external_nudge+ and not _date_gate_blocks(request, run_studio_tool_loop)+ and current_date_prompt_line(request = request)+ and not any(m.get("role") in ("system", "developer") for m in chat_messages)+ ):+ _served_template = await client.served_chat_template(model)chat_messages = _prepend_current_date_to_messages(chat_messages,request,include_api_key = run_studio_tool_loop,provider_type = None if _external_nudge else provider_type,+ served_template = _served_template,+ tools = bool(external_studio_tools or payload.tools),+ controls = llama_cpp_template_controls(+ payload.enable_thinking, payload.reasoning_effort, payload.preserve_thinking+ ),)if _external_nudge:chat_messages = _append_to_system_message(chat_messages, _external_nudge)@@ -29777,6 +29815,7 @@ async def _proxy_to_external_provider(payload,tools = _external_fit_tools,)+ fitted = _date_a_fitted_system_turn(fitted, request, run_studio_tool_loop)if truncation and truncation.get("dropped_messages"):_external_truncation = truncationtruncation_line = None@@ -29805,6 +29844,7 @@ async def _proxy_to_external_provider(payload,tools = _external_fit_tools,)+ chat_messages = _date_a_fitted_system_turn(chat_messages, request, run_studio_tool_loop)cancel_event = threading.Event()cancel_keys = tuple(key for key in (payload.cancel_id, payload.session_id) if key)diff --git a/studio/backend/tests/test_current_date_prompt_settings.py b/studio/backend/tests/test_current_date_prompt_settings.pyindex d2672069796..0c88bbef285 100644--- a/studio/backend/tests/test_current_date_prompt_settings.py+++ b/studio/backend/tests/test_current_date_prompt_settings.py@@ -215,10 +215,76 @@ class TestExternalProviderMessages:assert out[0]["content"] == "The current date is 2026-08-15.\n\nBe terse."assert out[1] == {"role": "user", "content": "hi"}- def test_other_local_servers_still_get_a_synthesized_system_turn(self):+ @pytest.mark.parametrize("provider_type", ("llama_cpp", "vllm", "lemonade"))+ def test_template_servers_keep_their_default_system_prompt_when_studio_sends_none(+ self, provider_type+ ):+ import routes.inference as inference++ messages = [{"role": "user", "content": "hi"}]+ out = inference._prepend_current_date_to_messages(messages, provider_type = provider_type)+ assert out is messages++ @pytest.mark.parametrize("provider_type", ("llama_cpp", "vllm", "lemonade"))+ def test_template_servers_still_date_a_system_turn_studio_composed(self, provider_type):+ import routes.inference as inference+ out = inference._prepend_current_date_to_messages(+ [{"role": "system", "content": "Be terse."}, {"role": "user", "content": "hi"}],+ provider_type = provider_type,+ )+ assert out[0]["content"] == "The current date is 2026-08-15.\n\nBe terse."++ def test_llama_cpp_carries_the_served_template_default_along_with_the_date(self):+ import routes.inference as inference+ out = inference._prepend_current_date_to_messages(+ [{"role": "user", "content": "hi"}],+ provider_type = "llama_cpp",+ served_template = _QWEN25_LIKE,+ )+ assert out[0] == {+ "role": "system",+ "content": "The current date is 2026-08-15.\n\nYou are Qwen, a helpful assistant.",+ }++ def test_llama_cpp_probes_the_served_template_with_the_request_controls(self):+ import routes.inference as inference++ template = (+ "{% if messages[0]['role'] == 'system' %}{% set sys = messages[0]['content'] %}"+ "{% set rest = messages[1:] %}{% else %}{% set rest = messages %}"+ "{% if enable_thinking is defined and enable_thinking is false %}"+ "{% set sys = 'Answer directly.' %}{% else %}{% set sys = 'Think first.' %}{% endif %}"+ "{% endif %}<|im_start|>system\n{{ sys }}<|im_end|>\n"+ "{% for m in rest %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ )+ out = inference._prepend_current_date_to_messages(+ [{"role": "user", "content": "hi"}],+ provider_type = "llama_cpp",+ served_template = template,+ controls = (("enable_thinking", False),),+ )+ assert out[0]["content"] == "The current date is 2026-08-15.\n\nAnswer directly."++ def test_llama_cpp_dates_a_served_template_with_no_default(self):+ import routes.inference as inference+ out = inference._prepend_current_date_to_messages(+ [{"role": "user", "content": "hi"}], provider_type = "llama_cpp", served_template = _CHATML+ )+ assert out[0] == {"role": "system", "content": "The current date is 2026-08-15."}++ def test_llama_cpp_sends_no_system_turn_a_served_template_refuses(self):+ import routes.inference as inference++ messages = [{"role": "user", "content": "hi"}]+ out = inference._prepend_current_date_to_messages(+ messages, provider_type = "llama_cpp", served_template = _REFUSES_SYSTEM+ )+ assert out is messages++ def test_custom_connections_still_get_a_synthesized_system_turn(self):import routes.inference as inferenceout = inference._prepend_current_date_to_messages(- [{"role": "user", "content": "hi"}], provider_type = "llama_cpp"+ [{"role": "user", "content": "hi"}], provider_type = "custom")assert out[0] == {"role": "system", "content": "The current date is 2026-08-15."}diff --git a/studio/backend/tests/test_external_auto_compaction.py b/studio/backend/tests/test_external_auto_compaction.pyindex 9cfe520d5e2..9d1264dc559 100644--- a/studio/backend/tests/test_external_auto_compaction.py+++ b/studio/backend/tests/test_external_auto_compaction.py@@ -9,6 +9,7 @@ import sysfrom http.server import BaseHTTPRequestHandlerfrom pathlib import Path+import pytestfrom starlette.requests import Requestimport routes.inference as ri@@ -429,6 +430,7 @@ class _ServedWindowHandler(_Handler):def _served(**attrs):ep_mod._served_windows.clear()+ ep_mod._served_templates.clear()return type("Served", (_ServedWindowHandler,), {"gets": [], **attrs})@@ -498,6 +500,31 @@ def test_an_older_llama_server_is_read_from_props_for_the_model():assert old.gets == ["/v1/models", "/props?model=a-model"]+def test_a_llama_server_template_default_is_sent_along_with_the_date(monkeypatch):+ monkeypatch.setattr(+ ri, "current_date_prompt_line", lambda **_kwargs: "The current date is 2026-08-15."+ )+ qwen = (+ "{% if messages[0]['role'] == 'system' %}{% set sys = messages[0]['content'] %}"+ "{% set rest = messages[1:] %}{% else %}"+ "{% set sys = 'You are Qwen, created by Alibaba Cloud.' %}{% set rest = messages %}{% endif %}"+ "<|im_start|>system\n{{ sys }}<|im_end|>\n"+ "{% for m in rest %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}"+ )+ server = _served(+ models = [{"id": "a-model", "owned_by": "llamacpp"}], props = {"chat_template": qwen}+ )+ _, sent = _proxy("llama_cpp", [{"role": "user", "content": "who are you?"}], handler = server)+ assert sent["messages"] == [+ {+ "role": "system",+ "content": "The current date is 2026-08-15.\n\nYou are Qwen, created by Alibaba Cloud.",+ },+ {"role": "user", "content": "who are you?"},+ ]+ assert server.gets == ["/props?model=a-model"]++def test_a_window_the_request_states_is_kept_over_the_served_one():server = _llama_server()_, sent = _proxy(@@ -621,3 +648,91 @@ def test_a_stalled_server_costs_one_deadline_and_is_remembered(monkeypatch):_run(go)assert windows == [None, None]assert reads == ["a-model"]+++def test_a_checkpoint_turn_the_fit_creates_still_carries_the_date(monkeypatch):+ monkeypatch.setattr(+ ri, "current_date_prompt_line", lambda **_kwargs: "The current date is 2026-08-15."+ )++ def fit(+ messages,+ payload,+ tools = None,+ ):+ return [{"role": "system", "content": "Earlier: a summary."}, *messages], None, None++ monkeypatch.setattr(ri, "_fit_external_context", fit)+ _, sent = _proxy(+ "vllm",+ [{"role": "user", "content": "hi"}],+ context_overflow = "truncate_oldest",+ compaction_threshold = 6_000,+ )+ assert sent["messages"][0] == {+ "role": "system",+ "content": "The current date is 2026-08-15.\n\nEarlier: a summary.",+ }+++def test_a_failed_template_read_logs_no_url_credentials(monkeypatch):+ import httpx++ lines = []+ monkeypatch.setattr(+ ep_mod, "logger", type("L", (), {"info": lambda self, *a: lines.append(a[0] % a[1:])})()+ )+ monkeypatch.setattr(+ ep_mod,+ "_client",+ lambda: httpx.AsyncClient(+ transport = httpx.MockTransport(lambda request: httpx.Response(404, request = request))+ ),+ )+ ep_mod._served_templates.clear()+ provider = ep_mod.ExternalProviderClient("llama_cpp", "http://user:secret@host/v1", "")+ got = []++ async def go():+ got.append(await provider.served_chat_template("a-model"))++ _run(go)+ assert got == [None]+ assert lines and not any("secret" in line for line in lines)+++ "enable_thinking,reasoning_effort,preserve_thinking",+ [+ (None, None, None),+ (True, None, None),+ (False, None, True),+ (None, "none", None),+ (True, "max", False),+ (None, "medium", None),+ ],+)+def test_the_probed_template_controls_are_the_ones_sent(+ enable_thinking, reasoning_effort, preserve_thinking+):+ with _Server() as server:+ provider = ep_mod.ExternalProviderClient("llama_cpp", server.base_url, "")++ async def go():+ async for _ in provider.stream_chat_completion(+ messages = [{"role": "user", "content": "hi"}],+ model = "a-model",+ enable_thinking = enable_thinking,+ reasoning_effort = reasoning_effort,+ preserve_thinking = preserve_thinking,+ ):+ pass++ _run(go)+ body = server.bodies[-1]+ sent = dict(body.get("chat_template_kwargs") or {})+ if "reasoning_effort" in body:+ sent["reasoning_effort"] = body["reasoning_effort"]+ assert ep_mod.llama_cpp_template_controls(+ enable_thinking, reasoning_effort, preserve_thinking+ ) == tuple(sorted(sent.items()))diff --git a/studio/backend/tests/test_external_hosted_tool_passthrough.py b/studio/backend/tests/test_external_hosted_tool_passthrough.pyindex 56921ad6dc5..38330e680dc 100644--- a/studio/backend/tests/test_external_hosted_tool_passthrough.py+++ b/studio/backend/tests/test_external_hosted_tool_passthrough.py@@ -46,6 +46,7 @@ class FakeExternalClient:"""Stands in for ExternalProviderClient, recording the passthrough call."""last: dict = {}+ served_template = Nonedef __init__(self, **kwargs):FakeExternalClient.last = {"ctor": kwargs, "passthrough": None}@@ -60,6 +61,9 @@ class FakeExternalClient:return gen()+ async def served_chat_template(self, model):+ return FakeExternalClient.served_template+async def close(self):return None@@ -220,11 +224,11 @@ def test_an_api_request_without_resolved_server_tools_stays_undated(monkeypatch)]-def test_an_ollama_connection_keeps_its_modelfile_prompt_when_studio_sends_no_system_turn(- monkeypatch,[email protected]("provider_type", ("ollama", "llama_cpp", "vllm"))+def test_a_local_server_keeps_its_own_system_prompt_when_studio_sends_no_system_turn(+ monkeypatch, provider_type):- # A synthesized date-only turn at index 0 is what displaces the Modelfile SYSTEM (#10436).- inf = _install(monkeypatch, "ollama")+ inf = _install(monkeypatch, provider_type)monkeypatch.setattr(inf,"current_date_prompt_line",@@ -238,6 +242,27 @@ def test_an_ollama_connection_keeps_its_modelfile_prompt_when_studio_sends_no_sy]+def test_a_llama_cpp_connection_dates_a_served_template_with_no_default(monkeypatch):+ inf = _install(monkeypatch, "llama_cpp")+ monkeypatch.setattr(+ FakeExternalClient,+ "served_template",+ "{% for m in messages %}<|im_start|>{{ m['role'] }}\n{{ m['content'] }}<|im_end|>\n{% endfor %}",+ )+ monkeypatch.setattr(+ inf,+ "current_date_prompt_line",+ lambda **_kwargs: "The current date is 2026-08-15.",+ )++ _run(inf, _payload())++ assert FakeExternalClient.last["passthrough"]["messages"] == [+ {"role": "system", "content": "The current date is 2026-08-15."},+ {"role": "user", "content": "what is 2+2?"},+ ]++def test_an_ollama_connection_still_dates_a_studio_composed_system_prompt(monkeypatch):"""Over-firing would drop the date for every Ollama user, not just empty-prompt ones."""inf = _install(monkeypatch, "ollama")@@ -263,10 +288,8 @@ def test_an_ollama_connection_still_dates_a_studio_composed_system_prompt(monkey][email protected]("provider_type", ("llama_cpp", "vllm", "custom"))-def test_the_other_self_hosted_providers_still_get_the_synthesized_turn(monkeypatch, provider_type):- """These have no Modelfile SYSTEM to lose, so the exemption must not widen to them."""- inf = _install(monkeypatch, provider_type)+def test_a_custom_connection_still_gets_the_synthesized_turn(monkeypatch):+ inf = _install(monkeypatch, "custom")monkeypatch.setattr(inf,"current_date_prompt_line",diff --git a/studio/backend/tests/test_external_hosted_tool_selection.py b/studio/backend/tests/test_external_hosted_tool_selection.pyindex c262d9b479f..126f308b25e 100644--- a/studio/backend/tests/test_external_hosted_tool_selection.py+++ b/studio/backend/tests/test_external_hosted_tool_selection.py@@ -42,6 +42,9 @@ class _FakeExternalClient:return gen()+ async def served_chat_template(self, model):+ return None+async def close(self):return None