json-schema-to-grammar.h 1.4 KB
Newer Older
Michael Yang's avatar
Michael Yang committed
1
2
#pragma once

3
4
5
#include <nlohmann/json_fwd.hpp>

#include <functional>
6
#include <memory>
7
#include <string>
Michael Yang's avatar
Michael Yang committed
8

9
10
11
std::string json_schema_to_grammar(const nlohmann::ordered_json & schema,
                                   bool force_gbnf = false);

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class common_schema_converter;

// Probes a JSON schema to extract information about its structure and type constraints.
class common_schema_info {
    std::unique_ptr<common_schema_converter> impl_;

  public:
    common_schema_info();
    ~common_schema_info();

    common_schema_info(const common_schema_info &) = delete;
    common_schema_info & operator=(const common_schema_info &) = delete;
    common_schema_info(common_schema_info &&) noexcept;
    common_schema_info & operator=(common_schema_info &&) noexcept;

    void resolve_refs(nlohmann::ordered_json & schema);
    bool resolves_to_string(const nlohmann::ordered_json & schema);
};

31
32
33
34
35
36
37
38
39
40
struct common_grammar_builder {
    std::function<std::string(const std::string &, const std::string &)> add_rule;
    std::function<std::string(const std::string &, const nlohmann::ordered_json &)> add_schema;
    std::function<void(nlohmann::ordered_json &)> resolve_refs;
};

struct common_grammar_options {
    bool dotall = false;
};

Daniel Hiltgen's avatar
Daniel Hiltgen committed
41
42
std::string gbnf_format_literal(const std::string & literal);

43
std::string build_grammar(const std::function<void(const common_grammar_builder &)> & cb, const common_grammar_options & options = {});