File tree Expand file tree Collapse file tree 2 files changed +30
-5
lines changed Expand file tree Collapse file tree 2 files changed +30
-5
lines changed Original file line number Diff line number Diff line change @@ -991,10 +991,27 @@ class SchemaConverter {
991991};
992992
993993std::string json_schema_to_grammar (const json & schema) {
994- SchemaConverter converter ([](const std::string &) { return json::object (); }, /* dotall= */ false );
995- auto copy = schema;
996- converter.resolve_refs (copy, " input" );
997- converter.visit (copy, " " );
994+ return build_grammar ([&](const llama_grammar_builder & callbacks) {
995+ auto copy = schema;
996+ callbacks.resolve_refs (copy);
997+ callbacks.add_schema (" " , copy);
998+ });
999+ }
1000+
1001+ std::string build_grammar (const std::function<void (const llama_grammar_builder &)> & cb) {
1002+ SchemaConverter converter ([&](const std::string &) { return json (); }, /* dotall= */ false );
1003+ llama_grammar_builder builder {
1004+ /* .add_rule = */ [&](const std::string & name, const std::string & rule) {
1005+ return converter._add_rule (name, rule);
1006+ },
1007+ /* .add_schema = */ [&](const std::string & name, const nlohmann::ordered_json & schema) {
1008+ return converter.visit (schema, name == " root" ? " " : name);
1009+ },
1010+ /* .resolve_refs = */ [&](nlohmann::ordered_json & schema) {
1011+ converter.resolve_refs (schema, " " );
1012+ }
1013+ };
1014+ cb (builder);
9981015 converter.check_errors ();
9991016 return converter.format_grammar ();
10001017}
Original file line number Diff line number Diff line change 55#define JSON_ASSERT GGML_ASSERT
66#include " json.hpp"
77
8- std::string json_schema_to_grammar (const nlohmann::ordered_json& schema);
8+ std::string json_schema_to_grammar (const nlohmann::ordered_json & schema);
9+
10+ struct llama_grammar_builder {
11+ std::function<std::string(const std::string &, const std::string &)> add_rule;
12+ std::function<std::string(const std::string &, const nlohmann::ordered_json &)> add_schema;
13+ std::function<void (nlohmann::ordered_json &)> resolve_refs;
14+ };
15+
16+ std::string build_grammar (const std::function<void (const llama_grammar_builder &)> & cb);
You can’t perform that action at this time.
0 commit comments