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: drop the schema bounds llama.cpp's grammar engine cannot compile (#9923)

Long Yixingd2c1345b3632
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 284e2085eed..ef8283542e8 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -299,19 +299,17 @@ def _friendly_gen_stream_error(value) -> str:
def _friendly_upstream_error(text: str) -> str:
"""Rewrite a raw llama-server error body into an actionable message where we can.
- The main case is a tool-calling grammar that llama-server can't compile ("failed to
- parse grammar" / "failed to initialize samplers"). This surfaces to coding agents as
- a hard 400 on every tool-bearing turn. It is a llama-server limitation with some
- model/quant + tool-schema combinations, and recent llama.cpp builds handle the common
- coding-agent tools, so point the user at updating Unsloth rather than the raw body.
+ A grammar llama-server cannot compile surfaces to coding agents as a hard 400 on
+ every tool-bearing turn, and comes from the request's schemas, not from the model or
+ quant. Other sampler failures keep their own text, which already names what is wrong.
"""
lowered = text.lower()
- if "failed to parse grammar" in lowered or "failed to initialize samplers" in lowered:
+ if "failed to parse grammar" in lowered:
return (
- "The model couldn't compile a tool-calling grammar for this request. This is a "
- "llama-server limitation with some model/quant and tool-schema combinations. "
- "Update Unsloth (it installs the latest llama.cpp, which handles the common "
- "coding-agent tools) or try a different GGUF model."
+ "The model couldn't compile a grammar for this request. A tool or response_format "
+ "schema in it carries a constraint llama-server's grammar engine cannot compile, "
+ "which does not depend on the model or quant. Update Unsloth, which drops the "
+ "constraints known to break it, and report the schemas if it still fails."
)
return f"llama-server error: {text}"
@@ -27597,22 +27595,35 @@ _JSON_SCHEMA_SINGLE_KEYWORDS = frozenset(
"unevaluatedProperties",
}
)
-_JSON_SCHEMA_LIST_KEYWORDS = frozenset({"allOf", "anyOf", "oneOf", "prefixItems"})
-_LLAMA_GRAMMAR_MAX_REPETITION = 2000
-_JSON_SCHEMA_REPETITION_KEYWORDS = frozenset({"maxItems", "maxLength", "minItems", "minLength"})
+# "items" is in both sets: draft 2020-12 gives it one schema, draft-07 a tuple of them.
+_JSON_SCHEMA_LIST_KEYWORDS = frozenset({"allOf", "anyOf", "items", "oneOf", "prefixItems"})
+# Highest bound each keyword can reach in llama-grammar.cpp's budget of 2000 generated rules.
+# Measured against llama.cpp b10639 and b10679: a string bound of N costs N rules, minItems N-1,
+# and maxItems N+2, its repetition sitting inside a group the enclosing quantifier is charged for
+# too. The array limits assume no lower bound, the costliest shape. Bounds far past the budget
+# compile again as unbounded repetitions; the band just above these does not.
+_JSON_SCHEMA_REPETITION_LIMITS = {
+ "maxItems": 1997,
+ "maxLength": 1999,
+ "minItems": 2000,
+ "minLength": 1999,
+}
+
+
+def _is_json_number(value) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
def _llama_compatible_tool_schema(schema):
"""Return a llama.cpp-compatible copy of one JSON Schema node.
- JSON Schema ``pattern`` expressions match anywhere in a string, so an
- unanchored pattern is valid and cannot be made compatible by merely adding
- ``^`` and ``$`` without changing its meaning. llama.cpp's grammar converter
- currently rejects those patterns outright. Its grammar parser likewise
- rejects repetition bounds above 2000. Omit only those unsupported
- constraints from the local-backend copy; the agent retains and validates
- its original schema, while every compatible constraint still reaches
- llama.cpp.
+ llama.cpp's converter rejects an unanchored ``pattern`` outright, and anchoring
+ one would change what it matches; its grammar parser fails on repetition bounds
+ that reach its rule budget. Both come off the local-backend copy, erring towards
+ dropping a constraint the backend would have taken, since the agent validates its
+ original schema either way. Recursion follows the schema keywords, so a ``$ref``
+ is covered where its target lives in ``$defs`` or ``definitions``, not where a
+ pointer reaches some other part of the document.
"""
if not isinstance(schema, dict):
return schema
@@ -27621,18 +27632,19 @@ def _llama_compatible_tool_schema(schema):
pattern = compatible.get("pattern")
if isinstance(pattern, str) and not (pattern.startswith("^") and pattern.endswith("$")):
compatible.pop("pattern")
- # llama-grammar.cpp refuses repetition bounds above its sane-default
- # threshold. Dropping the local-backend constraint preserves every value
- # the client schema accepts; capping it would incorrectly reject otherwise
- # valid tool arguments.
- for keyword in _JSON_SCHEMA_REPETITION_KEYWORDS:
+ for keyword, limit in _JSON_SCHEMA_REPETITION_LIMITS.items():
bound = compatible.get(keyword)
- if (
- isinstance(bound, int)
- and not isinstance(bound, bool)
- and bound > _LLAMA_GRAMMAR_MAX_REPETITION
- ):
+ # An integral bound can decode to float, and llama.cpp reads one either way.
+ if _is_json_number(bound) and bound > limit:
compatible.pop(keyword)
+ # A lower bound above its upper bound becomes a descending repetition, which
+ # llama-grammar.cpp expands until the process runs out of memory. No grammar
+ # expresses such a pair anyway, so neither half survives.
+ for lower, upper in (("minItems", "maxItems"), ("minLength", "maxLength")):
+ low, high = compatible.get(lower), compatible.get(upper)
+ if _is_json_number(low) and _is_json_number(high) and low > high:
+ compatible.pop(lower)
+ compatible.pop(upper)
for keyword in _JSON_SCHEMA_MAP_KEYWORDS:
children = compatible.get(keyword)
@@ -27654,6 +27666,28 @@ def _llama_compatible_tool_schema(schema):
return compatible
+def _llama_compatible_response_format(response_format):
+ """Return a copy whose guided-decoding schema llama.cpp's grammar engine can compile.
+
+ llama-server reads it from ``json_object``'s ``schema`` and from ``json_schema``'s
+ nested ``schema``, and hands both to the converter that rejects tool schemas.
+ """
+ if not isinstance(response_format, dict):
+ return response_format
+
+ compatible = dict(response_format)
+ schema = compatible.get("schema")
+ if isinstance(schema, dict):
+ compatible["schema"] = _llama_compatible_tool_schema(schema)
+ wrapper = compatible.get("json_schema")
+ if isinstance(wrapper, dict) and isinstance(wrapper.get("schema"), dict):
+ compatible["json_schema"] = {
+ **wrapper,
+ "schema": _llama_compatible_tool_schema(wrapper["schema"]),
+ }
+ return compatible
+
+
def _llama_compatible_tools(openai_tools):
if not isinstance(openai_tools, list):
return openai_tools
@@ -27761,7 +27795,7 @@ def _build_passthrough_payload(
# response_format is present. The field is documented flat at the
# request root (tools/server/README.md), which is also what the OpenAI
# SDK produces by spreading extra_body into the body top.
- body["response_format"] = response_format
+ body["response_format"] = _llama_compatible_response_format(response_format)
if chat_template_kwargs is not None:
# Propagate reasoning / template overrides (e.g. enable_thinking) so
# llama-server renders the Jinja template in the caller's mode instead
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index c96d4b1ca80..803882dac07 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -130,10 +130,21 @@ class TestFriendlyUpstreamError:
raw = '{"error":{"code":400,"message":"Failed to initialize samplers: failed to parse grammar","type":"invalid_request_error"}}'
msg = _friendly_upstream_error(raw)
assert "failed to parse grammar" not in msg # raw body is not surfaced verbatim
- assert "tool-calling grammar" in msg and "Update Unsloth" in msg
-
- def test_failed_to_initialize_samplers_alone_matches(self):
- assert "tool-calling grammar" in _friendly_upstream_error("Failed to initialize samplers")
+ assert "compile a grammar" in msg and "Update Unsloth" in msg
+
+ def test_sampler_failure_without_a_grammar_keeps_its_own_text(self):
+ # llama-server prefixes every sampler failure the same way, so a bad penalty
+ # would otherwise be reported as an uncompilable schema.
+ detail = "Failed to initialize samplers: penalty_repeat must be finite and greater than 0"
+ msg = _friendly_upstream_error(detail)
+ assert "compile a grammar" not in msg
+ assert "penalty_repeat" in msg
+
+ def test_message_does_not_blame_the_model(self):
+ # The request's schemas decide the failure; swapping the GGUF changes nothing.
+ msg = _friendly_upstream_error("failed to parse grammar")
+ assert "schema" in msg
+ assert "GGUF" not in msg and "quant and tool-schema" not in msg
def test_unrelated_error_passes_through(self):
assert _friendly_upstream_error("out of memory") == "llama-server error: out of memory"
@@ -146,7 +157,7 @@ class TestFriendlyUpstreamError:
exc = _openai_passthrough_error(
400, '{"error":{"message":"Failed to initialize samplers: failed to parse grammar"}}'
)
- assert "tool-calling grammar" in exc.detail
+ assert "compile a grammar" in exc.detail
# An unrelated upstream error still passes through verbatim.
assert "llama-server error:" in _openai_passthrough_error(500, "disk full").detail
@@ -2308,8 +2319,35 @@ class TestBuildPassthroughPayloadToolChoice:
},
},
"largeScript": {"type": "string", "minLength": 1, "maxLength": 65536},
- "boundedScript": {"type": "string", "maxLength": 2000},
+ # Each keyword's highest compilable bound survives; the first one that reaches
+ # llama.cpp's rule budget does not.
+ "keptScript": {"type": "string", "maxLength": 1999, "minLength": 1999},
+ "budgetScript": {"type": "string", "maxLength": 2000},
+ "budgetFloor": {"type": "string", "minLength": 2000},
+ "keptList": {"type": "array", "items": {"type": "string"}, "maxItems": 1997},
+ "budgetList": {"type": "array", "items": {"type": "string"}, "maxItems": 1998},
+ "keptFloorList": {"type": "array", "items": {"type": "string"}, "minItems": 2000},
+ "budgetFloorList": {"type": "array", "items": {"type": "string"}, "minItems": 2001},
+ # An integral bound can decode to float, and llama.cpp reads one either way.
+ "floatList": {"type": "array", "items": {"type": "string"}, "minItems": 2001.0},
+ # draft-07 tuple form, which llama.cpp visits member by member.
+ "tupleList": {
+ "type": "array",
+ "items": [{"type": "string", "maxLength": 2000}],
+ },
+ # Unsatisfiable pairs, small enough to pass every limit above: they reach the
+ # parser as a descending repetition, which exhausts memory.
+ "impossibleList": {
+ "type": "array",
+ "items": {"type": "string"},
+ "minItems": 5,
+ "maxItems": 2,
+ },
+ "impossibleScript": {"type": "string", "minLength": 5, "maxLength": 2},
+ "referenced": {"$ref": "#/$defs/Bounded"},
}
+ # llama.cpp resolves the reference, so its target has to be filtered too.
+ schema["$defs"] = {"Bounded": {"type": "string", "maxLength": 2000}}
body = _build_passthrough_payload(**args)
forwarded = body["tools"][0]["function"]["parameters"]["properties"]
@@ -2321,11 +2359,70 @@ class TestBuildPassthroughPayloadToolChoice:
assert nested["anyOf"][1]["pattern"] == "^fixed$"
assert nested["default"] == {"pattern": "annotation data"}
assert forwarded["largeScript"] == {"type": "string", "minLength": 1}
- assert forwarded["boundedScript"]["maxLength"] == 2000
+ assert forwarded["keptScript"] == {"type": "string", "maxLength": 1999, "minLength": 1999}
+ assert forwarded["budgetScript"] == {"type": "string"}
+ assert forwarded["budgetFloor"] == {"type": "string"}
+ assert forwarded["keptList"]["maxItems"] == 1997
+ assert forwarded["budgetList"] == {"type": "array", "items": {"type": "string"}}
+ assert forwarded["keptFloorList"]["minItems"] == 2000
+ assert forwarded["budgetFloorList"] == {"type": "array", "items": {"type": "string"}}
+ assert forwarded["floatList"] == {"type": "array", "items": {"type": "string"}}
+ assert forwarded["tupleList"]["items"] == [{"type": "string"}]
+ assert schema["properties"]["budgetScript"]["maxLength"] == 2000
+ assert schema["properties"]["budgetList"]["maxItems"] == 1998
+ assert forwarded["impossibleList"] == {"type": "array", "items": {"type": "string"}}
+ assert forwarded["impossibleScript"] == {"type": "string"}
+ assert schema["properties"]["tupleList"]["items"][0]["maxLength"] == 2000
+ assert schema["properties"]["impossibleList"]["minItems"] == 5
+ assert body["tools"][0]["function"]["parameters"]["$defs"] == {
+ "Bounded": {"type": "string"}
+ }
+ assert schema["$defs"]["Bounded"]["maxLength"] == 2000
assert schema["properties"]["declarationKey"]["pattern"] == r"\S"
assert schema["properties"]["nested"]["items"]["anyOf"][0]["pattern"] == "token"
assert schema["properties"]["largeScript"]["maxLength"] == 65536
+ def test_repetition_limits_match_the_measured_grammar_budget(self):
+ # First bound llama-server refuses, measured against llama.cpp b10639 and b10679 by
+ # posting each schema to a live server. maxItems costs N+2 rules, not N+1, so 1998 is
+ # already over budget even though the other three keywords reach 2000.
+ from routes.inference import _JSON_SCHEMA_REPETITION_LIMITS
+ first_rejected = {"maxItems": 1998, "maxLength": 2000, "minItems": 2001, "minLength": 2000}
+ assert _JSON_SCHEMA_REPETITION_LIMITS == {
+ keyword: value - 1 for keyword, value in first_rejected.items()
+ }
+
+ def test_response_format_schema_drops_incompatible_constraints(self):
+ # Guided decoding reaches the same grammar engine tool schemas do.
+ rf = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "report",
+ "schema": {
+ "type": "object",
+ "properties": {"summary": {"type": "string", "maxLength": 2000}},
+ },
+ },
+ }
+ body = _build_passthrough_payload(**self._args(), response_format = rf)
+ forwarded = body["response_format"]["json_schema"]["schema"]["properties"]["summary"]
+ assert forwarded == {"type": "string"}
+ assert body["response_format"]["type"] == "json_schema"
+ assert body["response_format"]["json_schema"]["name"] == "report"
+ assert rf["json_schema"]["schema"]["properties"]["summary"]["maxLength"] == 2000
+
+ def test_response_format_json_object_schema_is_filtered_too(self):
+ # An array bound only reaches the grammar when the items schema does too.
+ rf = {
+ "type": "json_object",
+ "schema": {"type": "array", "items": {"type": "string"}, "maxItems": 1999},
+ }
+ body = _build_passthrough_payload(**self._args(), response_format = rf)
+ assert body["response_format"] == {
+ "type": "json_object",
+ "schema": {"type": "array", "items": {"type": "string"}},
+ }
+
def test_stream_omits_usage_options_when_client_did_not_request_them(self):
args = self._args()
args["stream"] = True