| 52 | } |
| 53 | |
| 54 | int main(int argc, char** argv) { |
| 55 | if (argc != 3) { |
| 56 | fprintf(stdout, "Usage: %s <grammar_filename> <input_filename>\n", argv[0]); |
| 57 | return 1; |
| 58 | } |
| 59 | |
| 60 | const std::string grammar_filename = argv[1]; |
| 61 | const std::string input_filename = argv[2]; |
| 62 | |
| 63 | // Read the GBNF grammar file |
| 64 | FILE* grammar_file = fopen(grammar_filename.c_str(), "r"); |
| 65 | if (!grammar_file) { |
| 66 | fprintf(stdout, "Failed to open grammar file: %s\n", grammar_filename.c_str()); |
| 67 | return 1; |
| 68 | } |
| 69 | |
| 70 | std::string grammar_str; |
| 71 | { |
| 72 | std::ifstream grammar_file(grammar_filename); |
| 73 | GGML_ASSERT(grammar_file.is_open() && "Failed to open grammar file"); |
| 74 | std::stringstream buffer; |
| 75 | buffer << grammar_file.rdbuf(); |
| 76 | grammar_str = buffer.str(); |
| 77 | } |
| 78 | |
| 79 | llama_grammar * grammar = llama_grammar_init_impl(nullptr, grammar_str.c_str(), "root", false, nullptr, 0, nullptr, 0); |
| 80 | if (grammar == nullptr) { |
| 81 | fprintf(stdout, "Failed to initialize llama_grammar\n"); |
| 82 | return 1; |
| 83 | } |
| 84 | // Read the input file |
| 85 | std::string input_str; |
| 86 | { |
| 87 | std::ifstream input_file(input_filename); |
| 88 | GGML_ASSERT(input_file.is_open() && "Failed to open input file"); |
| 89 | std::stringstream buffer; |
| 90 | buffer << input_file.rdbuf(); |
| 91 | input_str = buffer.str(); |
| 92 | } |
| 93 | |
| 94 | // Validate the input string against the grammar |
| 95 | size_t error_pos; |
| 96 | std::string error_msg; |
| 97 | bool is_valid = llama_grammar_validate(grammar, input_str, error_pos, error_msg); |
| 98 | |
| 99 | if (is_valid) { |
| 100 | fprintf(stdout, "Input string is valid according to the grammar.\n"); |
| 101 | } else { |
| 102 | print_error_message(input_str, error_pos, error_msg); |
| 103 | } |
| 104 | |
| 105 | // Clean up |
| 106 | llama_grammar_free_impl(grammar); |
| 107 | |
| 108 | return 0; |
| 109 | } |
nothing calls this directly
no test coverage detected