test-chat.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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 <fstream>
  9. #include <iostream>
  10. #include <json.hpp>
  11. #include <string>
  12. #include "chat.h"
  13. #include "llama-grammar.h"
  14. #include "unicode.h"
  15. using json = nlohmann::ordered_json;
  16. template <class T> 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 std::string read_file(const std::string & path) {
  25. std::cerr << "# Reading: " << path << '\n' << std::flush;
  26. std::ifstream fs(path, std::ios_base::binary);
  27. if (!fs.is_open()) {
  28. fs = std::ifstream("../" + path, std::ios_base::binary);
  29. if (!fs.is_open()) {
  30. throw std::runtime_error("Failed to open file: " + path);
  31. }
  32. }
  33. fs.seekg(0, std::ios_base::end);
  34. auto size = fs.tellg();
  35. fs.seekg(0);
  36. std::string out;
  37. out.resize(static_cast<size_t>(size));
  38. fs.read(out.data(), static_cast<std::streamsize>(size));
  39. return out;
  40. }
  41. static common_chat_templates_ptr read_templates(const std::string & path) {
  42. return common_chat_templates_ptr(common_chat_templates_init(/* model= */ nullptr, read_file(path)));
  43. }
  44. static std::unique_ptr<llama_grammar> build_grammar(const std::string & grammar_str) {
  45. return std::unique_ptr<llama_grammar>(
  46. llama_grammar_init_impl(nullptr, grammar_str.c_str(), "root", false, nullptr, 0, nullptr, 0));
  47. }
  48. // TODO: extract to common helper (copied from test-grammar-integration.cpp)
  49. static bool match_string(const std::string & input, llama_grammar * grammar) {
  50. const auto cpts = unicode_cpts_from_utf8(input);
  51. auto & stacks_cur = llama_grammar_get_stacks(grammar);
  52. for (const auto & cpt : cpts) {
  53. llama_grammar_accept(grammar, cpt);
  54. if (stacks_cur.empty()) {
  55. // no stacks means that the grammar failed to match at this point
  56. return false;
  57. }
  58. }
  59. if (std::any_of(stacks_cur.begin(), stacks_cur.end(), [](const auto & stack) { return stack.empty(); })) {
  60. // An empty stack means that the grammar has been completed
  61. return true;
  62. }
  63. return false;
  64. }
  65. static void assert_msg_equals(const common_chat_msg & expected, const common_chat_msg & actual) {
  66. assert_equals(expected.role, actual.role);
  67. assert_equals(expected.content, actual.content);
  68. assert_equals(expected.content_parts.size(), actual.content_parts.size());
  69. for (size_t i = 0; i < expected.content_parts.size(); i++) {
  70. const auto & expected_part = expected.content_parts[i];
  71. const auto & actual_part = actual.content_parts[i];
  72. assert_equals(expected_part.type, actual_part.type);
  73. assert_equals(expected_part.text, actual_part.text);
  74. }
  75. assert_equals(expected.reasoning_content, actual.reasoning_content);
  76. assert_equals(expected.tool_calls.size(), actual.tool_calls.size());
  77. for (size_t i = 0; i < expected.tool_calls.size(); i++) {
  78. const auto & expected_tool_call = expected.tool_calls[i];
  79. const auto & actual_tool_call = actual.tool_calls[i];
  80. assert_equals(expected_tool_call.name, actual_tool_call.name);
  81. assert_equals(json::parse(expected_tool_call.arguments).dump(), json::parse(actual_tool_call.arguments).dump());
  82. assert_equals(expected_tool_call.id, actual_tool_call.id);
  83. }
  84. }
  85. common_chat_tool special_function_tool {
  86. /* .name = */ "special_function",
  87. /* .description = */ "I'm special",
  88. /* .parameters = */ R"({
  89. "type": "object",
  90. "properties": {
  91. "arg1": {
  92. "type": "integer",
  93. "description": "The arg."
  94. }
  95. },
  96. "required": ["arg1"]
  97. })",
  98. };
  99. common_chat_tool python_tool {
  100. /* .name = */ "python",
  101. /* .description = */ "an ipython interpreter",
  102. /* .parameters = */ R"({
  103. "type": "object",
  104. "properties": {
  105. "code": {
  106. "type": "string",
  107. "description": "Python code to execute."
  108. }
  109. },
  110. "required": ["code"]
  111. })",
  112. };
  113. common_chat_tool code_interpreter_tool {
  114. /* .name = */ "code_interpreter",
  115. /* .description = */ "an ipython interpreter",
  116. /* .parameters = */ R"({
  117. "type": "object",
  118. "properties": {
  119. "code": {
  120. "type": "string",
  121. "description": "Python code to execute."
  122. }
  123. },
  124. "required": ["code"]
  125. })",
  126. };
  127. std::vector<common_chat_tool> tools { special_function_tool, python_tool };
  128. std::vector<common_chat_tool> llama_3_1_tools { special_function_tool, code_interpreter_tool };
  129. struct delta_data {
  130. std::string delta;
  131. common_chat_params params;
  132. };
  133. static delta_data init_delta(const struct common_chat_templates * tmpls, const std::vector<std::string> & end_tokens,
  134. const common_chat_msg & user_message,
  135. const common_chat_msg & delta_message,
  136. const std::vector<common_chat_tool> & tools,
  137. const common_chat_tool_choice & tool_choice,
  138. bool think = false) {
  139. common_chat_templates_inputs inputs;
  140. inputs.parallel_tool_calls = true;
  141. inputs.messages.push_back(user_message);
  142. inputs.tools = tools;
  143. inputs.tool_choice = tool_choice;
  144. inputs.extract_reasoning = think;
  145. auto params_prefix = common_chat_templates_apply(tmpls, inputs);
  146. inputs.messages.push_back(delta_message);
  147. inputs.add_generation_prompt = false;
  148. auto params_full = common_chat_templates_apply(tmpls, inputs);
  149. std::string prefix = params_prefix.prompt;
  150. std::string full = params_full.prompt;
  151. if (full == prefix) {
  152. throw std::runtime_error("Full message is the same as the prefix");
  153. }
  154. size_t common_prefix_length = 0;
  155. for (size_t i = 0; i < prefix.size() && i < full.size(); ++i) {
  156. if (prefix[i] != full[i]) {
  157. break;
  158. }
  159. if (prefix[i] == '<') {
  160. // DeepSeek R1's template (as of 20250209) adds a trailing <think> if add_generation_prompt,
  161. // but it removes thinking tags for past messages.
  162. // The prefix and full strings diverge at <think> vs. <|tool▁calls▁begin|>, we avoid consuming the leading <.
  163. continue;
  164. }
  165. common_prefix_length = i + 1;
  166. }
  167. auto delta = full.substr(common_prefix_length);
  168. // Strip end tokens
  169. for (const auto & end_token : end_tokens) {
  170. // rfind to find the last occurrence
  171. auto pos = delta.rfind(end_token);
  172. if (pos != std::string::npos) {
  173. delta = delta.substr(0, pos);
  174. break;
  175. }
  176. }
  177. return { delta, params_full };
  178. }
  179. /*
  180. Applies the template to 1 user message w/ add_generation_prompt=true, then w/ the test message w/ add_generation_prompt=false,
  181. gets the diff, removes any end tokens and parses the result w/ the grammar, checking that
  182. the parsed message is the same as the test_message
  183. */
  184. static void test_templates(const struct common_chat_templates * tmpls, const std::vector<std::string> & end_tokens,
  185. const common_chat_msg & test_message,
  186. const std::vector<common_chat_tool> & tools = {},
  187. const std::string & expected_delta = "",
  188. bool expect_grammar_triggered = true,
  189. bool test_grammar_if_triggered = true,
  190. bool think = false) {
  191. common_chat_msg user_message;
  192. user_message.role = "user";
  193. user_message.content = "Hello, world!";
  194. for (const auto & tool_choice : std::vector<common_chat_tool_choice> {COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED}) {
  195. auto data = init_delta(tmpls, end_tokens, user_message, test_message, tools, tool_choice, think);
  196. if (!expected_delta.empty()) {
  197. assert_equals(expected_delta, data.delta);
  198. }
  199. if (expect_grammar_triggered) {
  200. const auto msg = common_chat_parse(data.delta, data.params.format);
  201. assert_msg_equals(test_message, msg);
  202. }
  203. if (!test_message.tool_calls.empty()) {
  204. GGML_ASSERT(!data.params.grammar.empty());
  205. }
  206. if (!data.params.grammar.empty()) {
  207. auto grammar = build_grammar(data.params.grammar);
  208. if (!grammar) {
  209. throw std::runtime_error("Failed to build grammar");
  210. }
  211. auto earliest_trigger_pos = std::string::npos;
  212. auto constrained = data.delta;
  213. for (const auto & trigger : data.params.grammar_triggers) {
  214. size_t pos = std::string::npos;
  215. std::smatch match;
  216. switch (trigger.type) {
  217. case COMMON_GRAMMAR_TRIGGER_TYPE_WORD:
  218. {
  219. const auto & word = trigger.value;
  220. pos = constrained.find(word);
  221. break;
  222. }
  223. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN:
  224. {
  225. const auto & pattern = trigger.value;
  226. if (std::regex_search(constrained, match, std::regex(pattern))) {
  227. pos = match.position();
  228. }
  229. break;
  230. }
  231. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_START:
  232. {
  233. const auto & pattern = trigger.value;
  234. if (std::regex_search(constrained, match, std::regex(pattern)) && match.position() == 0) {
  235. pos = 0;
  236. }
  237. break;
  238. }
  239. default:
  240. throw std::runtime_error("Unknown trigger type");
  241. }
  242. if (pos == std::string::npos) {
  243. continue;
  244. }
  245. if (earliest_trigger_pos == std::string::npos || pos < earliest_trigger_pos) {
  246. earliest_trigger_pos = pos;
  247. }
  248. }
  249. auto grammar_triggered = false;
  250. if (earliest_trigger_pos != std::string::npos) {
  251. constrained = constrained.substr(earliest_trigger_pos);
  252. grammar_triggered = true;
  253. }
  254. if (data.params.grammar_lazy) {
  255. assert_equals(expect_grammar_triggered, grammar_triggered);
  256. }
  257. if (grammar_triggered && test_grammar_if_triggered && !match_string(constrained, grammar.get())) {
  258. throw std::runtime_error("Failed to match delta against grammar:\n\n" + data.delta +
  259. "\n\nConstrained: " + constrained +
  260. "\n\nGrammar: " + data.params.grammar);
  261. }
  262. }
  263. }
  264. }
  265. const common_chat_msg message_user {
  266. "user",
  267. "Hey there!",
  268. /* .content_parts = */ {},
  269. /* .tool_calls = */ {},
  270. /* .reasoning_content = */ "",
  271. /* .tool_name = */ "",
  272. /* .tool_call_id = */ "",
  273. };
  274. const common_chat_msg message_user_parts {
  275. "user",
  276. /* .content = */ "",
  277. /* .content_parts = */ {
  278. { "text", "Hey" },
  279. { "text", "there" },
  280. },
  281. /* .tool_calls = */ {},
  282. /* .reasoning_content = */ "",
  283. /* .tool_name = */ "",
  284. /* .tool_call_id = */ "",
  285. };
  286. const common_chat_msg message_assist {
  287. "assistant",
  288. "Hello, world!\nWhat's up?",
  289. /* .content_parts = */ {},
  290. /* .tool_calls = */ {},
  291. /* .reasoning_content = */ "",
  292. /* .tool_name = */ "",
  293. /* .tool_call_id = */ "",
  294. };
  295. const common_chat_msg message_assist_thoughts_unparsed_think {
  296. "assistant",
  297. "<think>I'm thinking</think>Hello, world!\nWhat's up?",
  298. /* .content_parts = */ {},
  299. /* .tool_calls = */ {},
  300. /* .reasoning_content = */ "",
  301. /* .tool_name = */ "",
  302. /* .tool_call_id = */ "",
  303. };
  304. const common_chat_msg message_assist_thoughts_unparsed_r7b {
  305. "assistant",
  306. "<|START_THINKING|>I'm thinking<|END_THINKING|>Hello, world!\nWhat's up?",
  307. /* .content_parts = */ {},
  308. /* .tool_calls = */ {},
  309. /* .reasoning_content = */ "",
  310. /* .tool_name = */ "",
  311. /* .tool_call_id = */ "",
  312. };
  313. const common_chat_msg message_assist_thoughts {
  314. "assistant",
  315. "Hello, world!\nWhat's up?",
  316. /* .content_parts = */ {},
  317. /* .tool_calls = */ {},
  318. /* .reasoning_content = */ "I'm thinking",
  319. /* .tool_name = */ "",
  320. /* .tool_call_id = */ "",
  321. };
  322. const std::vector<common_chat_tool_call> tool_calls {
  323. { "special_function", "{\"arg1\": 1}", /* .id = */ "" },
  324. };
  325. const std::vector<common_chat_tool_call> tool_calls_idx {
  326. { "special_function", "{\"arg1\": 1}", /* .id = */ "0" },
  327. };
  328. const std::vector<common_chat_tool_call> tool_calls_id {
  329. { "special_function", "{\"arg1\": 1}", /* .id = */ "123456789" },
  330. };
  331. const common_chat_msg message_assist_call {
  332. "assistant",
  333. "",
  334. /* .content_parts = */ {},
  335. tool_calls,
  336. /* .reasoning_content = */ "",
  337. /* .tool_name = */ "",
  338. /* .tool_call_id = */ "",
  339. };
  340. const common_chat_msg message_assist_call_thoughts = {
  341. "assistant",
  342. /* .content = */ "",
  343. /* .content_parts = */ {},
  344. tool_calls,
  345. /* .reasoning_content = */ "I'm\nthinking",
  346. /* .tool_name = */ "",
  347. /* .tool_call_id = */ "",
  348. };
  349. const common_chat_msg message_assist_call_thoughts_unparsed = {
  350. "assistant",
  351. /* .content = */ "<think>I'm\nthinking</think>",
  352. /* .content_parts = */ {},
  353. tool_calls,
  354. /* .reasoning_content = */ "",
  355. /* .tool_name = */ "",
  356. /* .tool_call_id = */ "",
  357. };
  358. const common_chat_msg message_assist_call_id {
  359. "assistant",
  360. "",
  361. /* .content_parts = */ {},
  362. tool_calls_id,
  363. /* .reasoning_content = */ "",
  364. /* .tool_name = */ "",
  365. /* .tool_call_id = */ "",
  366. };
  367. const common_chat_msg message_assist_call_idx {
  368. "assistant",
  369. "",
  370. /* .content_parts = */ {},
  371. tool_calls_idx,
  372. /* .reasoning_content = */ "",
  373. /* .tool_name = */ "",
  374. /* .tool_call_id = */ "",
  375. };
  376. const common_chat_msg message_assist_call_python {
  377. "assistant",
  378. "",
  379. /* .content_parts = */ {},
  380. { { "python", "{\"code\": \"print('hey')\"}", /* .id = */ "" } },
  381. /* .reasoning_content = */ "",
  382. /* .tool_name = */ "",
  383. /* .tool_call_id = */ "",
  384. };
  385. const common_chat_msg message_assist_call_code_interpreter {
  386. "assistant",
  387. "",
  388. /* .content_parts = */ {},
  389. { { "code_interpreter", "{\"code\": \"print('hey')\"}", /* .id = */ "" } },
  390. /* .reasoning_content = */ "",
  391. /* .tool_name = */ "",
  392. /* .tool_call_id = */ "",
  393. };
  394. static void test_msgs_oaicompat_json_conversion() {
  395. std::vector<common_chat_msg> msgs{
  396. message_user,
  397. message_user_parts,
  398. message_assist_call,
  399. message_assist_call_thoughts,
  400. message_assist_call_thoughts_unparsed,
  401. message_assist_call_id,
  402. message_assist_call_idx,
  403. message_assist_call_python,
  404. message_assist_call_code_interpreter,
  405. };
  406. for (const auto & msg : msgs) {
  407. auto oai_json = common_chat_msgs_to_json_oaicompat<json>({msg});
  408. auto msgs2 = common_chat_msgs_parse_oaicompat(oai_json);
  409. assert_equals((size_t) 1, msgs2.size());
  410. auto msg2 = msgs2[0];
  411. assert_msg_equals(msg, msg2);
  412. }
  413. assert_equals(
  414. std::string(
  415. "[\n"
  416. " {\n"
  417. " \"role\": \"user\",\n"
  418. " \"content\": [\n"
  419. " {\n"
  420. " \"type\": \"text\",\n"
  421. " \"text\": \"Hey\"\n"
  422. " },\n"
  423. " {\n"
  424. " \"type\": \"text\",\n"
  425. " \"text\": \"there\"\n"
  426. " }\n"
  427. " ]\n"
  428. " }\n"
  429. "]"
  430. ),
  431. common_chat_msgs_to_json_oaicompat<json>({message_user_parts}).dump(2));
  432. assert_equals(
  433. std::string(
  434. "[\n"
  435. " {\n"
  436. " \"role\": \"assistant\",\n"
  437. " \"content\": null,\n"
  438. " \"tool_calls\": [\n"
  439. " {\n"
  440. " \"type\": \"function\",\n"
  441. " \"function\": {\n"
  442. " \"name\": \"python\",\n"
  443. " \"arguments\": \"{\\\"code\\\": \\\"print('hey')\\\"}\"\n"
  444. " }\n"
  445. " }\n"
  446. " ]\n"
  447. " }\n"
  448. "]"
  449. ),
  450. common_chat_msgs_to_json_oaicompat<json>({message_assist_call_python}).dump(2));
  451. auto res = common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\", \"tool_calls\": []}]"));
  452. assert_equals<size_t>(1, res.size());
  453. assert_equals<std::string>(res[0].role, "assistant");
  454. assert_equals(true, res[0].content.empty());
  455. assert_equals(true, res[0].tool_calls.empty());
  456. try {
  457. common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\"}]"));
  458. throw std::runtime_error("Expected exception");
  459. } catch (const std::exception & e) {
  460. if (std::string(e.what()).find("'content'") == std::string::npos) {
  461. throw std::runtime_error("Expected exception about missing 'content'");
  462. }
  463. }
  464. }
  465. static void test_tools_oaicompat_json_conversion() {
  466. std::vector<common_chat_tool> tools{
  467. special_function_tool,
  468. python_tool,
  469. code_interpreter_tool,
  470. };
  471. for (const auto & tool : tools) {
  472. auto oai_json = common_chat_tools_to_json_oaicompat<json>({tool});
  473. auto tools2 = common_chat_tools_parse_oaicompat(oai_json);
  474. assert_equals((size_t) 1, tools2.size());
  475. auto tool2 = tools2[0];
  476. assert_equals(tool.name, tool2.name);
  477. assert_equals(tool.description, tool2.description);
  478. assert_equals(json::parse(tool.parameters).dump(2), json::parse(tool2.parameters).dump(2));
  479. }
  480. assert_equals(
  481. std::string(
  482. "[\n"
  483. " {\n"
  484. " \"type\": \"function\",\n"
  485. " \"function\": {\n"
  486. " \"name\": \"special_function\",\n"
  487. " \"description\": \"I'm special\",\n"
  488. " \"parameters\": {\n"
  489. " \"type\": \"object\",\n"
  490. " \"properties\": {\n"
  491. " \"arg1\": {\n"
  492. " \"type\": \"integer\",\n"
  493. " \"description\": \"The arg.\"\n"
  494. " }\n"
  495. " },\n"
  496. " \"required\": [\n"
  497. " \"arg1\"\n"
  498. " ]\n"
  499. " }\n"
  500. " }\n"
  501. " }\n"
  502. "]"
  503. ),
  504. common_chat_tools_to_json_oaicompat<json>({special_function_tool}).dump(2));
  505. }
  506. static void test_template_output_parsers() {
  507. common_chat_templates_inputs inputs_no_tools;
  508. inputs_no_tools.messages = {message_user};
  509. inputs_no_tools.extract_reasoning = false;
  510. common_chat_templates_inputs inputs_no_tools_think;
  511. inputs_no_tools_think.messages = {message_user};
  512. inputs_no_tools_think.extract_reasoning = true;
  513. common_chat_templates_inputs inputs_tools;
  514. inputs_tools.messages = {message_user};
  515. inputs_tools.tools = {special_function_tool};
  516. inputs_tools.extract_reasoning = false;
  517. common_chat_templates_inputs inputs_tools_think;
  518. inputs_tools_think.messages = {message_user};
  519. inputs_tools_think.tools = {special_function_tool};
  520. inputs_tools_think.extract_reasoning = true;
  521. common_chat_templates_inputs inputs_tools_builtin;
  522. inputs_tools_builtin.messages = {message_user};
  523. inputs_tools_builtin.tools = {python_tool};
  524. inputs_tools_builtin.extract_reasoning = false;
  525. {
  526. // Not supported yet
  527. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r-plus-tool_use.jinja");
  528. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  529. }
  530. {
  531. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r7b-12-2024-tool_use.jinja");
  532. std::vector<std::string> end_tokens{ "<|END_OF_TURN_TOKEN|>" };
  533. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  534. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  535. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B_EXTRACT_REASONING, common_chat_templates_apply(tmpls.get(), inputs_tools_think).format);
  536. assert_msg_equals(message_assist,
  537. common_chat_parse(
  538. "Hello, world!\nWhat's up?",
  539. COMMON_CHAT_FORMAT_COMMAND_R7B));
  540. assert_msg_equals(message_assist,
  541. common_chat_parse(
  542. "Hello, world!\nWhat's up?<|END_RESPONSE|>",
  543. COMMON_CHAT_FORMAT_COMMAND_R7B));
  544. assert_msg_equals(message_assist,
  545. common_chat_parse(
  546. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  547. COMMON_CHAT_FORMAT_COMMAND_R7B));
  548. assert_msg_equals(message_assist_thoughts_unparsed_r7b,
  549. common_chat_parse(
  550. "<|START_THINKING|>I'm thinking<|END_THINKING|>"
  551. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  552. COMMON_CHAT_FORMAT_COMMAND_R7B));
  553. assert_msg_equals(message_assist_thoughts_unparsed_r7b,
  554. common_chat_parse(
  555. "<|START_THINKING|>I'm thinking<|END_THINKING|>"
  556. "Hello, world!\nWhat's up?<|END_RESPONSE|>",
  557. COMMON_CHAT_FORMAT_COMMAND_R7B));
  558. assert_msg_equals(message_assist_thoughts,
  559. common_chat_parse(
  560. "<|START_THINKING|>I'm thinking<|END_THINKING|>"
  561. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  562. COMMON_CHAT_FORMAT_COMMAND_R7B_EXTRACT_REASONING));
  563. test_templates(tmpls.get(), end_tokens, message_assist_call_idx, tools,
  564. "<|START_THINKING|><|END_THINKING|>"
  565. "<|START_ACTION|>[\n"
  566. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  567. "]<|END_ACTION|>");
  568. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  569. "<|START_RESPONSE|>Hello, world!\n"
  570. "What's up?<|END_RESPONSE|>",
  571. /* expect_grammar_triggered= */ false);
  572. }
  573. {
  574. auto tmpls = read_templates("models/templates/google-gemma-2-2b-it.jinja");
  575. std::vector<std::string> end_tokens{ "<end_of_turn>" };
  576. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  577. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  578. assert_equals(COMMON_CHAT_FORMAT_GENERIC,
  579. common_chat_templates_apply(
  580. read_templates("models/templates/microsoft-Phi-3.5-mini-instruct.jinja").get(),
  581. inputs_tools)
  582. .format);
  583. // Generic tool calls doesn't generate / parse content-only messages symmetrically.
  584. assert_msg_equals(message_assist,
  585. common_chat_parse("{\n"
  586. " \"response\": \"Hello, world!\\nWhat's up?\"\n"
  587. "}",
  588. common_chat_templates_apply(tmpls.get(), inputs_tools).format));
  589. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  590. "{\n"
  591. " \"tool_calls\": [\n"
  592. " {\n"
  593. " \"name\": \"special_function\",\n"
  594. " \"arguments\": {\n"
  595. " \"arg1\": 1\n"
  596. " },\n"
  597. " \"id\": \"123456789\"\n"
  598. " }\n"
  599. " ]\n"
  600. "}");
  601. }
  602. {
  603. auto tmpls = read_templates("models/templates/mistralai-Mistral-Nemo-Instruct-2407.jinja");
  604. std::vector<std::string> end_tokens{ "</s>" };
  605. assert_equals(COMMON_CHAT_FORMAT_MISTRAL_NEMO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  606. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  607. test_templates(
  608. tmpls.get(), end_tokens, message_assist_call_id, tools,
  609. "[TOOL_CALLS][{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, \"id\": \"123456789\"}]");
  610. }
  611. {
  612. auto tmpls = read_templates("models/templates/NousResearch-Hermes-2-Pro-Llama-3-8B-tool_use.jinja");
  613. std::vector<std::string> end_tokens{ "<|im_end|>" };
  614. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  615. assert_equals(
  616. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  617. common_chat_templates_apply(
  618. read_templates("models/templates/NousResearch-Hermes-3-Llama-3.1-8B-tool_use.jinja").get(),
  619. inputs_tools)
  620. .format);
  621. assert_equals(
  622. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  623. common_chat_templates_apply(
  624. read_templates("models/templates/Qwen-Qwen2.5-7B-Instruct.jinja").get(),
  625. inputs_tools)
  626. .format);
  627. // Test parsing
  628. assert_msg_equals(message_assist_call, common_chat_parse(
  629. "<tool_call>\n"
  630. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  631. "</tool_call>",
  632. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  633. assert_msg_equals(message_assist_call, common_chat_parse(
  634. "<function=special_function>{\"arg1\": 1}</function>",
  635. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  636. assert_msg_equals(message_assist_call, common_chat_parse(
  637. "<function name=\"special_function\">\n"
  638. "{\"arg1\": 1}\n"
  639. "</function>",
  640. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  641. assert_msg_equals(message_assist_call, common_chat_parse(
  642. "<tool>\n"
  643. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  644. "</tool>",
  645. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  646. assert_msg_equals(message_assist_call, common_chat_parse(
  647. "<tools>\n"
  648. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  649. "</tools>",
  650. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  651. assert_msg_equals(message_assist_call, common_chat_parse(
  652. "<response>\n"
  653. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  654. "</response>",
  655. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  656. assert_msg_equals(message_assist_call, common_chat_parse(
  657. "```xml\n"
  658. "<response>\n"
  659. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  660. "</response>\n"
  661. "```",
  662. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  663. assert_msg_equals(message_assist_call, common_chat_parse(
  664. "```xml\n"
  665. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  666. "```",
  667. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  668. assert_msg_equals(message_assist_call, common_chat_parse(
  669. "```\n"
  670. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  671. "```",
  672. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  673. assert_msg_equals(message_assist_call, common_chat_parse(
  674. "```\n"
  675. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  676. "```",
  677. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  678. assert_msg_equals(message_assist_call, common_chat_parse(
  679. "```json\n"
  680. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  681. "```",
  682. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  683. assert_msg_equals(message_assist_call, common_chat_parse(
  684. "```json\n"
  685. "\n"
  686. " <function_call> {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}} \n"
  687. " </function_call> \n"
  688. "``` ",
  689. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  690. assert_msg_equals(message_assist_call, common_chat_parse(
  691. "<json>\n"
  692. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  693. "</json>",
  694. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  695. assert_msg_equals(message_assist_call, common_chat_parse(
  696. "<xml>\n"
  697. " {\n"
  698. " \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}\n"
  699. " }\n"
  700. "</xml>",
  701. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  702. assert_msg_equals(message_assist_call, common_chat_parse(
  703. "<JSON>\n"
  704. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  705. "</JSON>",
  706. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  707. assert_msg_equals(message_assist_call, common_chat_parse(
  708. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  709. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  710. assert_msg_equals(message_assist_call, common_chat_parse(
  711. "{\n \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  712. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  713. assert_msg_equals(message_assist_thoughts_unparsed_think,
  714. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  715. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  716. assert_msg_equals(message_assist_thoughts_unparsed_think,
  717. common_chat_parse("I'm thinking</think>Hello, world!\nWhat's up?",
  718. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  719. assert_msg_equals(message_assist_thoughts,
  720. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  721. COMMON_CHAT_FORMAT_HERMES_2_PRO_EXTRACT_REASONING));
  722. assert_msg_equals(message_assist_thoughts,
  723. common_chat_parse("I'm thinking</think>Hello, world!\nWhat's up?",
  724. COMMON_CHAT_FORMAT_HERMES_2_PRO_EXTRACT_REASONING));
  725. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  726. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  727. "<tool_call>\n"
  728. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  729. "</tool_call>");
  730. test_templates(tmpls.get(), end_tokens, message_assist_call_python, tools,
  731. "<tool_call>\n"
  732. "{\"name\": \"python\", \"arguments\": {\"code\": \"print('hey')\"}}\n"
  733. "</tool_call>");
  734. }
  735. {
  736. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.1-8B-Instruct.jinja");
  737. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  738. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  739. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  740. common_chat_templates_apply(tmpls.get(), inputs_tools_builtin).format);
  741. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  742. common_chat_templates_apply(
  743. read_templates("models/templates/meta-llama-Llama-3.3-70B-Instruct.jinja").get(),
  744. inputs_tools_builtin)
  745. .format);
  746. // test_templates(tmpls.get(), end_tokens, message_assist, tools, R"(?)", /* expect_grammar_triggered= */ false);
  747. test_templates(tmpls.get(), end_tokens, message_assist_call_code_interpreter, llama_3_1_tools,
  748. "<|python_tag|>code_interpreter.call(code=\"print('hey')\")");
  749. test_templates(tmpls.get(), end_tokens, message_assist_call_python, tools,
  750. "<|python_tag|>python.call(code=\"print('hey')\")");
  751. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  752. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  753. }
  754. {
  755. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.2-3B-Instruct.jinja");
  756. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  757. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  758. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  759. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  760. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  761. }
  762. {
  763. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.1.jinja");
  764. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  765. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1,
  766. common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  767. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  768. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  769. "<function=special_function>{\"arg1\": 1}</function>");
  770. }
  771. {
  772. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.2.jinja");
  773. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  774. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  775. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  776. test_templates(tmpls.get(), end_tokens, message_assist, {},
  777. "all\n"
  778. "Hello, world!\n"
  779. "What's up?",
  780. /* expect_grammar_triggered= */ false);
  781. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  782. "special_function\n"
  783. "{\"arg1\": 1}");
  784. }
  785. {
  786. auto tmpls = read_templates("models/templates/fireworks-ai-llama-3-firefunction-v2.jinja");
  787. std::vector<std::string> end_tokens{ "<|eot_id|>" };
  788. assert_equals(COMMON_CHAT_FORMAT_FIREFUNCTION_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  789. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  790. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  791. " functools[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]");
  792. }
  793. {
  794. // Original DeepSeek R1 template. Leaves <|tool▁calls▁begin|> and others unclosed. Our logic fixes the prompt.
  795. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-R1-Distill-Llama-8B.jinja");
  796. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  797. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  798. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING, common_chat_templates_apply(tmpls.get(), inputs_tools_think).format);
  799. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  800. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  801. assert_msg_equals(message_assist_thoughts_unparsed_think,
  802. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  803. COMMON_CHAT_FORMAT_DEEPSEEK_R1));
  804. assert_msg_equals(message_assist_thoughts,
  805. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  806. COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING));
  807. assert_msg_equals(message_assist_thoughts,
  808. // Latest template update (ast of 20250209) adds a trailing <think>\n if add_generation_prompt is true.
  809. common_chat_parse("I'm thinking</think>Hello, world!\nWhat's up?",
  810. COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING));
  811. // test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  812. // "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  813. // "```json\n"
  814. // "{\"arg1\": 1}\n"
  815. // // Look what's not here: <|tool▁calls▁end|> (also missing the <|end▁of▁sentence|>, but that is removed lazily by the test's delta logic)
  816. // "```<|tool▁call▁end|>",
  817. // /* expect_grammar_triggered= */ true,
  818. // /* test_grammar_if_triggered= */ false);
  819. }
  820. {
  821. // Replacement DeepSeek R1 template. Makes the Distill Qwen 7B/32B models happy to call tools and all.
  822. auto tmpls = read_templates("models/templates/llama-cpp-deepseek-r1.jinja");
  823. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  824. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  825. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING, common_chat_templates_apply(tmpls.get(), inputs_tools_think).format);
  826. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  827. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  828. assert_msg_equals(message_assist_thoughts_unparsed_think,
  829. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  830. COMMON_CHAT_FORMAT_DEEPSEEK_R1));
  831. assert_msg_equals(message_assist_thoughts,
  832. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  833. COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING));
  834. assert_msg_equals(message_assist_call_thoughts_unparsed,
  835. common_chat_parse(
  836. "<think>I'm\nthinking</think>\n\n"
  837. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  838. "```json\n"
  839. "{\"arg1\": 1}\n"
  840. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  841. COMMON_CHAT_FORMAT_DEEPSEEK_R1));
  842. assert_msg_equals(message_assist_call_thoughts,
  843. common_chat_parse(
  844. "<think>I'm\nthinking</think>\n\n"
  845. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  846. "```json\n"
  847. "{\"arg1\": 1}\n"
  848. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  849. COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING));
  850. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  851. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  852. "```json\n"
  853. "{\"arg1\": 1}\n"
  854. "```<|tool▁call▁end|><|tool▁calls▁end|>");
  855. }
  856. }
  857. int main(int argc, char ** argv) {
  858. // try {
  859. #ifndef _WIN32
  860. if (argc > 1) {
  861. common_chat_templates_inputs inputs;
  862. common_chat_msg msg;
  863. msg.role = "user";
  864. msg.content = "Hey";
  865. inputs.messages = {msg};
  866. inputs.tools = { special_function_tool };
  867. std::cout << "| Template | Format |\n";
  868. std::cout << "|----------|--------|\n";
  869. for (int i = 1; i < argc; i++) {
  870. try {
  871. std::string path = argv[i];
  872. if (path.rfind(".jinja") != path.size() - 6) {
  873. std::cerr << "Skipping non-jinja file: " << path << '\n';
  874. continue;
  875. }
  876. auto tmpls = read_templates(path);
  877. auto parts = string_split(path, "/");
  878. auto name = parts[parts.size() - 1];
  879. auto format = common_chat_format_name(common_chat_templates_apply(tmpls.get(), inputs).format);
  880. std::cout << "| " << name << " | " << format << " |\n";
  881. } catch (const std::exception & e) {
  882. std::cerr << "Failed to process " << argv[i] << ": " << e.what() << '\n';
  883. }
  884. }
  885. } else
  886. #endif
  887. {
  888. test_msgs_oaicompat_json_conversion();
  889. test_tools_oaicompat_json_conversion();
  890. test_template_output_parsers();
  891. std::cout << "\n[chat] All tests passed!" << '\n';
  892. }
  893. return 0;
  894. // } catch (const std::exception & e) {
  895. // std::cerr << "Error: " << e.what() << '\n';
  896. // return 1;
  897. // }
  898. }