]> git.djapps.eu Git - pkg/ggml/sources/llama.cpp/commitdiff
grammar : handle maxItems == 0 in JSON schema (#13117)
authorfrob <redacted>
Sat, 26 Apr 2025 08:10:20 +0000 (10:10 +0200)
committerGitHub <redacted>
Sat, 26 Apr 2025 08:10:20 +0000 (10:10 +0200)
Co-authored-by: Richard Lyons <redacted>
common/json-schema-to-grammar.cpp
examples/json_schema_to_grammar.py
examples/server/public_legacy/json-schema-to-grammar.mjs
tests/test-json-schema-to-grammar.cpp

index 90679822571204c02c66f0c828c7872febd61f3b..5b3059c2f774f3fa5c817aff695fd68d12d6e341 100644 (file)
@@ -16,6 +16,9 @@ using json = nlohmann::ordered_json;
 static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
     auto has_max = max_items != std::numeric_limits<int>::max();
 
+    if (max_items == 0) {
+        return "";
+    }
     if (min_items == 0 && max_items == 1) {
         return item_rule + "?";
     }
index 55f94c0b0a864d596b5b8c48be0fd2c45e9adefe..ed379585546c24c68ffed7d15de7f5954487ea5d 100755 (executable)
@@ -10,6 +10,9 @@ from typing import Any, List, Optional, Set, Tuple, Union
 
 def _build_repetition(item_rule, min_items, max_items, separator_rule=None):
 
+    if max_items == 0:
+        return ""
+
     if min_items == 0 and max_items == 1:
         return f'{item_rule}?'
 
index f767ce7b7200848599f1a8cf3ce01364a459a253..b12bf2ab0909ac14c304652e796b547f92e167f7 100644 (file)
@@ -2,6 +2,9 @@
 const SPACE_RULE = '| " " | "\\n"{1,2} [ \\t]{0,20}';
 
 function _buildRepetition(itemRule, minItems, maxItems, opts={}) {
+  if (maxItems == 0) {
+    return '';
+  }
   if (minItems === 0 && maxItems === 1) {
     return `${itemRule}?`;
   }
index e35134f3cb063194a70a61592676ea1375d7330b..38cf01d6d8dfb2fdb49399f56200fc414d801cd4 100755 (executable)
@@ -597,6 +597,22 @@ static void test_all(const std::string & lang, std::function<void(const TestCase
         )"""
     });
 
+    test({
+        SUCCESS,
+        "maxItems 0",
+        R"""({
+            "items": {
+                "type": "boolean"
+            },
+            "maxItems": 0
+        })""",
+        R"""(
+            boolean ::= ("true" | "false") space
+            root ::= "[" space  "]" space
+            space ::= | " " | "\n"{1,2} [ \t]{0,20}
+        )"""
+    });
+
     test({
         SUCCESS,
         "maxItems 1",