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: ask llama-server again with its tool parser off when it rejects a reply before streaming (#16002)

Daniel Han848676c9844a
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 5966276e340..075a7a43cdd 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -91,7 +91,7 @@ from core.inference.lookup_tables import (
is_per_layer_embedding as _is_per_layer_embedding,
lazy_read_bytes as _lookup_lazy_read_bytes,
)
-from core.inference.stream_errors import stream_error_from_chunk
+from core.inference.stream_errors import is_tool_parse_rejection, stream_error_from_chunk
from hub.utils.hf_errors import modelscope_missing
from hub.utils.hf_tokens import (
call_hub_with_anonymous_retry,
@@ -7542,6 +7542,19 @@ def _llama_chunk_has_generated_output(data: dict) -> bool:
return False
+def _structured_calls_complete(calls: dict) -> bool:
+ for call in calls.values():
+ function = call.get("function") or {}
+ if not function.get("name", "").strip():
+ return False
+ try:
+ if not isinstance(json.loads(function.get("arguments") or ""), dict):
+ return False
+ except ValueError:
+ return False
+ return bool(calls)
+
+
def _perf_callback_wants_timings(callback) -> bool:
"""A callback that only tracks prefill progress opts out of per-token timings."""
return callback is not None and getattr(callback, "wants_timings", True)
@@ -35834,6 +35847,57 @@ class LlamaCppBackend:
return False
return _llama_chunk_has_generated_output(data)
+ def _iter_tool_round_text(
+ self,
+ response: "httpx.Response",
+ payload: dict,
+ cancel_event: Optional[threading.Event],
+ first_token_deadline: Optional[float],
+ on_respawn: Optional[Callable[[], None]] = None,
+ ) -> Generator[str, None, None]:
+ """Raw SSE text of one tool round. A tool-call parse rejection before any output (Llama 3.x
+ ``{"type": "function", ...}``, ``;``-joined calls) is retried once with tool_choice "none",
+ which turns llama-server's parser off so Studio's parser reads the raw reply."""
+ stream = self._iter_text_cancellable(
+ response, cancel_event, first_token_deadline = first_token_deadline
+ )
+ if not payload.get("tools") or payload.get("tool_choice") == "none":
+ yield from stream
+ return
+ pending = ""
+ for chunk in stream:
+ pending += chunk
+ while "\n" in pending:
+ line, pending = pending.split("\n", 1)
+ data = None
+ stripped = line.strip()
+ if stripped.startswith("data: ") and stripped != "data: [DONE]":
+ try:
+ data = json.loads(stripped[6:])
+ except json.JSONDecodeError:
+ pass
+ if is_tool_parse_rejection(data):
+ logger.info(
+ "llama-server could not parse the reply as tool calls; "
+ "asking again with its tool-call parser off"
+ )
+ response.close()
+ payload["tool_choice"] = "none"
+ with self._open_chat_stream_with_respawn_retry(
+ payload, cancel_event, on_respawn = on_respawn
+ ) as (retry_response, retry_deadline):
+ yield from self._iter_text_cancellable(
+ retry_response, cancel_event, first_token_deadline = retry_deadline
+ )
+ return
+ yield line + "\n"
+ # Output already reached the caller: a second request could not be joined to it.
+ if isinstance(data, dict) and _llama_chunk_has_generated_output(data):
+ yield pending
+ yield from stream
+ return
+ yield pending
+
@staticmethod
def _iter_text_cancellable(
response: "httpx.Response",
@@ -37869,10 +37933,12 @@ class LlamaCppBackend:
for truncation in _respawn_truncations:
yield {"type": "context_truncated", **truncation}
raw_buf = ""
- for raw_chunk in self._iter_text_cancellable(
+ for raw_chunk in self._iter_tool_round_text(
response,
+ payload,
cancel_event,
- first_token_deadline = first_token_deadline,
+ first_token_deadline,
+ on_respawn = _refit_iteration_after_respawn,
):
raw_buf += raw_chunk
while "\n" in raw_buf:
@@ -37932,6 +37998,19 @@ class LlamaCppBackend:
# Error chunks have no choices; don't drop them.
_stream_error = stream_error_from_chunk(chunk_data)
if _stream_error is not None:
+ # A rejected later call (`;`-joined) must not lose the complete ones before it.
+ if (
+ has_structured_tc
+ and is_tool_parse_rejection(chunk_data)
+ and _structured_calls_complete(tool_calls_acc)
+ ):
+ logger.info(
+ "llama-server rejected a later tool call; "
+ "running the %d complete one(s) before it",
+ len(tool_calls_acc),
+ )
+ _stream_done = True
+ break
raise _stream_error
choices = chunk_data.get("choices", [])
if not choices:
diff --git a/studio/backend/core/inference/stream_errors.py b/studio/backend/core/inference/stream_errors.py
index d631d21a39e..497a460bd22 100644
--- a/studio/backend/core/inference/stream_errors.py
+++ b/studio/backend/core/inference/stream_errors.py
@@ -27,6 +27,13 @@ KV_STARVATION_MESSAGE = (
"Context Length in Model settings."
)
+# llama-server's tool-call parser rejecting a reply (b11000+ PEG, older parser, non-JSON args); the text is dropped.
+_TOOL_PARSE_REJECTIONS = (
+ "the model produced output that does not match the expected",
+ "failed to parse input at pos",
+ "failed to parse tool call arguments as json",
+)
+
_OVERSIZE_HINT = "Raise the Context Length in Model settings, or shorten the request."
_GENERIC_MESSAGE = "The model stopped generating early."
@@ -110,6 +117,11 @@ def is_context_oversize(message: Optional[str]) -> bool:
return any(marker in lowered for marker in _OVERSIZE_MARKERS)
+def is_tool_parse_rejection(chunk: Any) -> bool:
+ message = error_message_from_chunk(chunk)
+ return bool(message) and message.lower().startswith(_TOOL_PARSE_REJECTIONS)
+
+
def describe_stream_error(message: Optional[str], *, prefix: str = "") -> str:
"""Starvation gets its own text; oversize keeps server token counts; other errors pass through unchanged, since a fixed string made them undiagnosable."""
if is_kv_starvation(message):
diff --git a/studio/backend/tests/test_llama_cpp_tool_loop.py b/studio/backend/tests/test_llama_cpp_tool_loop.py
index 8c989b803be..b58009d6e9b 100644
--- a/studio/backend/tests/test_llama_cpp_tool_loop.py
+++ b/studio/backend/tests/test_llama_cpp_tool_loop.py
@@ -189,7 +189,9 @@ def _make_backend(
stream = streams.pop(0)
if isinstance(stream, BaseException):
raise stream
- yield type("FakeResponse", (), {"status_code": 200, "chunks": stream})()
+ yield type(
+ "FakeResponse", (), {"status_code": 200, "chunks": stream, "close": lambda self: None}
+ )()
def fake_iter_text_cancellable(
response,
diff --git a/studio/backend/tests/test_llama_tool_parse_rejection_retry.py b/studio/backend/tests/test_llama_tool_parse_rejection_retry.py
new file mode 100644
index 00000000000..102613d0bf3
--- /dev/null
+++ b/studio/backend/tests/test_llama_tool_parse_rejection_retry.py
@@ -0,0 +1,164 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""llama-server drops a reply its tool-call parser rejects; Studio re-asks with tool_choice "none" and parses it."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from core.inference.stream_errors import LlamaStreamError
+
+from .test_llama_cpp_tool_loop import (
+ _done,
+ _finish,
+ _make_backend,
+ _record_tool_calls,
+ _run_tool_loop,
+ _sse,
+ _tool_call_sse,
+ _web_search_tool,
+)
+
+_PEG = "The model produced output that does not match the expected peg-native format"
+_RAW_CALL = '{"type": "function", "function": "web_search", "parameters": {"query": "mars rover"}}'
+
+
+def _progress() -> str:
+ return (
+ "data: "
+ + json.dumps({"choices": [{"index": 0, "delta": {"role": "assistant", "content": None}}]})
+ + "\n"
+ )
+
+
+def _error(message: str) -> str:
+ return (
+ "data: "
+ + json.dumps({"error": {"code": 500, "message": message, "type": "server_error"}})
+ + "\n"
+ )
+
+
+def _content_stream(text: str) -> list[str]:
+ return (
+ [_progress()]
+ + [_sse({"content": text[i : i + 3]}) for i in range(0, len(text), 3)]
+ + [_finish("stop"), _done()]
+ )
+
+
+ "message",
+ [
+ _PEG,
+ 'Failed to parse input at pos 0: {"type": "function"',
+ "Failed to parse tool call arguments as JSON: [json.exception.parse_error.101]",
+ ],
+)
+def test_rejected_reply_is_asked_again_without_the_server_parser(monkeypatch, message):
+ payloads: list[dict] = []
+ streams = [
+ [_progress(), _error(message)],
+ _content_stream(_RAW_CALL),
+ _content_stream("Found it."),
+ ]
+ backend = _make_backend(monkeypatch, streams, payloads)
+ calls = _record_tool_calls(monkeypatch, "RESULT_OK")
+
+ events = _run_tool_loop(
+ backend,
+ [{"role": "user", "content": "Search for the mars rover."}],
+ [_web_search_tool()],
+ max_tool_iterations = 2,
+ )
+
+ assert calls == [("web_search", {"query": "mars rover"})]
+ assert [p.get("tool_choice") for p in payloads[:2]] == ["auto", "none"]
+ assert payloads[1]["messages"] == payloads[0]["messages"]
+ assert payloads[1]["tools"] == payloads[0]["tools"]
+ shown = [e["text"] for e in events if e.get("type") == "content"]
+ assert shown and shown[-1] == "Found it."
+ assert not any('"function"' in text for text in shown)
+
+
+def test_complete_calls_before_a_rejected_later_call_still_run(monkeypatch):
+ """Llama-3.2-1B ``;``-joins two calls: the first streams whole, then the second is rejected."""
+ payloads: list[dict] = []
+ streams = [
+ [_progress(), _tool_call_sse("web_search", {"query": "a"}, "c1"), _error(_PEG)],
+ _content_stream("Done."),
+ ]
+ backend = _make_backend(monkeypatch, streams, payloads)
+ calls = _record_tool_calls(monkeypatch, "RESULT_OK")
+
+ events = _run_tool_loop(
+ backend,
+ [{"role": "user", "content": "Search."}],
+ [_web_search_tool()],
+ max_tool_iterations = 2,
+ )
+
+ assert calls == [("web_search", {"query": "a"})]
+ assert [p.get("tool_choice") for p in payloads] == ["auto", "auto"]
+ assert [e["text"] for e in events if e.get("type") == "content"][-1] == "Done."
+
+
+def test_rejection_after_an_incomplete_streamed_call_still_fails(monkeypatch):
+ payloads: list[dict] = []
+ partial = {"index": 0, "id": "c1", "type": "function"}
+ partial["function"] = {"name": "web_search", "arguments": '{"query": "a'}
+ streams = [[_progress(), _sse({"tool_calls": [partial]}), _error(_PEG)]]
+ backend = _make_backend(monkeypatch, streams, payloads)
+ calls = _record_tool_calls(monkeypatch, "RESULT_OK")
+
+ with pytest.raises(LlamaStreamError):
+ _run_tool_loop(
+ backend,
+ [{"role": "user", "content": "Search."}],
+ [_web_search_tool()],
+ )
+ assert len(payloads) == 1
+ assert calls == []
+
+
+def test_other_stream_errors_are_not_retried(monkeypatch):
+ payloads: list[dict] = []
+ streams = [[_progress(), _error("the request exceeds the available context size")]]
+ backend = _make_backend(monkeypatch, streams, payloads)
+ _record_tool_calls(monkeypatch, "RESULT_OK")
+
+ with pytest.raises(LlamaStreamError):
+ _run_tool_loop(
+ backend,
+ [{"role": "user", "content": "Search."}],
+ [_web_search_tool()],
+ )
+ assert len(payloads) == 1
+
+
+def test_well_formed_structured_call_is_untouched(monkeypatch):
+ payloads: list[dict] = []
+ streams = [
+ [
+ _progress(),
+ _tool_call_sse("web_search", {"query": "a"}, "c1"),
+ _finish("tool_calls"),
+ _done(),
+ ],
+ _content_stream("Done."),
+ ]
+ backend = _make_backend(monkeypatch, streams, payloads)
+ calls = _record_tool_calls(monkeypatch, "RESULT_OK")
+
+ _run_tool_loop(
+ backend,
+ [{"role": "user", "content": "Search."}],
+ [_web_search_tool()],
+ max_tool_iterations = 2,
+ )
+
+ assert calls == [("web_search", {"query": "a"})]
+ assert [p.get("tool_choice") for p in payloads] == ["auto", "auto"]