char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Aldehir Rojascommon : implement common_schema internal representation for JSON schemas (#28736)acecd5603

char/aliceai-t5-moe
42.4 KiB1027 linesraw
1#include "json-schema-to-grammar.h"
2#include "common.h"
3#include "trie.h"
4#include "unicode.h"
5
6#include <algorithm>
7#include <limits>
8#include <map>
9#include <regex>
10#include <sstream>
11#include <string>
12#include <unordered_map>
13#include <unordered_set>
14#include <vector>
15
16using json = common_json;
17
18static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
19    auto has_max = max_items != std::numeric_limits<int>::max();
20
21    if (max_items == 0) {
22        return "";
23    }
24    if (min_items == 0 && max_items == 1) {
25        return item_rule + "?";
26    }
27
28    if (separator_rule.empty()) {
29        if (min_items == 1 && !has_max) {
30            return item_rule + "+";
31        }
32        if (min_items == 0 && !has_max) {
33            return item_rule + "*";
34        }
35        return item_rule + "{" + std::to_string(min_items) + "," + (has_max ? std::to_string(max_items) : "") + "}";
36    }
37
38    auto result = item_rule + " " + build_repetition("(" + separator_rule + " " + item_rule + ")", min_items == 0 ? 0 : min_items - 1, has_max ? max_items - 1 : max_items);
39    if (min_items == 0) {
40        result = "(" + result + ")?";
41    }
42    return result;
43}
44
45static void build_min_max_int(int64_t min_value, int64_t max_value, std::stringstream & out, int decimals_left = 16, bool top_level = true) {
46    auto has_min = min_value != std::numeric_limits<int64_t>::min();
47    auto has_max = max_value != std::numeric_limits<int64_t>::max();
48
49    auto digit_range = [&](char from, char to) {
50        out << "[";
51        if (from == to) {
52            out << from;
53        } else {
54            out << from << "-" << to;
55        }
56        out << "]";
57    };
58    auto more_digits = [&](int min_digits, int max_digits) {
59        out << "[0-9]";
60        if (min_digits == max_digits && min_digits == 1) {
61            return;
62        }
63        out << "{";
64        out << min_digits;
65        if (max_digits != min_digits) {
66            out << ",";
67            if (max_digits != std::numeric_limits<int>::max()) {
68                out << max_digits;
69            }
70        }
71        out << "}";
72    };
73    std::function<void(const std::string_view &, const std::string_view &)> uniform_range =
74        [&](const std::string_view & from, const std::string_view & to) {
75            size_t i = 0;
76            while (i < from.length() && i < to.length() && from[i] == to[i]) {
77                i++;
78            }
79            if (i > 0) {
80                out << "\"" << from.substr(0, i) << "\"";
81            }
82            if (i < from.length() && i < to.length()) {
83                if (i > 0) {
84                    out << " ";
85                }
86                auto sub_len = from.length() - i - 1;
87                if (sub_len > 0) {
88                    auto from_sub = from.substr(i + 1);
89                    auto to_sub = to.substr(i + 1);
90                    auto sub_zeros = string_repeat("0", sub_len);
91                    auto sub_nines = string_repeat("9", sub_len);
92
93                    auto to_reached = false;
94                    out << "(";
95                    if (from_sub == sub_zeros) {
96                        digit_range(from[i], to[i] - 1);
97                        out << " ";
98                        more_digits(sub_len, sub_len);
99                    } else {
100                        out << "[" << from[i] << "] ";
101                        out << "(";
102                        uniform_range(from_sub, sub_nines);
103                        out << ")";
104                        if (from[i] < to[i] - 1) {
105                            out << " | ";
106                            if (to_sub == sub_nines) {
107                                digit_range(from[i] + 1, to[i]);
108                                to_reached = true;
109                            } else {
110                                digit_range(from[i] + 1, to[i] - 1);
111                            }
112                            out << " ";
113                            more_digits(sub_len, sub_len);
114                        }
115                    }
116                    if (!to_reached) {
117                        out << " | ";
118                        digit_range(to[i], to[i]);
119                        out << " ";
120                        uniform_range(sub_zeros, to_sub);
121                    }
122                    out << ")";
123                } else {
124                    out << "[" << from[i] << "-" << to[i] << "]";
125                }
126            }
127        };
128
129    if (has_min && has_max) {
130        if (min_value < 0 && max_value < 0) {
131            out << "\"-\" (";
132            build_min_max_int(-max_value, -min_value, out, decimals_left, /* top_level= */ true);
133            out << ")";
134            return;
135        }
136
137        if (min_value < 0) {
138            out << "\"-\" (";
139            build_min_max_int(0, -min_value, out, decimals_left, /* top_level= */ true);
140            out << ") | ";
141            min_value = 0;
142        }
143
144        auto min_s = std::to_string(min_value);
145        auto max_s = std::to_string(max_value);
146        auto min_digits = min_s.length();
147        auto max_digits = max_s.length();
148
149        for (auto digits = min_digits; digits < max_digits; digits++) {
150            uniform_range(min_s, string_repeat("9", digits));
151            min_s = "1" + string_repeat("0", digits);
152            out << " | ";
153        }
154        uniform_range(min_s, max_s);
155        return;
156    }
157
158    auto less_decimals = std::max(decimals_left - 1, 1);
159
160    if (has_min) {
161        if (min_value < 0) {
162            out << "\"-\" (";
163            build_min_max_int(std::numeric_limits<int64_t>::min(), -min_value, out, decimals_left, /* top_level= */ false);
164            out << ") | [0] | [1-9] ";
165            more_digits(0, decimals_left - 1);
166        } else if (min_value == 0) {
167            if (top_level) {
168                out << "[0] | [1-9] ";
169                more_digits(0, less_decimals);
170            } else {
171                more_digits(1, decimals_left);
172            }
173        } else if (min_value <= 9) {
174            char c = '0' + min_value;
175            auto range_start = top_level ? '1' : '0';
176            if (c > range_start) {
177                digit_range(range_start, c - 1);
178                out << " ";
179                more_digits(1, less_decimals);
180                out << " | ";
181            }
182            digit_range(c, '9');
183            out << " ";
184            more_digits(0, less_decimals);
185        } else {
186            auto min_s = std::to_string(min_value);
187            auto len = min_s.length();
188            auto c = min_s[0];
189
190            if (c > '1') {
191                digit_range(top_level ? '1' : '0', c - 1);
192                out << " ";
193                more_digits(len, less_decimals);
194                out << " | ";
195            }
196            digit_range(c, c);
197            out << " (";
198            build_min_max_int(std::stoll(min_s.substr(1)), std::numeric_limits<int64_t>::max(), out, less_decimals, /* top_level= */ false);
199            out << ")";
200            if (c < '9') {
201                out << " | ";
202                digit_range(c + 1, '9');
203                out << " ";
204                more_digits(len - 1, less_decimals);
205            }
206        }
207        return;
208    }
209
210    if (has_max) {
211        if (max_value >= 0) {
212            if (top_level) {
213                out << "\"-\" [1-9] ";
214                more_digits(0, less_decimals);
215                out << " | ";
216            }
217            build_min_max_int(0, max_value, out, decimals_left, /* top_level= */ true);
218        } else {
219            out << "\"-\" (";
220            build_min_max_int(-max_value, std::numeric_limits<int64_t>::max(), out, decimals_left, /* top_level= */ false);
221            out << ")";
222        }
223        return;
224    }
225
226    throw std::runtime_error("At least one of min_value or max_value must be set");
227}
228
229const std::string SPACE_RULE = "| \" \" | \"\\n\"{1,2} [ \\t]{0,20}";
230
231struct BuiltinRule {
232    std::string content;
233    std::vector<std::string> deps;
234};
235
236static std::unordered_map<std::string, BuiltinRule> PRIMITIVE_RULES = {
237    {"boolean", {"(\"true\" | \"false\")", {}}},
238    {"decimal-part", {"[0-9]{1,16}", {}}},
239    {"integral-part", {"[0] | [1-9] [0-9]{0,15}", {}}},
240    {"number", {"(\"-\"? integral-part) (\".\" decimal-part)? ([eE] [-+]? integral-part)?", {"integral-part", "decimal-part"}}},
241    {"integer", {"(\"-\"? integral-part)", {"integral-part"}}},
242    {"value", {"object | array | string | number | boolean | null", {"object", "array", "string", "number", "boolean", "null"}}},
243    {"object", {"\"{\" space ( string \":\" space value (\",\" space string \":\" space value)* )? space \"}\"", {"string", "value"}}},
244    {"array", {"\"[\" space ( value (\",\" space value)* )? space \"]\"", {"value"}}},
245    {"uuid", {"\"\\\"\" [0-9a-fA-F]{8} \"-\" [0-9a-fA-F]{4} \"-\" [0-9a-fA-F]{4} \"-\" [0-9a-fA-F]{4} \"-\" [0-9a-fA-F]{12} \"\\\"\"", {}}},
246    {"char",   {"[^\"\\\\\\x7F\\x00-\\x1F] | [\\\\] ([\"\\\\bfnrt] | \"u\" [0-9a-fA-F]{4})", {}}},
247    {"string", {"\"\\\"\" char* \"\\\"\"", {"char"}}},
248    {"null", {"\"null\"", {}}},
249};
250
251static std::unordered_map<std::string, BuiltinRule> STRING_FORMAT_RULES = {
252    {"date", {"[0-9]{4} \"-\" ( \"0\" [1-9] | \"1\" [0-2] ) \"-\" ( \"0\" [1-9] | [1-2] [0-9] | \"3\" [0-1] )", {}}},
253    {"time", {"([01] [0-9] | \"2\" [0-3]) \":\" [0-5] [0-9] \":\" [0-5] [0-9] ( \".\" [0-9]{3} )? ( \"Z\" | ( \"+\" | \"-\" ) ( [01] [0-9] | \"2\" [0-3] ) \":\" [0-5] [0-9] )", {}}},
254    {"date-time", {"date \"T\" time", {"date", "time"}}},
255    {"date-string", {"\"\\\"\" date \"\\\"\"", {"date"}}},
256    {"time-string", {"\"\\\"\" time \"\\\"\"", {"time"}}},
257    {"date-time-string", {"\"\\\"\" date-time \"\\\"\"", {"date-time"}}}
258};
259
260static bool is_reserved_name(const std::string & name) {
261    static const std::unordered_set<std::string> RESERVED_NAMES = [] {
262        std::unordered_set<std::string> s;
263        s.insert("root");
264        for (const auto & p : PRIMITIVE_RULES) {
265            s.insert(p.first);
266        }
267        for (const auto & p : STRING_FORMAT_RULES) {
268            s.insert(p.first);
269        }
270        return s;
271    }();
272    return RESERVED_NAMES.find(name) != RESERVED_NAMES.end();
273}
274
275static std::regex INVALID_RULE_CHARS_RE("[^a-zA-Z0-9-]+");
276static std::regex GRAMMAR_LITERAL_ESCAPE_RE("[\r\n\"\\\\]");
277static std::regex GRAMMAR_RANGE_LITERAL_ESCAPE_RE("[\r\n\"\\]\\-\\\\]");
278static std::unordered_map<char, std::string> GRAMMAR_LITERAL_ESCAPES = {
279    {'\r', "\\r"}, {'\n', "\\n"}, {'"', "\\\""}, {'-', "\\-"}, {']', "\\]"}, {'\\', "\\\\"}
280};
281
282static const int MAX_PATTERN_DEPTH = 100;
283
284static std::unordered_set<char> NON_LITERAL_SET = {'|', '.', '(', ')', '[', ']', '{', '}', '*', '+', '?', '^', '$'};
285static std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'};
286
287static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch  &)> & replacement) {
288    std::smatch match;
289    std::string result;
290
291    std::string::const_iterator searchStart(input.cbegin());
292    std::string::const_iterator searchEnd(input.cend());
293
294    while (std::regex_search(searchStart, searchEnd, match, regex)) {
295        result.append(searchStart, searchStart + match.position());
296        result.append(replacement(match));
297        searchStart = match.suffix().first;
298    }
299
300    result.append(searchStart, searchEnd);
301
302    return result;
303}
304
305static std::string format_literal(const std::string & literal) {
306    std::string escaped = replacePattern(literal, GRAMMAR_LITERAL_ESCAPE_RE, [&](const std::smatch & match) {
307        char c = match.str()[0];
308        return GRAMMAR_LITERAL_ESCAPES.at(c);
309    });
310    return "\"" + escaped + "\"";
311}
312
313std::string gbnf_format_literal(const std::string & literal) { return format_literal(literal); }
314
315static size_t gbnf_escape_length(const std::string & pattern, size_t pos) {
316    if (pos + 1 >= pattern.length() || pattern[pos] != '\\') {
317        return 0;
318    }
319    size_t n_hex = 0;
320    switch (pattern[pos + 1]) {
321        case 'x': n_hex = 2; break;
322        case 'u': n_hex = 4; break;
323        case 'U': n_hex = 8; break;
324        case 't': case 'r': case 'n': case '\\': case '"': case '[': case ']':
325            return 2;
326        default:
327            return 0;
328    }
329    if (pos + 2 + n_hex > pattern.length()) {
330        return 0;
331    }
332    for (size_t i = pos + 2; i < pos + 2 + n_hex; i++) {
333        char h = pattern[i];
334        if (!((h >= '0' && h <= '9') || (h >= 'a' && h <= 'f') || (h >= 'A' && h <= 'F'))) {
335            return 0;
336        }
337    }
338    return 2 + n_hex;
339}
340
341class common_chat_schema_converter {
342private:
343    friend std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options);
344    bool _dotall;
345    std::map<std::string, std::string> _rules;
346    std::unordered_set<std::string> _refs_being_resolved;
347    std::vector<std::string> _errors;
348    std::vector<std::string> _warnings;
349
350    template <typename T>
351    static const T & as(const common_chat_schema & node) {
352        return static_cast<const T &>(node);
353    }
354
355    std::string _add_rule(const std::string & name, const std::string & rule) {
356        std::string esc_name = regex_replace(name, INVALID_RULE_CHARS_RE, "-");
357        if (_rules.find(esc_name) == _rules.end() || _rules[esc_name] == rule) {
358            _rules[esc_name] = rule;
359            return esc_name;
360        }
361        int i = 0;
362        while (_rules.find(esc_name + std::to_string(i)) != _rules.end() && _rules[esc_name + std::to_string(i)] != rule) {
363            i++;
364        }
365        std::string key = esc_name + std::to_string(i);
366        _rules[key] = rule;
367        return key;
368    }
369
370    std::string _generate_union_rule(const std::string & name, const std::vector<common_chat_schema_ptr> & alt_schemas) {
371        std::vector<std::string> rules;
372        rules.reserve(alt_schemas.size());
373        for (size_t i = 0; i < alt_schemas.size(); i++) {
374            rules.push_back(visit(*alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i)));
375        }
376        return string_join(rules, " | ");
377    }
378
379    // thrown when the pattern is a valid regex with no grammar equivalent
380    struct unsupported_pattern : public std::runtime_error {
381        using std::runtime_error::runtime_error;
382    };
383
384    // thrown when the pattern is not a valid regex
385    struct invalid_pattern : public std::runtime_error {
386        using std::runtime_error::runtime_error;
387    };
388
389    std::string _visit_pattern(const std::string & pattern, const std::string & name) {
390        auto rules_snapshot = _rules;
391        try {
392            return _pattern_to_rule(pattern, name);
393        } catch (const unsupported_pattern & err) {
394            // revert rules
395            _rules = std::move(rules_snapshot);
396            _warnings.push_back("pattern " + pattern + " is not supported (" + err.what() + "), accepting any string");
397            return _add_rule(name, _add_primitive("string", PRIMITIVE_RULES.at("string")));
398        } catch (const invalid_pattern & err) {
399            _rules = std::move(rules_snapshot);
400            _errors.push_back("Invalid pattern " + pattern + ": " + err.what());
401            return "";
402        }
403    }
404
405    std::string _pattern_to_rule(const std::string & pattern, const std::string & name) {
406        if (pattern.length() < 2 || pattern.front() != '^' || pattern.back() != '$') {
407            throw unsupported_pattern("not anchored with '^' and '$'");
408        }
409        std::string sub_pattern = pattern.substr(1, pattern.length() - 2);
410        std::unordered_map<std::string, std::string> sub_rule_ids;
411
412        size_t i = 0;
413        size_t length = sub_pattern.length();
414        int paren_depth = 0;
415
416        using literal_or_rule = std::pair<std::string, bool>;
417        auto to_rule = [&](const literal_or_rule & ls) {
418            auto is_literal = ls.second;
419            auto s = ls.first;
420            return is_literal ? "\"" + s + "\"" : s;
421        };
422        std::function<literal_or_rule()> transform = [&]() -> literal_or_rule {
423            std::vector<literal_or_rule> seq;
424
425            auto get_dot = [&]() {
426                std::string rule;
427                if (_dotall) {
428                    rule = "[\\U00000000-\\U0010FFFF]";
429                } else {
430                    rule = "[^\\x0A\\x0D]";
431                }
432                return _add_rule("dot", rule);
433            };
434
435            // Joins the sequence, merging consecutive literals together.
436            auto join_seq = [&]() {
437                std::vector<literal_or_rule> ret;
438
439                std::string literal;
440                auto flush_literal = [&]() {
441                    if (literal.empty()) {
442                        return false;
443                    }
444                    ret.emplace_back(literal, true);
445                    literal.clear();
446                    return true;
447                };
448
449                for (const auto & item : seq) {
450                    auto is_literal = item.second;
451                    if (is_literal) {
452                        literal += item.first;
453                    } else {
454                        flush_literal();
455                        ret.push_back(item);
456                    }
457                }
458                flush_literal();
459
460                std::vector<std::string> results;
461                results.reserve(ret.size());
462                for (const auto & item : ret) {
463                    results.push_back(to_rule(item));
464                }
465                return std::make_pair(string_join(results, " "), false);
466            };
467
468            while (i < length) {
469                char c = sub_pattern[i];
470                if (c == '.') {
471                    seq.emplace_back(get_dot(), false);
472                    i++;
473                } else if (c == '(') {
474                    i++;
475                    if (i < length && sub_pattern[i] == '?') {
476                        if (i + 1 < length && sub_pattern[i + 1] == ':') {
477                            i += 2; // skip "?:" for non-capturing group, treat as regular group
478                        } else {
479                            // lookaround, named group, inline flags, ...
480                            throw unsupported_pattern("unsupported group syntax");
481                        }
482                    }
483                    paren_depth++;
484                    if (paren_depth > MAX_PATTERN_DEPTH) {
485                        throw unsupported_pattern("pattern nesting too deep");
486                    }
487                    seq.emplace_back("(" + to_rule(transform()) + ")", false);
488                } else if (c == ')') {
489                    i++;
490                    if (paren_depth == 0) {
491                        throw invalid_pattern("unbalanced parentheses");
492                    }
493                    paren_depth--;
494                    return join_seq();
495                } else if (c == '^' || c == '$') {
496                    throw unsupported_pattern("anchor inside the pattern");
497                } else if (c == '[') {
498                    std::string square_brackets = std::string(1, c);
499                    i++;
500                    while (i < length && sub_pattern[i] != ']') {
501                        if (sub_pattern[i] == '\\') {
502                            auto escape_length = gbnf_escape_length(sub_pattern, i);
503                            if (escape_length == 0) {
504                                throw unsupported_pattern("unsupported escape in character class: " + sub_pattern.substr(i, 2));
505                            }
506                            square_brackets += sub_pattern.substr(i, escape_length);
507                            i += escape_length;
508                        } else {
509                            square_brackets += sub_pattern[i];
510                            i++;
511                        }
512                    }
513                    if (i >= length) {
514                        throw invalid_pattern("unterminated character class");
515                    }
516                    square_brackets += ']';
517                    i++;
518                    seq.emplace_back(square_brackets, false);
519                } else if (c == '|') {
520                    seq.emplace_back("|", false);
521                    i++;
522                } else if (c == '*' || c == '+' || c == '?') {
523                    if (seq.empty()) {
524                        throw invalid_pattern("nothing to repeat");
525                    }
526                    seq.back() = std::make_pair(to_rule(seq.back()) + c, false);
527                    i++;
528                } else if (c == '{') {
529                    std::string curly_brackets = std::string(1, c);
530                    i++;
531                    while (i < length && sub_pattern[i] != '}') {
532                        curly_brackets += sub_pattern[i];
533                        i++;
534                    }
535                    if (i >= length) {
536                        throw unsupported_pattern("unterminated curly brackets");
537                    }
538                    curly_brackets += '}';
539                    i++;
540                    auto nums = string_split(curly_brackets.substr(1, curly_brackets.length() - 2), ",");
541                    int min_times = 0;
542                    int max_times = std::numeric_limits<int>::max();
543                    if (nums.size() != 1 && nums.size() != 2) {
544                        throw unsupported_pattern("wrong number of values in curly brackets");
545                    }
546                    try {
547                        if (nums.size() == 1) {
548                            min_times = max_times = std::stoi(nums[0]);
549                        } else {
550                            if (!nums[0].empty()) {
551                                min_times = std::stoi(nums[0]);
552                            }
553                            if (!nums[1].empty()) {
554                                max_times = std::stoi(nums[1]);
555                            }
556                        }
557                    } catch (const std::logic_error &) {
558                        throw unsupported_pattern("invalid number in curly brackets");
559                    }
560                    if (seq.empty()) {
561                        throw invalid_pattern("nothing to repeat");
562                    }
563                    auto &last = seq.back();
564                    auto &sub = last.first;
565                    auto sub_is_literal = last.second;
566
567                    if (!sub_is_literal) {
568                        std::string & sub_id = sub_rule_ids[sub];
569                        if (sub_id.empty()) {
570                            sub_id = _add_rule(name + "-" + std::to_string(sub_rule_ids.size()), sub);
571                        }
572                        sub = sub_id;
573                    }
574                    seq.back().first = build_repetition(
575                        sub_is_literal ? "\"" + sub + "\"" : sub,
576                        min_times,
577                        max_times,
578                        ""
579                    );
580                    seq.back().second = false;
581                } else {
582                    std::string literal;
583                    auto is_non_literal = [&](char c) {
584                        return NON_LITERAL_SET.find(c) != NON_LITERAL_SET.end();
585                    };
586                    while (i < length) {
587                        if (sub_pattern[i] == '\\') {
588                            if (i == length - 1) {
589                                throw invalid_pattern("trailing backslash");
590                            }
591                            char next = sub_pattern[i + 1];
592                            if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) {
593                                i++;
594                                literal += sub_pattern[i];
595                                i++;
596                            } else {
597                                auto escape_length = gbnf_escape_length(sub_pattern, i);
598                                if (escape_length == 0) {
599                                    throw unsupported_pattern("unsupported escape: " + sub_pattern.substr(i, 2));
600                                }
601                                literal += sub_pattern.substr(i, escape_length);
602                                i += escape_length;
603                            }
604                        } else if (sub_pattern[i] == '"') {
605                            literal += "\\\"";
606                            i++;
607                        } else if (!is_non_literal(sub_pattern[i]) &&
608                                (i == length - 1 || literal.empty() || sub_pattern[i + 1] == '.' || !is_non_literal(sub_pattern[i + 1]))) {
609                            literal += sub_pattern[i];
610                            i++;
611                        } else {
612                            break;
613                        }
614                    }
615                    if (literal.empty()) { // nothing was consumed, ex. a stray ']' or '}'
616                        throw unsupported_pattern(std::string("unsupported character: ") + c);
617                    }
618                    seq.emplace_back(literal, true);
619                }
620            }
621            return join_seq();
622        };
623
624        auto rule = to_rule(transform());
625        if (paren_depth != 0) {
626            throw invalid_pattern("unbalanced parentheses");
627        }
628
629        return _add_rule(name, "\"\\\"\" (" + rule + ") \"\\\"\"");
630    }
631
632    /*
633        Returns a rule that matches a JSON string that is none of the provided strings
634
635        not_strings({"a"})
636            -> ["] ( [a] char+ | [^"a] char* )? ["]
637        not_strings({"and", "also"})
638            -> ["] ( [a] ([l] ([s] ([o] char+ | [^"o] char*) | [^"s] char*) | [n] ([d] char+ | [^"d] char*) | [^"ln] char*) | [^"a] char* )? ["]
639    */
640    std::string _not_strings(const std::vector<std::string> & strings) {
641        common_trie trie(strings);
642
643        std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
644        std::ostringstream out;
645        out << "[\"] ( ";
646        std::function<void(size_t)> visit = [&](size_t idx) {
647            const auto & node = trie.nodes[idx];
648            std::string rejects;
649            auto first = true;
650            for (const auto & [cpt, child] : node.children) {
651                std::string c = common_unicode_cpt_to_utf8(cpt);
652                rejects += c;
653                if (first) {
654                    first = false;
655                } else {
656                    out << " | ";
657                }
658                out << "[" << c << "]";
659                if (!trie.nodes[child].children.empty()) {
660                    out << " (";
661                    visit(child);
662                    out << ")";
663                } else {
664                    out << " " << char_rule << "+";
665                }
666            }
667            if (!node.children.empty()) {
668                out << " | [^\"" << rejects << "] " << char_rule << "*";
669            }
670        };
671        visit(0);
672
673        out << " )";
674        if (trie.nodes[0].pattern < 0) {
675            out << "?";
676        }
677        out << " [\"]";
678        return out.str();
679    }
680
681    std::string _resolve_ref(const common_chat_schema_ref & schema) {
682        auto it = schema.ref.find('#');
683        std::string ref_fragment = it != std::string::npos ? schema.ref.substr(it + 1) : schema.ref;
684        static const std::regex nonalphanumeric_regex(R"([^a-zA-Z0-9-]+)");
685        std::string ref_name = "ref" + std::regex_replace(ref_fragment, nonalphanumeric_regex, "-");
686        if (_rules.find(ref_name) == _rules.end() && _refs_being_resolved.find(schema.ref) == _refs_being_resolved.end()) {
687            if (!schema.target) {
688                _errors.push_back("Unresolved $ref " + schema.ref);
689                return "";
690            }
691            _refs_being_resolved.insert(schema.ref);
692            ref_name = visit(*schema.target, ref_name);
693            _refs_being_resolved.erase(schema.ref);
694        }
695        return ref_name;
696    }
697
698    std::string _build_object_rule(
699        const std::vector<std::pair<std::string, const common_chat_schema *>> & properties,
700        const std::unordered_set<std::string> & required,
701        const std::string & name,
702        const common_chat_schema * additional_properties)
703    {
704        std::vector<std::string> required_props;
705        std::vector<std::string> optional_props;
706        std::unordered_map<std::string, std::string> prop_kv_rule_names;
707        std::vector<std::string> prop_names;
708        for (const auto & kv : properties) {
709            const auto &prop_name = kv.first;
710            const auto &prop_schema = kv.second;
711
712            std::string prop_rule_name = visit(*prop_schema, name + (name.empty() ? "" : "-") + prop_name);
713            prop_kv_rule_names[prop_name] = _add_rule(
714                name + (name.empty() ? "" : "-") + prop_name + "-kv",
715                format_literal(json(prop_name).dump()) + " space \":\" space " + prop_rule_name
716            );
717            if (required.find(prop_name) != required.end()) {
718                required_props.push_back(prop_name);
719            } else {
720                optional_props.push_back(prop_name);
721            }
722            prop_names.push_back(prop_name);
723        }
724        if (additional_properties) {
725            std::string sub_name = name + (name.empty() ? "" : "-") + "additional";
726            std::string value_rule =
727                additional_properties->kind() != common_chat_schema::KIND_ANY ? visit(*additional_properties, sub_name + "-value")
728                : _add_primitive("value", PRIMITIVE_RULES.at("value"));
729
730            auto key_rule =
731                prop_names.empty() ? _add_primitive("string", PRIMITIVE_RULES.at("string"))
732                : _add_rule(sub_name + "-k", _not_strings(prop_names));
733            std::string kv_rule = _add_rule(sub_name + "-kv", key_rule + " \":\" space " + value_rule);
734            prop_kv_rule_names["*"] = kv_rule;
735            optional_props.push_back("*");
736        }
737
738        if (required_props.empty() && optional_props.empty()) {
739            return "\"{\" space \"}\"";
740        }
741
742        std::string rule = "\"{\" space ";
743        for (size_t i = 0; i < required_props.size(); i++) {
744            if (i > 0) {
745                rule += " \",\" space ";
746            }
747            rule += prop_kv_rule_names[required_props[i]];
748        }
749
750        if (!optional_props.empty()) {
751            rule += " (";
752            if (!required_props.empty()) {
753                rule += " \",\" space ( ";
754            }
755
756            std::function<std::string(const std::vector<std::string> &, bool)> get_recursive_refs = [&](const std::vector<std::string> & ks, bool first_is_optional) {
757                std::string res;
758                if (ks.empty()) {
759                    return res;
760                }
761                const std::string& k = ks[0];
762                std::string kv_rule_name = prop_kv_rule_names[k];
763                std::string comma_ref = "( \",\" space " + kv_rule_name + " )";
764                if (first_is_optional) {
765                    res = comma_ref + (k == "*" ? "*" : "?");
766                } else {
767                    res = kv_rule_name + (k == "*" ? " " + comma_ref + "*" : "");
768                }
769                if (ks.size() > 1) {
770                    res += " " + _add_rule(
771                        name + (name.empty() ? "" : "-") + k + "-rest",
772                        get_recursive_refs(std::vector<std::string>(ks.begin() + 1, ks.end()), true)
773                    );
774                }
775                return res;
776            };
777
778            for (size_t i = 0; i < optional_props.size(); i++) {
779                if (i > 0) {
780                    rule += " | ";
781                }
782                rule += get_recursive_refs(std::vector<std::string>(optional_props.begin() + i, optional_props.end()), false);
783            }
784            if (!required_props.empty()) {
785                rule += " )";
786            }
787            rule += " )?";
788        }
789
790        rule += " space \"}\"";
791
792        return rule;
793    }
794
795    std::string _add_primitive(const std::string & name, const BuiltinRule & rule) {
796        auto n = _add_rule(name, rule.content);
797        for (const auto & dep : rule.deps) {
798            BuiltinRule dep_rule;
799            auto it = PRIMITIVE_RULES.find(dep);
800            if (it == PRIMITIVE_RULES.end()) {
801                it = STRING_FORMAT_RULES.find(dep);
802                if (it == STRING_FORMAT_RULES.end()) {
803                    _errors.push_back("Rule " + dep + " not known");
804                    continue;
805                }
806            }
807            if (_rules.find(dep) == _rules.end()) {
808                _add_primitive(dep, it->second);
809            }
810        }
811        return n;
812    }
813
814public:
815    explicit common_chat_schema_converter(bool dotall) : _dotall(dotall) {
816        _rules["space"] = SPACE_RULE;
817    }
818
819    std::string add_schema(const std::string & name, const common_chat_schema & schema) {
820        return visit(schema, name);
821    }
822
823    static std::string _generate_constant_rule(const json & value) {
824        return format_literal(value.dump());
825    }
826
827    std::string _visit_primitive(const std::string & rule_name, const std::string & type) {
828        return _add_primitive(rule_name == "root" ? "root" : type, PRIMITIVE_RULES.at(type));
829    }
830
831    std::string _visit_all_of(const common_chat_schema_all_of & schema, const std::string & name, const std::string & rule_name) {
832        std::unordered_set<std::string> required;
833        std::vector<std::pair<std::string, const common_chat_schema *>> properties;
834        std::map<std::string, size_t> enum_values;
835        std::function<void(const common_chat_schema &, bool)> add_component = [&](const common_chat_schema & comp, bool is_required) {
836            if (comp.kind() == common_chat_schema::KIND_REF) {
837                if (const auto * target = as<common_chat_schema_ref>(comp).target) {
838                    add_component(*target, is_required);
839                }
840            } else if (comp.kind() == common_chat_schema::KIND_OBJECT) {
841                for (const auto & prop : as<common_chat_schema_object>(comp).properties) {
842                    properties.emplace_back(prop.name, prop.schema.get());
843                    if (is_required) {
844                        required.insert(prop.name);
845                    }
846                }
847            } else if (comp.kind() == common_chat_schema::KIND_ENUM) {
848                for (const auto & v : as<common_chat_schema_enum>(comp).values) {
849                    enum_values[_generate_constant_rule(v)] += 1;
850                }
851            }
852        };
853        for (const auto & child : schema.children) {
854            if (child->kind() == common_chat_schema::KIND_ANY_OF) {
855                for (const auto & alt : as<common_chat_schema_any_of>(*child).children) {
856                    add_component(*alt, false);
857                }
858            } else {
859                add_component(*child, true);
860            }
861        }
862        if (!enum_values.empty()) {
863            std::vector<std::string> enum_intersection;
864            for (const auto & p : enum_values) {
865                if (p.second == schema.children.size()) {
866                    enum_intersection.push_back(p.first);
867                }
868            }
869            if (!enum_intersection.empty()) {
870                return _add_rule(rule_name, "(" + string_join(enum_intersection, " | ") + ")");
871            }
872        }
873        return _add_rule(rule_name, _build_object_rule(properties, required, name, nullptr));
874    }
875
876    std::string visit(const common_chat_schema & schema, const std::string & name) {
877        std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
878        std::string sub_name  = name + (name.empty() ? "" : "-");
879
880        switch (schema.kind()) {
881            case common_chat_schema::KIND_REF:
882                return _add_rule(rule_name, _resolve_ref(as<common_chat_schema_ref>(schema)));
883            case common_chat_schema::KIND_ANY_OF:
884                return _add_rule(rule_name, _generate_union_rule(name, as<common_chat_schema_any_of>(schema).children));
885            case common_chat_schema::KIND_ALL_OF:
886                return _visit_all_of(as<common_chat_schema_all_of>(schema), name, rule_name);
887            case common_chat_schema::KIND_CONST:
888                return _add_rule(rule_name, _generate_constant_rule(as<common_chat_schema_const>(schema).value));
889            case common_chat_schema::KIND_ENUM: {
890                std::vector<std::string> enum_values;
891                for (const auto & v : as<common_chat_schema_enum>(schema).values) {
892                    enum_values.push_back(_generate_constant_rule(v));
893                }
894                return _add_rule(rule_name, "(" + string_join(enum_values, " | ") + ")");
895            }
896            case common_chat_schema::KIND_OBJECT: {
897                const auto & obj = as<common_chat_schema_object>(schema);
898                if (obj.properties.empty() && obj.additional_properties && obj.additional_properties->kind() == common_chat_schema::KIND_ANY) {
899                    return _add_rule(rule_name, _add_primitive("object", PRIMITIVE_RULES.at("object")));
900                }
901                std::vector<std::pair<std::string, const common_chat_schema *>> properties;
902                std::unordered_set<std::string> required;
903                for (const auto & prop : obj.properties) {
904                    properties.emplace_back(prop.name, prop.schema.get());
905                    if (prop.required) {
906                        required.insert(prop.name);
907                    }
908                }
909                return _add_rule(rule_name, _build_object_rule(properties, required, name, obj.additional_properties.get()));
910            }
911            case common_chat_schema::KIND_TUPLE: {
912                const auto & items = as<common_chat_schema_tuple>(schema).items;
913                std::string rule = "\"[\" space ";
914                for (size_t i = 0; i < items.size(); i++) {
915                    if (i > 0) {
916                        rule += " \",\" space ";
917                    }
918                    rule += visit(*items[i], sub_name + "tuple-" + std::to_string(i));
919                }
920                rule += " space \"]\"";
921                return _add_rule(rule_name, rule);
922            }
923            case common_chat_schema::KIND_ARRAY: {
924                const auto & arr = as<common_chat_schema_array>(schema);
925                if (arr.items->kind() == common_chat_schema::KIND_ANY && arr.min_items == 0 && arr.max_items < 0) {
926                    return _visit_primitive(rule_name, "array");
927                }
928                std::string item_rule_name = visit(*arr.items, sub_name + "item");
929                int max_items = arr.max_items < 0 ? std::numeric_limits<int>::max() : arr.max_items;
930                return _add_rule(rule_name, "\"[\" space " + build_repetition(item_rule_name, arr.min_items, max_items, "\",\" space") + " space \"]\"");
931            }
932            case common_chat_schema::KIND_STRING: {
933                const auto & str = as<common_chat_schema_string>(schema);
934                if (!str.pattern.empty()) {
935                    return _visit_pattern(str.pattern, rule_name);
936                }
937                if (str.format == common_chat_schema::FORMAT_UUID) {
938                    return _visit_primitive(rule_name, "uuid");
939                }
940                if (str.format != common_chat_schema::FORMAT_NONE) {
941                    std::string prim_name = std::string(str.format == common_chat_schema::FORMAT_DATE ? "date" : str.format == common_chat_schema::FORMAT_TIME ? "time" : "date-time") + "-string";
942                    return _add_rule(rule_name, _add_primitive(prim_name, STRING_FORMAT_RULES.at(prim_name)));
943                }
944                if (str.min_length > 0 || str.max_length >= 0) {
945                    std::string char_rule = _add_primitive("char", PRIMITIVE_RULES.at("char"));
946                    int max_len = str.max_length < 0 ? std::numeric_limits<int>::max() : str.max_length;
947                    return _add_rule(rule_name, "\"\\\"\" " + build_repetition(char_rule, str.min_length, max_len) + " \"\\\"\"");
948                }
949                return _visit_primitive(rule_name, "string");
950            }
951            case common_chat_schema::KIND_INTEGER: {
952                const auto & i = as<common_chat_schema_integer>(schema);
953                if (i.minimum == std::numeric_limits<int64_t>::min() && i.maximum == std::numeric_limits<int64_t>::max()) {
954                    return _visit_primitive(rule_name, "integer");
955                }
956                std::stringstream out;
957                out << "(";
958                build_min_max_int(i.minimum, i.maximum, out);
959                out << ")";
960                return _add_rule(rule_name, out.str());
961            }
962            case common_chat_schema::KIND_NUMBER:
963                return _visit_primitive(rule_name, "number");
964            case common_chat_schema::KIND_BOOLEAN:
965                return _visit_primitive(rule_name, "boolean");
966            case common_chat_schema::KIND_NULL:
967                return _visit_primitive(rule_name, "null");
968            case common_chat_schema::KIND_ANY:
969                return _add_rule(rule_name, _add_primitive("value", PRIMITIVE_RULES.at("value")));
970        }
971        return "";
972    }
973
974    void check_errors() {
975        if (!_errors.empty()) {
976            throw std::invalid_argument("JSON schema conversion failed:\n" + string_join(_errors, "\n"));
977        }
978        if (!_warnings.empty()) {
979            fprintf(stderr, "WARNING: JSON schema conversion was incomplete: %s\n", string_join(_warnings, "; ").c_str());
980        }
981    }
982
983    std::string format_grammar() {
984        std::stringstream ss;
985        for (const auto & kv : _rules) {
986            ss << kv.first << " ::= " << kv.second << '\n';
987        }
988        return ss.str();
989    }
990};
991
992std::string json_schema_to_grammar(const common_json & schema, bool force_gbnf) {
993#ifdef LLAMA_USE_LLGUIDANCE
994    if (!force_gbnf) {
995        return "%llguidance {}\nstart: %json " + schema.dump();
996    }
997#else
998    (void)force_gbnf;
999#endif // LLAMA_USE_LLGUIDANCE
1000    try {
1001        return json_schema_to_grammar(common_chat_schema_from_json(schema));
1002    } catch (const std::runtime_error & e) {
1003        throw std::invalid_argument(std::string("JSON schema conversion failed:\n") + e.what());
1004    }
1005}
1006
1007std::string json_schema_to_grammar(const common_chat_schema_document & schema) {
1008    common_chat_schema_converter converter(false);
1009    converter.visit(*schema.root, "");
1010    converter.check_errors();
1011    return converter.format_grammar();
1012}
1013
1014std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options) {
1015    common_chat_schema_converter converter(options.dotall);
1016    common_grammar_builder builder {
1017        /* .add_rule = */ [&](const std::string & name, const std::string & rule) {
1018            return converter._add_rule(name, rule);
1019        },
1020        /* .add_schema = */ [&](const std::string & name, const common_chat_schema & schema) {
1021            return converter.add_schema(name == "root" ? "" : name, schema);
1022        },
1023    };
1024    cb(builder);
1025    converter.check_errors();
1026    return converter.format_grammar();
1027}