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: count tokens for templates that refuse an empty chat (#12336)

Michael Han0dba81767825
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index e95fd762321..295a48fcb56 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -12011,6 +12011,9 @@ class LlamaCppBackend:
# Property of the host, not the model, so warn once rather than per launch.
_warned_no_nvlink = False
+ # The loaded template refuses an empty render. Reset on every load.
+ _empty_chat_render_refused = False
+
@staticmethod
def _sanitize_p2p_env(env: dict) -> Optional[str]:
"""Drop an inherited GGML_CUDA_P2P that must not reach the child; return the
@@ -18128,6 +18131,7 @@ class LlamaCppBackend:
# carry over when switching models.
self._context_length = None
self._chat_template = None
+ self._empty_chat_render_refused = False
self._markup_tokens = []
self._markup_profile = None
self._supports_reasoning = False
@@ -27937,6 +27941,7 @@ class LlamaCppBackend:
_pv_split_mode_pin = _paravirtual_split_mode_pin(extra_args)
self._chat_template_override = chat_template_override
+ self._empty_chat_render_refused = False
_effective_template = self._effective_chat_template(chat_template_override)
if _effective_template:
import tempfile
@@ -32368,6 +32373,7 @@ class LlamaCppBackend:
self._markup_tokens = []
self._markup_profile = None
self._chat_template_override = None
+ self._empty_chat_render_refused = False
self._supports_reasoning = False
self._reasoning_always_on = False
self._reasoning_budget = -1
@@ -39948,60 +39954,79 @@ class LlamaCppBackend:
template_messages = [
{"role": "system", "content": system_text}
] + template_messages
- # An empty list is passed through as-is: llama-server renders through minja, not
- # jinja2, so messages[0] yields undefined rather than raising and the template
- # returns its bare preamble. A placeholder turn would add a system block instead.
- apply_template_failed = False
- try:
- # llama-server's /apply-template renders tool declarations
- # into the prompt when ``tools`` is supplied, so pass them
- # through, otherwise tool-schema tokens go uncounted.
- template_body = {"messages": template_messages}
- if tools:
- template_body["tools"] = llama_grammar_tools(tools)
- # Layered over the load-time --chat-template-kwargs: only keys sent here move.
- if chat_template_kwargs:
- template_body["chat_template_kwargs"] = chat_template_kwargs
- if continue_final_message:
- template_body["continue_final_message"] = True
- template_body["add_generation_prompt"] = False
- if prefer_native:
- if should_abort is not None and should_abort():
- raise CountAborted()
- try:
- native = client.post(
- f"{self.base_url}/v1/chat/completions/input_tokens",
- json = template_body,
- )
- if native.status_code == 200:
- count = native.json().get("input_tokens")
- if type(count) is int and count > 0:
- return count
- except Exception:
- pass
- if should_abort is not None and should_abort():
- raise CountAborted()
- resp = client.post(
- f"{self.base_url}/apply-template",
- json = template_body,
- )
- if resp.status_code == 200:
+
+ def _render_count(render_messages) -> tuple[Optional[int], bool]:
+ """(count or None, refused). Only a 500 is a template refusal; 503 = loading or no slot."""
+ try:
+ # /apply-template renders tool schemas; omitting them undercounts.
+ template_body = {"messages": render_messages}
+ if tools:
+ template_body["tools"] = llama_grammar_tools(tools)
+ # Layered over the load-time --chat-template-kwargs: only keys sent here move.
+ if chat_template_kwargs:
+ template_body["chat_template_kwargs"] = chat_template_kwargs
+ if continue_final_message:
+ template_body["continue_final_message"] = True
+ template_body["add_generation_prompt"] = False
+ if prefer_native:
+ if should_abort is not None and should_abort():
+ raise CountAborted()
+ try:
+ native = client.post(
+ f"{self.base_url}/v1/chat/completions/input_tokens",
+ json = template_body,
+ )
+ if native.status_code == 200:
+ count = native.json().get("input_tokens")
+ if type(count) is int and count > 0:
+ return count, False
+ except Exception:
+ pass
+ if should_abort is not None and should_abort():
+ raise CountAborted()
+ resp = client.post(
+ f"{self.base_url}/apply-template",
+ json = template_body,
+ )
+ if resp.status_code != 200:
+ return None, resp.status_code == 500
prompt = resp.json().get("prompt", "")
if isinstance(prompt, str):
if should_abort is not None and should_abort():
raise CountAborted()
- return _tokenize(prompt)
- apply_template_failed = True
- except CountAborted:
- # Not a template failure: swallowed, the text fallback tokenizes anyway,
- # which is the work being declined. Must precede the generic except.
- raise
- except Exception:
- apply_template_failed = True
+ return _tokenize(prompt), False
+ except CountAborted:
+ # Not a template failure: swallowed, the text fallback tokenizes anyway,
+ # which is the work being declined. Must precede the generic except.
+ raise
+ except Exception:
+ pass
+ return None, False
+
+ # Qwen3.5+ templates raise on an empty render (#12327); a lone assistant turn is
+ # stripped as a prefill, so renders empty too. Retry behind an empty user turn.
+ renders_empty = not template_messages or (
+ len(template_messages) == 1
+ and isinstance(template_messages[0], dict)
+ and template_messages[0].get("role") == "assistant"
+ )
+ with_user_turn = [{"role": "user", "content": ""}] + template_messages
+ if renders_empty and self._empty_chat_render_refused:
+ count, _refused = _render_count(with_user_turn)
+ else:
+ count, _refused = _render_count(template_messages)
+ if count is None and _refused and renders_empty:
+ if should_abort is not None and should_abort():
+ raise CountAborted()
+ count, _ = _render_count(with_user_turn)
+ if count is not None:
+ self._empty_chat_render_refused = True
+ if count is not None:
+ return count
# The fallback drops role markers, special tokens and tool schemas (~30% of a
# six-turn two-tool prompt), so strict callers error rather than undercount.
- if strict and apply_template_failed:
+ if strict:
raise RuntimeError("llama-server could not render the chat template")
# 2. Fallback: concatenate plain text and tokenize. Append a
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 93bd8b35ffe..8dcec43edba 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -5920,7 +5920,8 @@ def test_an_empty_chat_sends_the_empty_list_unchanged(monkeypatch):
shipped templates for Llama-3.2-1B-Instruct, Qwen3-8B, Phi-4, gemma-3-270m-it and
mistral-7b-instruct-v0.3 driven through llama-server with --jinja: all five render.
Injecting a placeholder system turn would add a system block to the count for Qwen3
- (+30 chars) and Phi-4 (+38), overcounting the empty chat the bar exists to show."""
+ (+30 chars) and Phi-4 (+38), overcounting the empty chat the bar exists to show. Templates
+ that raise on no messages (Qwen3.5+) are re-priced only after refusing; see below."""
seen = {}
class _FakeResponse:
@@ -5963,6 +5964,132 @@ def test_an_empty_chat_sends_the_empty_list_unchanged(monkeypatch):
assert count > 0, "a fresh chat still prices the template preamble"
+class _RefusingEmptyRenderClient:
+ """llama-server with a Qwen3.5+ template that raises on no messages; strips a trailing assistant."""
+
+ sent = []
+ down = False
+ empty_status = 500
+
+ def __init__(self, **_kwargs):
+ pass
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ return False
+
+ def post(
+ self,
+ url,
+ json = None,
+ ):
+ body = json or {}
+ if url.endswith(("/apply-template", "/input_tokens")):
+ messages = body.get("messages")
+ type(self).sent.append((url.rsplit("/", 1)[-1], messages))
+ if type(self).down:
+ raise RuntimeError("timed out")
+ rendered = list(messages or [])
+ if rendered and rendered[-1].get("role") == "assistant":
+ rendered = rendered[:-1]
+ if not rendered:
+ status = type(self).empty_status
+ return _CountResponse(
+ {"error": {"code": status, "message": "No messages provided."}},
+ status_code = status,
+ )
+ if url.endswith("/input_tokens"):
+ return _CountResponse({"input_tokens": 7})
+ return _CountResponse(
+ {"prompt": "<|im_start|>user\n<|im_end|>\n<|im_start|>assistant\n"}
+ )
+ return _CountResponse({"tokens": str(body.get("content", "")).split()})
+
+
+class _CountResponse:
+ def __init__(
+ self,
+ payload,
+ status_code = 200,
+ ):
+ self._payload = payload
+ self.status_code = status_code
+
+ def json(self):
+ return self._payload
+
+
+def refusing_client(monkeypatch):
+ _RefusingEmptyRenderClient.sent = []
+ _RefusingEmptyRenderClient.down = False
+ _RefusingEmptyRenderClient.empty_status = 500
+ monkeypatch.setattr(llama_cpp_mod.httpx, "Client", _RefusingEmptyRenderClient)
+ return _RefusingEmptyRenderClient
+
+
[email protected]("prefer_native", [False, True])
+ "messages",
+ [[], [{"role": "assistant", "content": '{"name": "terminal"}'}]],
+ ids = ["new_chat", "lone_pending_call"],
+)
+def test_a_template_refusing_an_empty_render_is_priced_behind_one_empty_user_turn(
+ refusing_client, prefer_native, messages
+):
+ """#12327: an empty render the template refuses is priced behind one empty user turn, once per load."""
+ backend = _CountBackend()
+ count = backend.count_chat_tokens(
+ messages, None, None, strict = True, prefer_native = prefer_native
+ )
+ assert count > 0, "a refused empty render must still be priced, not refused"
+ assert refusing_client.sent[0][1] == messages, "what the caller sent is still tried first"
+ assert refusing_client.sent[-1][1] == [{"role": "user", "content": ""}] + messages
+
+ refusing_client.sent = []
+ assert (
+ backend.count_chat_tokens(messages, None, None, strict = True, prefer_native = prefer_native)
+ == count
+ )
+ assert all(
+ sent == [{"role": "user", "content": ""}] + messages for _, sent in refusing_client.sent
+ ), "a known refusal must not be re-sent on every recount"
+
+
+def test_a_conversation_the_template_renders_costs_one_request(refusing_client):
+ """The chat path counts real conversations on every turn; the fallback must add nothing there."""
+ backend = _CountBackend()
+ backend._empty_chat_render_refused = True
+ conversation = [
+ {"role": "system", "content": "rules"},
+ {"role": "user", "content": "Read ./README.md"},
+ ]
+ backend.count_chat_tokens(conversation, None, None, strict = True)
+ assert refusing_client.sent == [("apply-template", conversation)]
+
+
+def test_an_unreachable_server_is_not_retried_or_taken_for_a_refusal(refusing_client):
+ """A timeout says nothing about the template: no second round trip, and no remembered refusal."""
+ refusing_client.down = True
+ backend = _CountBackend()
+ with pytest.raises(RuntimeError):
+ backend.count_chat_tokens([], None, None, strict = True)
+ assert len(refusing_client.sent) == 1
+ assert backend._empty_chat_render_refused is False
+
+
+def test_a_busy_server_is_not_taken_for_a_refusal(refusing_client):
+ """llama-server answers 503 while loading or out of slots; only a 500 is a template refusal."""
+ refusing_client.empty_status = 503
+ backend = _CountBackend()
+ with pytest.raises(RuntimeError):
+ backend.count_chat_tokens([], None, None, strict = True)
+ assert [m for _, m in refusing_client.sent] == [[]], "a busy server is not retried"
+ assert backend._empty_chat_render_refused is False
+
+
def test_a_count_never_spawns_mcp_servers():
"""get_enabled_mcp_tools starts stdio MCP server processes, writes cache and cooloff state,
and blocks for a whole probe timeout against a server that is down. A background recount