| 182 | } |
| 183 | |
| 184 | static std::pair<uint32_t, const char *> parse_token(const llama_vocab * vocab, const char * src) { |
| 185 | const char * pos = src; |
| 186 | if (*pos != '<') { |
| 187 | throw std::runtime_error(std::string("expecting '<' at ") + pos); |
| 188 | } |
| 189 | pos++; |
| 190 | |
| 191 | // Parse <[id]> |
| 192 | if (*pos == '[') { |
| 193 | pos++; |
| 194 | const char * int_end = parse_int(pos); |
| 195 | uint32_t token_id = std::stoul(std::string(pos, int_end - pos)); |
| 196 | pos = int_end; |
| 197 | if (*pos != ']') { |
| 198 | throw std::runtime_error(std::string("expecting ']' at ") + pos); |
| 199 | } |
| 200 | pos++; |
| 201 | if (*pos != '>') { |
| 202 | throw std::runtime_error(std::string("expecting '>' at ") + pos); |
| 203 | } |
| 204 | pos++; |
| 205 | return std::make_pair(token_id, pos); |
| 206 | } |
| 207 | |
| 208 | if (vocab == nullptr) { |
| 209 | throw std::runtime_error(std::string("no vocab to parse token at ") + src); |
| 210 | } |
| 211 | |
| 212 | // Parse <token> and tokenize to obtain the token id |
| 213 | while (*pos != 0 && *pos != '>') { |
| 214 | pos++; |
| 215 | } |
| 216 | if (*pos != '>') { |
| 217 | throw std::runtime_error(std::string("expecting '>' at ") + pos); |
| 218 | } |
| 219 | pos++; |
| 220 | |
| 221 | llama_token tokens[2]; |
| 222 | int32_t n_tokens = vocab->tokenize(src, static_cast<int32_t>(pos - src), tokens, 2, false, true); |
| 223 | if (n_tokens != 1) { |
| 224 | // must tokenize to exactly 1 token |
| 225 | throw std::runtime_error("invalid token '" + std::string(src, pos - src) + "'"); |
| 226 | } |
| 227 | return std::make_pair(tokens[0], pos); |
| 228 | } |
| 229 | |
| 230 | static void print_grammar_char(FILE * file, uint32_t c) { |
| 231 | if (0x20 <= c && c <= 0x7f) { |
no test coverage detected