Skip to content

LLM inference in C/C++

C++ ggml

common/json-schema : fix GBNF grammar generation for empty object schemas (#28279)

Sergey Sklyarovc5a5535e6ebc
diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp
index 0aee51b26e..a7a18857d7 100644
--- a/common/json-schema-to-grammar.cpp
+++ b/common/json-schema-to-grammar.cpp
@@ -748,6 +748,10 @@ private:
optional_props.push_back("*");
}
+ if (required_props.empty() && optional_props.empty()) {
+ return "\"{\" space \"}\"";
+ }
+
std::string rule = "\"{\" space ";
for (size_t i = 0; i < required_props.size(); i++) {
if (i > 0) {
diff --git a/examples/json_schema_to_grammar.py b/examples/json_schema_to_grammar.py
index 83abd259da..02b7ef15ae 100755
--- a/examples/json_schema_to_grammar.py
+++ b/examples/json_schema_to_grammar.py
@@ -734,6 +734,9 @@ class SchemaConverter:
)
optional_props.append("*")
+ if not required_props and not optional_props:
+ return '"{" space "}"'
+
rule = '"{" space '
rule += ' "," space '.join(prop_kv_rule_names[k] for k in required_props)
diff --git a/tests/test-json-schema-to-grammar.cpp b/tests/test-json-schema-to-grammar.cpp
index 214dbe1993..2a1b6348c9 100755
--- a/tests/test-json-schema-to-grammar.cpp
+++ b/tests/test-json-schema-to-grammar.cpp
@@ -994,7 +994,7 @@ static void test_all(const std::string & lang, std::function<void(const TestCase
"additionalProperties": false
})""",
R"""(
- root ::= "{" space space "}"
+ root ::= "{" space "}"
space ::= | " " | "\n"{1,2} [ \t]{0,20}
)"""
});