test-chat.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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. }
  452. static void test_tools_oaicompat_json_conversion() {
  453. std::vector<common_chat_tool> tools{
  454. special_function_tool,
  455. python_tool,
  456. code_interpreter_tool,
  457. };
  458. for (const auto & tool : tools) {
  459. auto oai_json = common_chat_tools_to_json_oaicompat<json>({tool});
  460. auto tools2 = common_chat_tools_parse_oaicompat(oai_json);
  461. assert_equals((size_t) 1, tools2.size());
  462. auto tool2 = tools2[0];
  463. assert_equals(tool.name, tool2.name);
  464. assert_equals(tool.description, tool2.description);
  465. assert_equals(json::parse(tool.parameters).dump(2), json::parse(tool2.parameters).dump(2));
  466. }
  467. assert_equals(
  468. std::string(
  469. "[\n"
  470. " {\n"
  471. " \"type\": \"function\",\n"
  472. " \"function\": {\n"
  473. " \"name\": \"special_function\",\n"
  474. " \"description\": \"I'm special\",\n"
  475. " \"parameters\": {\n"
  476. " \"type\": \"object\",\n"
  477. " \"properties\": {\n"
  478. " \"arg1\": {\n"
  479. " \"type\": \"integer\",\n"
  480. " \"description\": \"The arg.\"\n"
  481. " }\n"
  482. " },\n"
  483. " \"required\": [\n"
  484. " \"arg1\"\n"
  485. " ]\n"
  486. " }\n"
  487. " }\n"
  488. " }\n"
  489. "]"
  490. ),
  491. common_chat_tools_to_json_oaicompat<json>({special_function_tool}).dump(2));
  492. }
  493. static void test_template_output_parsers() {
  494. common_chat_templates_inputs inputs_no_tools;
  495. inputs_no_tools.messages = {message_user};
  496. inputs_no_tools.extract_reasoning = false;
  497. common_chat_templates_inputs inputs_no_tools_think;
  498. inputs_no_tools_think.messages = {message_user};
  499. inputs_no_tools_think.extract_reasoning = true;
  500. common_chat_templates_inputs inputs_tools;
  501. inputs_tools.messages = {message_user};
  502. inputs_tools.tools = {special_function_tool};
  503. inputs_tools.extract_reasoning = false;
  504. common_chat_templates_inputs inputs_tools_think;
  505. inputs_tools_think.messages = {message_user};
  506. inputs_tools_think.tools = {special_function_tool};
  507. inputs_tools_think.extract_reasoning = true;
  508. common_chat_templates_inputs inputs_tools_builtin;
  509. inputs_tools_builtin.messages = {message_user};
  510. inputs_tools_builtin.tools = {python_tool};
  511. inputs_tools_builtin.extract_reasoning = false;
  512. {
  513. // Not supported yet
  514. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r-plus-tool_use.jinja");
  515. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  516. }
  517. {
  518. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r7b-12-2024-tool_use.jinja");
  519. std::vector<std::string> end_tokens{ "<|END_OF_TURN_TOKEN|>" };
  520. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  521. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  522. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B_EXTRACT_REASONING, common_chat_templates_apply(tmpls.get(), inputs_tools_think).format);
  523. assert_msg_equals(message_assist,
  524. common_chat_parse(
  525. "Hello, world!\nWhat's up?",
  526. COMMON_CHAT_FORMAT_COMMAND_R7B));
  527. assert_msg_equals(message_assist,
  528. common_chat_parse(
  529. "Hello, world!\nWhat's up?<|END_RESPONSE|>",
  530. COMMON_CHAT_FORMAT_COMMAND_R7B));
  531. assert_msg_equals(message_assist,
  532. common_chat_parse(
  533. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  534. COMMON_CHAT_FORMAT_COMMAND_R7B));
  535. assert_msg_equals(message_assist_thoughts_unparsed_r7b,
  536. common_chat_parse(
  537. "<|START_THINKING|>I'm thinking<|END_THINKING|>"
  538. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  539. COMMON_CHAT_FORMAT_COMMAND_R7B));
  540. assert_msg_equals(message_assist_thoughts_unparsed_r7b,
  541. common_chat_parse(
  542. "<|START_THINKING|>I'm thinking<|END_THINKING|>"
  543. "Hello, world!\nWhat's up?<|END_RESPONSE|>",
  544. COMMON_CHAT_FORMAT_COMMAND_R7B));
  545. assert_msg_equals(message_assist_thoughts,
  546. common_chat_parse(
  547. "<|START_THINKING|>I'm thinking<|END_THINKING|>"
  548. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  549. COMMON_CHAT_FORMAT_COMMAND_R7B_EXTRACT_REASONING));
  550. test_templates(tmpls.get(), end_tokens, message_assist_call_idx, tools,
  551. "<|START_THINKING|><|END_THINKING|>"
  552. "<|START_ACTION|>[\n"
  553. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  554. "]<|END_ACTION|>");
  555. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  556. "<|START_RESPONSE|>Hello, world!\n"
  557. "What's up?<|END_RESPONSE|>",
  558. /* expect_grammar_triggered= */ false);
  559. }
  560. {
  561. auto tmpls = read_templates("models/templates/google-gemma-2-2b-it.jinja");
  562. std::vector<std::string> end_tokens{ "<end_of_turn>" };
  563. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  564. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  565. assert_equals(COMMON_CHAT_FORMAT_GENERIC,
  566. common_chat_templates_apply(
  567. read_templates("models/templates/microsoft-Phi-3.5-mini-instruct.jinja").get(),
  568. inputs_tools)
  569. .format);
  570. // Generic tool calls doesn't generate / parse content-only messages symmetrically.
  571. assert_msg_equals(message_assist,
  572. common_chat_parse("{\n"
  573. " \"response\": \"Hello, world!\\nWhat's up?\"\n"
  574. "}",
  575. common_chat_templates_apply(tmpls.get(), inputs_tools).format));
  576. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  577. "{\n"
  578. " \"tool_calls\": [\n"
  579. " {\n"
  580. " \"name\": \"special_function\",\n"
  581. " \"arguments\": {\n"
  582. " \"arg1\": 1\n"
  583. " },\n"
  584. " \"id\": \"123456789\"\n"
  585. " }\n"
  586. " ]\n"
  587. "}");
  588. }
  589. {
  590. auto tmpls = read_templates("models/templates/mistralai-Mistral-Nemo-Instruct-2407.jinja");
  591. std::vector<std::string> end_tokens{ "</s>" };
  592. assert_equals(COMMON_CHAT_FORMAT_MISTRAL_NEMO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  593. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  594. test_templates(
  595. tmpls.get(), end_tokens, message_assist_call_id, tools,
  596. "[TOOL_CALLS][{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, \"id\": \"123456789\"}]");
  597. }
  598. {
  599. auto tmpls = read_templates("models/templates/NousResearch-Hermes-2-Pro-Llama-3-8B-tool_use.jinja");
  600. std::vector<std::string> end_tokens{ "<|im_end|>" };
  601. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  602. assert_equals(
  603. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  604. common_chat_templates_apply(
  605. read_templates("models/templates/NousResearch-Hermes-3-Llama-3.1-8B-tool_use.jinja").get(),
  606. inputs_tools)
  607. .format);
  608. assert_equals(
  609. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  610. common_chat_templates_apply(
  611. read_templates("models/templates/Qwen-Qwen2.5-7B-Instruct.jinja").get(),
  612. inputs_tools)
  613. .format);
  614. // Test parsing
  615. assert_msg_equals(message_assist_call, common_chat_parse(
  616. "<tool_call>\n"
  617. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  618. "</tool_call>",
  619. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  620. assert_msg_equals(message_assist_call, common_chat_parse(
  621. "<function=special_function>{\"arg1\": 1}</function>",
  622. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  623. assert_msg_equals(message_assist_call, common_chat_parse(
  624. "<function name=\"special_function\">\n"
  625. "{\"arg1\": 1}\n"
  626. "</function>",
  627. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  628. assert_msg_equals(message_assist_call, common_chat_parse(
  629. "<tool>\n"
  630. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  631. "</tool>",
  632. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  633. assert_msg_equals(message_assist_call, common_chat_parse(
  634. "<tools>\n"
  635. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  636. "</tools>",
  637. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  638. assert_msg_equals(message_assist_call, common_chat_parse(
  639. "<response>\n"
  640. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  641. "</response>",
  642. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  643. assert_msg_equals(message_assist_call, common_chat_parse(
  644. "```xml\n"
  645. "<response>\n"
  646. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  647. "</response>\n"
  648. "```",
  649. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  650. assert_msg_equals(message_assist_call, common_chat_parse(
  651. "```xml\n"
  652. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  653. "```",
  654. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  655. assert_msg_equals(message_assist_call, common_chat_parse(
  656. "```\n"
  657. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  658. "```",
  659. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  660. assert_msg_equals(message_assist_call, common_chat_parse(
  661. "```\n"
  662. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  663. "```",
  664. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  665. assert_msg_equals(message_assist_call, common_chat_parse(
  666. "```json\n"
  667. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  668. "```",
  669. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  670. assert_msg_equals(message_assist_call, common_chat_parse(
  671. "```json\n"
  672. "\n"
  673. " <function_call> {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}} \n"
  674. " </function_call> \n"
  675. "``` ",
  676. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  677. assert_msg_equals(message_assist_call, common_chat_parse(
  678. "<json>\n"
  679. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  680. "</json>",
  681. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  682. assert_msg_equals(message_assist_call, common_chat_parse(
  683. "<xml>\n"
  684. " {\n"
  685. " \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}\n"
  686. " }\n"
  687. "</xml>",
  688. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  689. assert_msg_equals(message_assist_call, common_chat_parse(
  690. "<JSON>\n"
  691. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  692. "</JSON>",
  693. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  694. assert_msg_equals(message_assist_call, common_chat_parse(
  695. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  696. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  697. assert_msg_equals(message_assist_call, common_chat_parse(
  698. "{\n \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  699. COMMON_CHAT_FORMAT_HERMES_2_PRO));
  700. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  701. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  702. "<tool_call>\n"
  703. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  704. "</tool_call>");
  705. test_templates(tmpls.get(), end_tokens, message_assist_call_python, tools,
  706. "<tool_call>\n"
  707. "{\"name\": \"python\", \"arguments\": {\"code\": \"print('hey')\"}}\n"
  708. "</tool_call>");
  709. }
  710. {
  711. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.1-8B-Instruct.jinja");
  712. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  713. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  714. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  715. common_chat_templates_apply(tmpls.get(), inputs_tools_builtin).format);
  716. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  717. common_chat_templates_apply(
  718. read_templates("models/templates/meta-llama-Llama-3.3-70B-Instruct.jinja").get(),
  719. inputs_tools_builtin)
  720. .format);
  721. // test_templates(tmpls.get(), end_tokens, message_assist, tools, R"(?)", /* expect_grammar_triggered= */ false);
  722. test_templates(tmpls.get(), end_tokens, message_assist_call_code_interpreter, llama_3_1_tools,
  723. "<|python_tag|>code_interpreter.call(code=\"print('hey')\")");
  724. test_templates(tmpls.get(), end_tokens, message_assist_call_python, tools,
  725. "<|python_tag|>python.call(code=\"print('hey')\")");
  726. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  727. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  728. }
  729. {
  730. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.2-3B-Instruct.jinja");
  731. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  732. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  733. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  734. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  735. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  736. }
  737. {
  738. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.1.jinja");
  739. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  740. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1,
  741. common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  742. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  743. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  744. "<function=special_function>{\"arg1\": 1}</function>");
  745. }
  746. {
  747. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.2.jinja");
  748. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  749. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  750. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  751. test_templates(tmpls.get(), end_tokens, message_assist, {},
  752. "all\n"
  753. "Hello, world!\n"
  754. "What's up?",
  755. /* expect_grammar_triggered= */ false);
  756. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  757. "special_function\n"
  758. "{\"arg1\": 1}");
  759. }
  760. {
  761. auto tmpls = read_templates("models/templates/fireworks-ai-llama-3-firefunction-v2.jinja");
  762. std::vector<std::string> end_tokens{ "<|eot_id|>" };
  763. assert_equals(COMMON_CHAT_FORMAT_FIREFUNCTION_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  764. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  765. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  766. " functools[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]");
  767. }
  768. {
  769. // Original DeepSeek R1 template. Leaves <|tool▁calls▁begin|> and others unclosed. Our logic fixes the prompt.
  770. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-R1-Distill-Llama-8B.jinja");
  771. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  772. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  773. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING, common_chat_templates_apply(tmpls.get(), inputs_tools_think).format);
  774. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  775. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  776. assert_msg_equals(message_assist_thoughts_unparsed_think,
  777. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  778. COMMON_CHAT_FORMAT_DEEPSEEK_R1));
  779. assert_msg_equals(message_assist_thoughts,
  780. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  781. COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING));
  782. assert_msg_equals(message_assist_thoughts,
  783. // Latest template update (ast of 20250209) adds a trailing <think>\n if add_generation_prompt is true.
  784. common_chat_parse("I'm thinking</think>Hello, world!\nWhat's up?",
  785. COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING));
  786. // test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  787. // "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  788. // "```json\n"
  789. // "{\"arg1\": 1}\n"
  790. // // 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)
  791. // "```<|tool▁call▁end|>",
  792. // /* expect_grammar_triggered= */ true,
  793. // /* test_grammar_if_triggered= */ false);
  794. }
  795. {
  796. // Replacement DeepSeek R1 template. Makes the Distill Qwen 7B/32B models happy to call tools and all.
  797. auto tmpls = read_templates("models/templates/llama-cpp-deepseek-r1.jinja");
  798. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  799. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  800. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING, common_chat_templates_apply(tmpls.get(), inputs_tools_think).format);
  801. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  802. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  803. assert_msg_equals(message_assist_thoughts_unparsed_think,
  804. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  805. COMMON_CHAT_FORMAT_DEEPSEEK_R1));
  806. assert_msg_equals(message_assist_thoughts,
  807. common_chat_parse("<think>I'm thinking</think>Hello, world!\nWhat's up?",
  808. COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING));
  809. assert_msg_equals(message_assist_call_thoughts_unparsed,
  810. common_chat_parse(
  811. "<think>I'm\nthinking</think>\n\n"
  812. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  813. "```json\n"
  814. "{\"arg1\": 1}\n"
  815. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  816. COMMON_CHAT_FORMAT_DEEPSEEK_R1));
  817. assert_msg_equals(message_assist_call_thoughts,
  818. common_chat_parse(
  819. "<think>I'm\nthinking</think>\n\n"
  820. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  821. "```json\n"
  822. "{\"arg1\": 1}\n"
  823. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  824. COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING));
  825. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  826. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  827. "```json\n"
  828. "{\"arg1\": 1}\n"
  829. "```<|tool▁call▁end|><|tool▁calls▁end|>");
  830. }
  831. }
  832. int main(int argc, char ** argv) {
  833. // try {
  834. #ifndef _WIN32
  835. if (argc > 1) {
  836. common_chat_templates_inputs inputs;
  837. common_chat_msg msg;
  838. msg.role = "user";
  839. msg.content = "Hey";
  840. inputs.messages = {msg};
  841. inputs.tools = { special_function_tool };
  842. std::cout << "| Template | Format |\n";
  843. std::cout << "|----------|--------|\n";
  844. for (int i = 1; i < argc; i++) {
  845. try {
  846. std::string path = argv[i];
  847. if (path.rfind(".jinja") != path.size() - 6) {
  848. std::cerr << "Skipping non-jinja file: " << path << '\n';
  849. continue;
  850. }
  851. auto tmpls = read_templates(path);
  852. auto parts = string_split(path, "/");
  853. auto name = parts[parts.size() - 1];
  854. auto format = common_chat_format_name(common_chat_templates_apply(tmpls.get(), inputs).format);
  855. std::cout << "| " << name << " | " << format << " |\n";
  856. } catch (const std::exception & e) {
  857. std::cerr << "Failed to process " << argv[i] << ": " << e.what() << '\n';
  858. }
  859. }
  860. } else
  861. #endif
  862. {
  863. test_msgs_oaicompat_json_conversion();
  864. test_tools_oaicompat_json_conversion();
  865. test_template_output_parsers();
  866. std::cout << "\n[chat] All tests passed!" << '\n';
  867. }
  868. return 0;
  869. // } catch (const std::exception & e) {
  870. // std::cerr << "Error: " << e.what() << '\n';
  871. // return 1;
  872. // }
  873. }