test-chat-parser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. // Tests chat handling, including grammar generation and parsing for tool calling, for various templates.
  2. //
  3. // Also acts as a CLI to generate a Markdown summary of the formats of Jinja templates,
  4. // e.g. given Minja (http://github.com/google/minja) checked out in parent dir:
  5. //
  6. // cmake -B build && cmake --build build --parallel && ./build/bin/test-chat ../minja/build/tests/*.jinja 2>/dev/null
  7. //
  8. #include <exception>
  9. #include <iostream>
  10. #include <string>
  11. #include "chat-parser.h"
  12. #include "common.h"
  13. #include "log.h"
  14. #include "regex-partial.h"
  15. template <class T>
  16. static void assert_equals(const T & expected, const T & actual) {
  17. if (expected != actual) {
  18. std::cerr << "Expected: " << expected << std::endl;
  19. std::cerr << "Actual: " << actual << std::endl;
  20. std::cerr << std::flush;
  21. throw std::runtime_error("Test failed");
  22. }
  23. }
  24. static void assert_equals(const char * expected, const std::string & actual) {
  25. return assert_equals<std::string>(expected, actual);
  26. }
  27. static void assert_throws(const std::function<void()> & fn, const std::string & expected_exception_pattern = "") {
  28. try {
  29. fn();
  30. } catch (const std::exception & e) {
  31. if (expected_exception_pattern.empty()) {
  32. return;
  33. }
  34. std::regex expected_exception_regex(expected_exception_pattern);
  35. std::string actual_message = e.what();
  36. if (std::regex_search(actual_message, expected_exception_regex)) {
  37. return;
  38. }
  39. throw std::runtime_error("Exception doesn't match expected pattern: " + actual_message + " (pattern: " + expected_exception_pattern + ")");
  40. throw std::runtime_error("Exception of unexpected type: " + std::string(e.what()));
  41. }
  42. throw std::runtime_error("Exception was expected but not thrown");
  43. }
  44. static void test_reasoning() {
  45. {
  46. common_chat_msg_parser builder("<tnk>Cogito</tnk>Ergo sum", /* is_partial= */ false, {
  47. /* .format = */ COMMON_CHAT_FORMAT_CONTENT_ONLY,
  48. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  49. /* .reasoning_in_content = */ false,
  50. /* .thinking_forced_open = */ false,
  51. });
  52. assert_equals(false, builder.try_parse_reasoning("<tnk>", "</tnk>"));
  53. assert_equals("<tnk>Cogito</tnk>Ergo sum", builder.consume_rest());
  54. }
  55. {
  56. common_chat_msg_parser builder("<tnk>Cogito</tnk>Ergo sum", /* is_partial= */ false, {
  57. /* .format = */ COMMON_CHAT_FORMAT_CONTENT_ONLY,
  58. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  59. /* .reasoning_in_content = */ false,
  60. /* .thinking_forced_open = */ false,
  61. });
  62. assert_equals(true, builder.try_parse_reasoning("<tnk>", "</tnk>"));
  63. assert_equals(std::string("Cogito"), builder.result().reasoning_content);
  64. assert_equals("Ergo sum", builder.consume_rest());
  65. }
  66. {
  67. common_chat_msg_parser builder("Cogito</tnk>Ergo sum", /* is_partial= */ false, {
  68. /* .format = */ COMMON_CHAT_FORMAT_CONTENT_ONLY,
  69. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  70. /* .reasoning_in_content = */ false,
  71. /* .thinking_forced_open = */ false,
  72. });
  73. assert_equals(false, builder.try_parse_reasoning("<tnk>", "</tnk>"));
  74. assert_equals("Cogito</tnk>Ergo sum", builder.consume_rest());
  75. }
  76. {
  77. common_chat_msg_parser builder("Cogito</tnk>Ergo sum", /* is_partial= */ false, {
  78. /* .format = */ COMMON_CHAT_FORMAT_CONTENT_ONLY,
  79. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  80. /* .reasoning_in_content = */ false,
  81. /* .thinking_forced_open = */ true,
  82. });
  83. assert_equals(true, builder.try_parse_reasoning("<tnk>", "</tnk>"));
  84. assert_equals(std::string("Cogito"), builder.result().reasoning_content);
  85. assert_equals("Ergo sum", builder.consume_rest());
  86. }
  87. {
  88. common_chat_msg_parser builder("Cogito</tnk>Ergo sum", /* is_partial= */ false, {
  89. /* .format = */ COMMON_CHAT_FORMAT_CONTENT_ONLY,
  90. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  91. /* .reasoning_in_content = */ true,
  92. /* .thinking_forced_open = */ true,
  93. });
  94. assert_equals(true, builder.try_parse_reasoning("<tnk>", "</tnk>"));
  95. assert_equals("<think>Cogito</think>", builder.result().content);
  96. assert_equals("Ergo sum", builder.consume_rest());
  97. }
  98. }
  99. static void test_regex() {
  100. auto test_throws = [](const std::string & input, const std::string & regex, const std::string & expected_exception_pattern = "") {
  101. common_chat_msg_parser builder(input, /* is_partial= */ false, {});
  102. assert_throws([&]() { builder.consume_regex(common_regex(regex)); }, expected_exception_pattern);
  103. };
  104. test_throws("Hello, world!", "abc", "^abc$");
  105. test_throws("Hello, world!", "e", "^e$");
  106. {
  107. common_chat_msg_parser builder("Hello, world!", /* is_partial= */ false, {});
  108. builder.consume_regex(common_regex("Hello"));
  109. assert_equals(", world!", builder.consume_rest());
  110. }
  111. {
  112. // When in non partial mode, we can say whether the regex was consumed or not.
  113. common_chat_msg_parser builder("Hello,", /* is_partial= */ false, {});
  114. assert_equals(false, builder.try_consume_regex(common_regex("Hello, world!")).has_value());
  115. }
  116. {
  117. common_chat_msg_parser builder("Hello,", /* is_partial= */ false, {});
  118. auto res = builder.try_consume_regex(common_regex("H(el)l(?:o, world!)?"));
  119. assert_equals(true, res.has_value());
  120. // Verify captures
  121. assert_equals<size_t>(2, res->groups.size());
  122. assert_equals("Hell", builder.str(res->groups[0]));
  123. assert_equals("el", builder.str(res->groups[1]));
  124. // Verify position is after the match
  125. assert_equals<size_t>(4, builder.pos());
  126. assert_equals("o,", builder.consume_rest());
  127. }
  128. {
  129. // But in partial mode, we have a partial final match / can't decide, so we throw a partial exception.
  130. common_chat_msg_parser builder("Hello,", /* is_partial= */ true, {});
  131. assert_throws([&]() {
  132. builder.try_consume_regex(common_regex("Hello, world!"));
  133. }, "^Hello, world!$");
  134. }
  135. // Now regardless of the mode, we can tell these aren't a match.
  136. for (const auto is_partial : {false, true}) {
  137. common_chat_msg_parser builder("Hello,", is_partial, {});
  138. assert_equals(false, builder.try_consume_regex(common_regex("a(b|c)(d|e)f")).has_value());
  139. }
  140. for (const auto is_partial : {false, true}) {
  141. common_chat_msg_parser builder("Hello,", is_partial, {});
  142. assert_equals(false, builder.try_consume_literal("Oh"));
  143. }
  144. }
  145. const std::vector<std::string> barely_healable_jsons = {
  146. "{",
  147. "{\"",
  148. "{\"\\",
  149. "{\"n",
  150. "{\"name\"",
  151. "{\"name\":",
  152. "{\"name\":\"",
  153. "{\"name\":\"\\",
  154. "{\"name\":\"python",
  155. "{\"name\":\"python\\",
  156. "{\",",
  157. "{\":",
  158. "{\"[",
  159. "{\"]",
  160. "{\"{",
  161. "{\"}",
  162. "{\"1",
  163. "{\"name\":\",",
  164. "{\"name\":\":",
  165. "{\"name\":\"[",
  166. "{\"name\":\"]",
  167. "{\"name\":\"{",
  168. "{\"name\":\"}",
  169. "{\"name\":\"1",
  170. };
  171. static void test(const std::string & input, bool is_partial, const std::vector<std::vector<std::string>> & args_paths, const std::vector<std::vector<std::string>> & content_paths, const std::string & expected) {
  172. common_chat_msg_parser builder(input, is_partial, {});
  173. auto js = builder.try_consume_json_with_dumped_args(args_paths, content_paths);
  174. assert_equals(true, js.has_value());
  175. assert_equals(is_partial, js->is_partial);
  176. assert_equals(expected, args_paths.size() == 1 && args_paths[0].empty() ? js->value.get<std::string>() : js->value.dump());
  177. }
  178. static void test_with_args(const std::string & input, const std::string & expected, bool parse_as_partial = true, bool is_partial = true) {
  179. common_chat_msg_parser builder(input, parse_as_partial, {});
  180. auto js = builder.try_consume_json_with_dumped_args({{"args"}}, {});
  181. assert_equals(true, js.has_value());
  182. assert_equals(is_partial, js->is_partial);
  183. assert_equals(expected, js->value.dump());
  184. }
  185. static void test_json_with_dumped_args_no_args() {
  186. // Normal JSON, nothing to heal, nothing to dump
  187. test("{\"name\": \"python\"}", false, {}, {}, "{\"name\":\"python\"}");
  188. // Full json is args
  189. test("{\"name\": \"python\"}", false, {{}}, {}, "{\"name\":\"python\"}");
  190. // If the arguments are further down, don't heal partial content.
  191. for (const auto & src : barely_healable_jsons) {
  192. test(src, true, {{"arguments"}}, {}, "{}");
  193. }
  194. // But heal content that isn't partial.
  195. test("{\"name\": \"python\"", true, {{"arguments"}}, {}, "{\"name\":\"python\"}");
  196. }
  197. static void test_json_with_dumped_args() {
  198. // Partial content.
  199. test("{\"content\": \"t", true, {}, {{"content"}}, "{\"content\":\"t\"}");
  200. test("{\"content\": \"", true, {}, {{"content"}}, "{\"content\":\"\"}");
  201. test("{\"content\": ", true, {}, {{"content"}}, "{}");
  202. // If the entire JSON is the arguments, healing it them dumping it produces the same output as the input (just reformatted).
  203. test("{\"name\": \"python", true, {{}}, {}, "{\"name\":\"python");
  204. for (const auto & src : barely_healable_jsons) {
  205. test(src, true, {{}}, {}, src);
  206. }
  207. // Full JSON w/ args
  208. for (auto parse_as_partial : {true, false}) {
  209. test_with_args(
  210. R"({"name": "python", "args": {"arg1": 1}})",
  211. R"({"name":"python","args":"{\"arg1\":1}"})",
  212. parse_as_partial,
  213. /* is_partial= */ false
  214. );
  215. }
  216. // Partial JSON w/ partial args
  217. test_with_args(
  218. R"({"foo": "bar", "args": {")",
  219. R"({"foo":"bar","args":"{\""})"
  220. );
  221. // Partial args broken in object key
  222. test_with_args(
  223. R"({"foo": "bar", "args": {"ar)",
  224. R"({"foo":"bar","args":"{\"ar"})"
  225. );
  226. // Partial args broken after object key
  227. test_with_args(
  228. R"({"foo": "bar", "args": {"arg1")",
  229. R"({"foo":"bar","args":"{\"arg1\""})"
  230. );
  231. // Partial args broken before object value
  232. test_with_args(
  233. R"({"foo": "bar", "args": {"arg1":)",
  234. R"({"foo":"bar","args":"{\"arg1\":"})"
  235. );
  236. // Partial args broken before object value (space)
  237. test_with_args(
  238. R"({"foo": "bar", "args": {"arg1": )",
  239. R"({"foo":"bar","args":"{\"arg1\":"})"
  240. );
  241. // Partial args broken in object value that may not be complete (int)
  242. test_with_args(
  243. R"({"foo": "bar", "args": {"arg1": 1)",
  244. R"({"foo":"bar","args":"{\"arg1\":"})"
  245. );
  246. // Partial args broken in object value that is complete (int)
  247. test_with_args(
  248. R"({"foo": "bar", "args": {"arg1": 1 )",
  249. R"({"foo":"bar","args":"{\"arg1\":1"})"
  250. );
  251. // Partial args broken in object value that is incomplete (string)
  252. test_with_args(
  253. R"({"foo": "bar", "args": {"arg1": ")",
  254. R"({"foo":"bar","args":"{\"arg1\":\""})"
  255. );
  256. // Partial args broken in object value that is complete (string)
  257. test_with_args(
  258. R"({"foo": "bar", "args": {"arg1": "1")",
  259. R"({"foo":"bar","args":"{\"arg1\":\"1\""})"
  260. );
  261. // Partial args broken on array opening
  262. test_with_args(
  263. R"({"foo": "bar", "args": [)",
  264. R"({"foo":"bar","args":"["})"
  265. );
  266. // Partial args broken on array value that is incomplete (int)
  267. test_with_args(
  268. R"({"foo": "bar", "args": [1)",
  269. R"({"foo":"bar","args":"["})"
  270. );
  271. // Partial args broken on array value that is complete (int)
  272. test_with_args(
  273. R"({"foo": "bar", "args": [1 )",
  274. R"({"foo":"bar","args":"[1"})"
  275. );
  276. // Partial args broken on array value that is complete (string)
  277. test_with_args(
  278. R"({"foo": "bar", "args": ["1")",
  279. R"({"foo":"bar","args":"[\"1\""})"
  280. );
  281. // Partial args broken after array value
  282. test_with_args(
  283. R"({"foo": "bar", "args": [1,)",
  284. R"({"foo":"bar","args":"[1,"})"
  285. );
  286. // Partial args broken on nested array
  287. test_with_args(
  288. R"({"foo": "bar", "args": {"arg1": [)",
  289. R"({"foo":"bar","args":"{\"arg1\":["})"
  290. );
  291. }
  292. static void test_positions() {
  293. {
  294. common_chat_msg_parser builder("Hello, world!", /* is_partial= */ false, {});
  295. assert_equals<size_t>(0, builder.pos());
  296. assert_throws([&]() { builder.move_to(100); });
  297. assert_equals<size_t>(0, builder.pos());
  298. assert_throws([&]() { builder.move_back(1); });
  299. assert_equals<size_t>(0, builder.pos());
  300. builder.move_to(8);
  301. assert_equals<size_t>(8, builder.pos());
  302. builder.move_back(1);
  303. assert_equals<size_t>(7, builder.pos());
  304. assert_equals("world!", builder.consume_rest());
  305. builder.move_to(0);
  306. assert_equals<size_t>(0, builder.pos());
  307. assert_throws([&]() { builder.finish(); });
  308. assert_equals<size_t>(0, builder.pos());
  309. builder.move_to(builder.input().size());
  310. builder.finish();
  311. }
  312. {
  313. common_chat_msg_parser builder("Hello, world!", /* is_partial= */ true, {});
  314. builder.move_to(builder.input().size());
  315. assert_equals<size_t>(builder.input().size(), builder.pos());
  316. builder.finish();
  317. }
  318. }
  319. int main() {
  320. test_positions();
  321. test_json_with_dumped_args_no_args();
  322. test_json_with_dumped_args();
  323. test_reasoning();
  324. test_regex();
  325. std::cout << "All tests passed!\n";
  326. return 0;
  327. }