Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

serve: accept json_schema roots that are unions of object schemas

Juan Canfieldbcc39a1e4290
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index a1aa466b5..65e486db9 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -1102,7 +1102,10 @@ times out, the server keeps ownership and reports an error rather than claiming
`POST /v1/chat/completions` accepts `response_format: {"type":"json_object"}` or
`{"type":"json_schema","json_schema":{"name":"answer","strict":true,"schema":{"type":"object","properties":{"answer":{"type":"integer"}},"required":["answer"],"additionalProperties":false}}}`.
-The schema must describe an object at its root. Local `#` references work; remote references are refused.
+The schema must accept only JSON objects at its root: `"type":"object"`, or an `anyOf`/`oneOf` whose branches are all
+object schemas (an `allOf` with an object member, or a local `$ref` to one, also counts), as apps written for
+llama.cpp's `json_schema` send. A root that also allows an array, string, number, boolean or null is refused. Local
+`#` references work; remote references are refused.
`json_schema` is checked with the Python package `jsonschema` when it is installed (`python -m pip install
"jsonschema>=4.23,<5"`; setup does not add it); without it the answer is only checked to be one JSON object, and the
server says so once.
diff --git a/serve/structured.py b/serve/structured.py
index b5f079cce..3a726d607 100644
--- a/serve/structured.py
+++ b/serve/structured.py
@@ -51,6 +51,35 @@ def jsonschema_modules():
return _jsonschema or None
+def _only_objects(node, root, refs=()):
+ """True when every value `node` accepts is a JSON object, so "return one JSON object" stays true.
+
+ `type: object`, an anyOf/oneOf whose branches all qualify (e.g. a root union of object shapes, which llama.cpp's
+ grammar path accepts and apps send), an allOf with a qualifying member, or a local `$ref` to one of these.
+ Anything that can also be an array, string, number, boolean or null (including `type: ["object", "null"]`) is
+ not, and a `$ref` cycle never qualifies.
+ """
+ if not isinstance(node, dict):
+ return False
+ if node.get("type") == "object":
+ return True
+ ref = node.get("$ref")
+ if isinstance(ref, str) and ref.startswith("#") and ref not in refs:
+ target = root
+ for part in ref[1:].split("/")[1:]:
+ part = part.replace("~1", "/").replace("~0", "~")
+ if not isinstance(target, dict) or part not in target:
+ return False
+ target = target[part]
+ return _only_objects(target, root, refs + (ref,))
+ for key in ("anyOf", "oneOf"):
+ branches = node.get(key)
+ if isinstance(branches, list) and branches and all(_only_objects(b, root, refs) for b in branches):
+ return True
+ branches = node.get("allOf")
+ return isinstance(branches, list) and any(_only_objects(b, root, refs) for b in branches)
+
+
def prepare_format(response_format, messages):
if response_format is None:
return messages, None
@@ -71,8 +100,9 @@ def prepare_format(response_format, messages):
if "strict" in spec and not isinstance(spec["strict"], bool):
raise ValueError("response_format.json_schema.strict must be boolean")
schema = spec["schema"]
- if schema.get("type") != "object":
- raise ValueError("response_format schema must have type object at its root")
+ if not _only_objects(schema, schema):
+ raise ValueError("response_format schema must accept only JSON objects at its root "
+ "(type object, or anyOf/oneOf of object schemas)")
modules = jsonschema_modules()
else:
raise ValueError("response_format.type must be text, json_object or json_schema")
diff --git a/serve/test_structured.py b/serve/test_structured.py
index cc157a76d..be9fd0ee0 100644
--- a/serve/test_structured.py
+++ b/serve/test_structured.py
@@ -154,6 +154,50 @@ class Structured(unittest.TestCase):
self.assertEqual(reply["error"]["code"], "structured_output_failed")
self.assertEqual(self.chat('{"answer":4}', response_format={"type": "json_object"})[0], 200)
+ def test_root_unions_of_object_shapes_are_accepted(self):
+ # A root anyOf of object shapes (sent by apps written against llama.cpp's grammar path) still means
+ # "one JSON object", so it is accepted; a non-object answer is still refused.
+ claim = {"type": "object", "additionalProperties": False, "required": ["claim_text"],
+ "properties": {"claim_text": {"type": "string", "minLength": 1}}}
+ empty = {"type": "object", "additionalProperties": False, "required": ["outcome"],
+ "properties": {"outcome": {"type": "string", "enum": ["no_substantive_content"]}}}
+ schemas = [
+ {"anyOf": [claim, empty]},
+ {"oneOf": [claim, empty]},
+ {"allOf": [claim, {"required": ["claim_text"]}]},
+ {"$ref": "#/$defs/claim", "$defs": {"claim": claim}},
+ {"anyOf": [{"$ref": "#/$defs/claim"}, {"anyOf": [empty]}], "$defs": {"claim": claim}},
+ ]
+ for schema in schemas:
+ fmt = {"type": "json_schema", "json_schema": {"name": "union", "strict": True, "schema": schema}}
+ with self.subTest(schema=schema):
+ self.assertEqual(self.chat('{"claim_text":"The term is 12 months."}', response_format=fmt)[0], 200)
+ self.assertEqual(self.chat("[1, 2]", response_format=fmt)[0], 502)
+
+ def test_schemas_that_allow_non_objects_are_still_rejected(self):
+ obj = {"type": "object"}
+ schemas = [
+ {"type": "array", "items": obj},
+ {"type": "string"},
+ {"type": ["object", "null"]},
+ {"anyOf": [obj, {"type": "string"}]},
+ {"anyOf": []},
+ {"oneOf": [obj, {"type": "array"}]},
+ {"allOf": [{"type": "string"}]},
+ {"properties": {"x": {"type": "string"}}}, # no type: any JSON value validates
+ {"$ref": "#/$defs/a", "$defs": {"a": {"$ref": "#/$defs/a"}}}, # reference cycle
+ {"$ref": "#/$defs/missing", "$defs": {}},
+ {"$ref": "#/$defs/s", "$defs": {"s": {"type": "string"}}},
+ ]
+ with mock.patch.object(self.svc, "load") as load:
+ for schema in schemas:
+ fmt = {"type": "json_schema", "json_schema": {"name": "bad", "schema": schema}}
+ with self.subTest(schema=schema):
+ code, reply = self.chat(response_format=fmt)
+ self.assertEqual(code, 400)
+ self.assertIn("only JSON objects", reply["error"]["message"])
+ load.assert_not_called()
+
def test_the_server_does_not_import_jsonschema_at_start(self):
import subprocess
import sys