test-chat.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  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 "chat.h"
  9. #include "log.h"
  10. #include "../src/unicode.h"
  11. #include "../src/llama-grammar.h"
  12. #include <nlohmann/json.hpp>
  13. #include <fstream>
  14. #include <iostream>
  15. #include <string>
  16. using json = nlohmann::ordered_json;
  17. static std::ostream & operator<<(std::ostream & os, const common_chat_msg_diff & diff) {
  18. os << "{ content_delta: " << diff.content_delta << "; ";
  19. os << "reasoning_content_delta: " << diff.reasoning_content_delta << "; ";
  20. if (diff.tool_call_index != std::string::npos) {
  21. os << "tool_call_index: " << diff.tool_call_index << "; ";
  22. os << "tool_call_delta.name: " << diff.tool_call_delta.name << "; ";
  23. os << "tool_call_delta.id: " << diff.tool_call_delta.id << "; ";
  24. os << "tool_call_delta.arguments: " << diff.tool_call_delta.arguments << "; ";
  25. }
  26. os << "}";
  27. return os;
  28. }
  29. // operator<< for vector<common_chat_msg_diff>:
  30. static std::ostream & operator<<(std::ostream & os, const std::vector<common_chat_msg_diff> & diffs) {
  31. os << "[\n";
  32. for (const auto & diff : diffs) {
  33. os << " " << diff << ",\n";
  34. }
  35. os << "]";
  36. return os;
  37. }
  38. static std::ostream & operator<<(std::ostream & os, const common_chat_msg & msg) {
  39. os << "{ role: " << msg.role << "; ";
  40. os << "content: " << msg.content << "; ";
  41. os << "content_parts: [\n";
  42. for (const auto & part : msg.content_parts) {
  43. os << " { type: " << part.type << "; text: " << part.text << " },\n";
  44. }
  45. os << "]; ";
  46. os << "reasoning_content: " << msg.reasoning_content << "; ";
  47. os << "tool_calls: [\n";
  48. for (const auto & tool_call : msg.tool_calls) {
  49. os << " { name: " << tool_call.name << "; arguments: " << tool_call.arguments << "; id: " << tool_call.id << " },\n";
  50. }
  51. os << "]";
  52. os << "}";
  53. return os;
  54. }
  55. template <class T> static bool equals(const T & expected, const T & actual) {
  56. return expected == actual;
  57. }
  58. static common_chat_msg normalize(const common_chat_msg & msg) {
  59. common_chat_msg normalized = msg;
  60. for (auto & tool_call : normalized.tool_calls) {
  61. try {
  62. tool_call.arguments = json::parse(tool_call.arguments).dump();
  63. } catch (const std::exception &) {
  64. // Do nothing
  65. }
  66. }
  67. return normalized;
  68. }
  69. template <>
  70. bool equals(const common_chat_msg & expected, const common_chat_msg & actual) {
  71. return normalize(expected) == normalize(actual);
  72. }
  73. template <class T> static void assert_equals(const T & expected, const T & actual) {
  74. if (!equals(expected, actual)) {
  75. std::cerr << "Expected: " << expected << std::endl;
  76. std::cerr << "Actual: " << actual << std::endl;
  77. std::cerr << std::flush;
  78. throw std::runtime_error("Test failed");
  79. }
  80. }
  81. static std::string read_file(const std::string & path) {
  82. std::cerr << "# Reading: " << path << '\n' << std::flush;
  83. std::ifstream fs(path, std::ios_base::binary);
  84. if (!fs.is_open()) {
  85. fs = std::ifstream("../" + path, std::ios_base::binary);
  86. if (!fs.is_open()) {
  87. throw std::runtime_error("Failed to open file: " + path);
  88. }
  89. }
  90. fs.seekg(0, std::ios_base::end);
  91. auto size = fs.tellg();
  92. fs.seekg(0);
  93. std::string out;
  94. out.resize(static_cast<size_t>(size));
  95. fs.read(out.data(), static_cast<std::streamsize>(size));
  96. return out;
  97. }
  98. static common_chat_templates_ptr read_templates(const std::string & path) {
  99. return common_chat_templates_ptr(common_chat_templates_init(/* model= */ nullptr, read_file(path)));
  100. }
  101. static std::unique_ptr<llama_grammar> build_grammar(const std::string & grammar_str) {
  102. return std::unique_ptr<llama_grammar>(
  103. llama_grammar_init_impl(nullptr, grammar_str.c_str(), "root", false, nullptr, 0, nullptr, 0));
  104. }
  105. // TODO: extract to common helper (copied from test-grammar-integration.cpp)
  106. static bool match_string(const std::string & input, llama_grammar * grammar) {
  107. const auto cpts = unicode_cpts_from_utf8(input);
  108. auto & stacks_cur = llama_grammar_get_stacks(grammar);
  109. for (const auto & cpt : cpts) {
  110. llama_grammar_accept(grammar, cpt);
  111. if (stacks_cur.empty()) {
  112. // no stacks means that the grammar failed to match at this point
  113. return false;
  114. }
  115. }
  116. if (std::any_of(stacks_cur.begin(), stacks_cur.end(), [](const auto & stack) { return stack.empty(); })) {
  117. // An empty stack means that the grammar has been completed
  118. return true;
  119. }
  120. return false;
  121. }
  122. static std::string renormalize_json(const std::string & json_str) {
  123. try {
  124. auto json_obj = json::parse(json_str);
  125. return json_obj.dump();
  126. } catch (const std::exception & e) {
  127. std::cerr << "Failed to parse JSON: " << e.what() << '\n';
  128. return json_str;
  129. }
  130. }
  131. static void assert_msg_equals(const common_chat_msg & expected, const common_chat_msg & actual) {
  132. assert_equals(expected.role, actual.role);
  133. assert_equals(expected.content, actual.content);
  134. assert_equals(expected.content_parts.size(), actual.content_parts.size());
  135. for (size_t i = 0; i < expected.content_parts.size(); i++) {
  136. const auto & expected_part = expected.content_parts[i];
  137. const auto & actual_part = actual.content_parts[i];
  138. assert_equals(expected_part.type, actual_part.type);
  139. assert_equals(expected_part.text, actual_part.text);
  140. }
  141. assert_equals(expected.reasoning_content, actual.reasoning_content);
  142. assert_equals(expected.tool_calls.size(), actual.tool_calls.size());
  143. for (size_t i = 0; i < expected.tool_calls.size(); i++) {
  144. const auto & expected_tool_call = expected.tool_calls[i];
  145. const auto & actual_tool_call = actual.tool_calls[i];
  146. assert_equals(expected_tool_call.name, actual_tool_call.name);
  147. assert_equals(renormalize_json(expected_tool_call.arguments), renormalize_json(actual_tool_call.arguments));
  148. assert_equals(expected_tool_call.id, actual_tool_call.id);
  149. }
  150. }
  151. common_chat_tool special_function_tool {
  152. /* .name = */ "special_function",
  153. /* .description = */ "I'm special",
  154. /* .parameters = */ R"({
  155. "type": "object",
  156. "properties": {
  157. "arg1": {
  158. "type": "integer",
  159. "description": "The arg."
  160. }
  161. },
  162. "required": ["arg1"]
  163. })",
  164. };
  165. common_chat_tool python_tool {
  166. /* .name = */ "python",
  167. /* .description = */ "an ipython interpreter",
  168. /* .parameters = */ R"({
  169. "type": "object",
  170. "properties": {
  171. "code": {
  172. "type": "string",
  173. "description": "Python code to execute."
  174. }
  175. },
  176. "required": ["code"]
  177. })",
  178. };
  179. common_chat_tool code_interpreter_tool {
  180. /* .name = */ "code_interpreter",
  181. /* .description = */ "an ipython interpreter",
  182. /* .parameters = */ R"({
  183. "type": "object",
  184. "properties": {
  185. "code": {
  186. "type": "string",
  187. "description": "Python code to execute."
  188. }
  189. },
  190. "required": ["code"]
  191. })",
  192. };
  193. std::vector<common_chat_tool> tools { special_function_tool, python_tool };
  194. std::vector<common_chat_tool> llama_3_1_tools { special_function_tool, code_interpreter_tool };
  195. struct delta_data {
  196. std::string delta;
  197. common_chat_params params;
  198. };
  199. static delta_data init_delta(const struct common_chat_templates * tmpls, const std::vector<std::string> & end_tokens,
  200. const common_chat_msg & user_message,
  201. const common_chat_msg & delta_message,
  202. const std::vector<common_chat_tool> & tools,
  203. const common_chat_tool_choice & tool_choice) {
  204. common_chat_templates_inputs inputs;
  205. inputs.parallel_tool_calls = true;
  206. inputs.messages.push_back(user_message);
  207. inputs.tools = tools;
  208. inputs.tool_choice = tool_choice;
  209. auto params_prefix = common_chat_templates_apply(tmpls, inputs);
  210. inputs.messages.push_back(delta_message);
  211. inputs.add_generation_prompt = false;
  212. auto params_full = common_chat_templates_apply(tmpls, inputs);
  213. std::string prefix = params_prefix.prompt;
  214. std::string full = params_full.prompt;
  215. if (full == prefix) {
  216. throw std::runtime_error("Full message is the same as the prefix");
  217. }
  218. size_t common_prefix_length = 0;
  219. for (size_t i = 0; i < prefix.size() && i < full.size(); ++i) {
  220. if (prefix[i] != full[i]) {
  221. break;
  222. }
  223. if (prefix[i] == '<') {
  224. // DeepSeek R1's template (as of 20250209) adds a trailing <think> if add_generation_prompt,
  225. // but it removes thinking tags for past messages.
  226. // The prefix and full strings diverge at <think> vs. <|tool▁calls▁begin|>, we avoid consuming the leading <.
  227. continue;
  228. }
  229. common_prefix_length = i + 1;
  230. }
  231. auto delta = full.substr(common_prefix_length);
  232. // Strip end tokens
  233. for (const auto & end_token : end_tokens) {
  234. // rfind to find the last occurrence
  235. auto pos = delta.rfind(end_token);
  236. if (pos != std::string::npos) {
  237. delta = delta.substr(0, pos);
  238. break;
  239. }
  240. }
  241. return { delta, params_full };
  242. }
  243. /*
  244. Applies the template to 1 user message w/ add_generation_prompt=true, then w/ the test message w/ add_generation_prompt=false,
  245. gets the diff, removes any end tokens and parses the result w/ the grammar, checking that
  246. the parsed message is the same as the test_message
  247. */
  248. static void test_templates(const struct common_chat_templates * tmpls, const std::vector<std::string> & end_tokens,
  249. const common_chat_msg & test_message,
  250. const std::vector<common_chat_tool> & tools = {},
  251. const std::string & expected_delta = "",
  252. bool expect_grammar_triggered = true,
  253. bool test_grammar_if_triggered = true,
  254. common_reasoning_format reasoning_format = COMMON_REASONING_FORMAT_NONE) {
  255. common_chat_msg user_message;
  256. user_message.role = "user";
  257. user_message.content = "Hello, world!";
  258. for (const auto & tool_choice : std::vector<common_chat_tool_choice> {COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED}) {
  259. auto data = init_delta(tmpls, end_tokens, user_message, test_message, tools, tool_choice);
  260. if (!expected_delta.empty()) {
  261. assert_equals(expected_delta, data.delta);
  262. }
  263. if (expect_grammar_triggered) {
  264. common_chat_syntax syntax;
  265. syntax.format = data.params.format;
  266. syntax.reasoning_format = reasoning_format;
  267. const auto msg = common_chat_parse(data.delta, /* is_partial= */ false, syntax);
  268. assert_msg_equals(test_message, msg);
  269. }
  270. if (!test_message.tool_calls.empty()) {
  271. GGML_ASSERT(!data.params.grammar.empty());
  272. }
  273. if (!data.params.grammar.empty()) {
  274. auto grammar = build_grammar(data.params.grammar);
  275. if (!grammar) {
  276. throw std::runtime_error("Failed to build grammar");
  277. }
  278. auto earliest_trigger_pos = std::string::npos;
  279. auto constrained = data.delta;
  280. for (const auto & trigger : data.params.grammar_triggers) {
  281. size_t pos = std::string::npos;
  282. std::smatch match;
  283. switch (trigger.type) {
  284. case COMMON_GRAMMAR_TRIGGER_TYPE_WORD:
  285. {
  286. const auto & word = trigger.value;
  287. pos = constrained.find(word);
  288. break;
  289. }
  290. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN:
  291. {
  292. const auto & pattern = trigger.value;
  293. if (std::regex_search(constrained, match, std::regex(pattern))) {
  294. pos = match.position(1);
  295. }
  296. break;
  297. }
  298. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL:
  299. {
  300. const auto & pattern = trigger.value;
  301. if (std::regex_match(constrained, match, std::regex(pattern))) {
  302. auto mpos = std::string::npos;
  303. for (size_t i = 1; i < match.size(); ++i) {
  304. if (match[i].length() > 0) {
  305. mpos = match.position(i);
  306. break;
  307. }
  308. }
  309. if (mpos == std::string::npos) {
  310. mpos = match.position(0);
  311. }
  312. pos = mpos;
  313. }
  314. break;
  315. }
  316. default:
  317. throw std::runtime_error("Unknown trigger type");
  318. }
  319. if (pos == std::string::npos) {
  320. continue;
  321. }
  322. if (earliest_trigger_pos == std::string::npos || pos < earliest_trigger_pos) {
  323. earliest_trigger_pos = pos;
  324. }
  325. }
  326. auto grammar_triggered = false;
  327. if (earliest_trigger_pos != std::string::npos) {
  328. constrained = constrained.substr(earliest_trigger_pos);
  329. grammar_triggered = true;
  330. }
  331. if (data.params.grammar_lazy) {
  332. assert_equals(expect_grammar_triggered, grammar_triggered);
  333. }
  334. if (grammar_triggered && test_grammar_if_triggered && !match_string(constrained, grammar.get())) {
  335. throw std::runtime_error("Failed to match delta against grammar:\n\n" + data.delta +
  336. "\n\nConstrained: " + constrained +
  337. "\n\nGrammar: " + data.params.grammar);
  338. }
  339. }
  340. }
  341. }
  342. const common_chat_msg message_user {
  343. "user",
  344. "Hey there!",
  345. /* .content_parts = */ {},
  346. /* .tool_calls = */ {},
  347. /* .reasoning_content = */ "",
  348. /* .tool_name = */ "",
  349. /* .tool_call_id = */ "",
  350. };
  351. const common_chat_msg message_user_parts {
  352. "user",
  353. /* .content = */ "",
  354. /* .content_parts = */ {
  355. { "text", "Hey" },
  356. { "text", "there" },
  357. },
  358. /* .tool_calls = */ {},
  359. /* .reasoning_content = */ "",
  360. /* .tool_name = */ "",
  361. /* .tool_call_id = */ "",
  362. };
  363. static common_chat_msg simple_assist_msg(const std::string & content, const std::string & reasoning_content = "", const std::string & tool_name = "", const std::string & arguments = "", const std::string & id = "") {
  364. common_chat_msg msg;
  365. msg.role = "assistant";
  366. msg.content = content;
  367. msg.reasoning_content = reasoning_content;
  368. if (!tool_name.empty()) {
  369. msg.tool_calls.push_back({ tool_name, arguments, id });
  370. }
  371. return msg;
  372. }
  373. const common_chat_msg message_assist = simple_assist_msg("Hello, world!\nWhat's up?");
  374. const common_chat_msg message_assist_empty = simple_assist_msg("");
  375. const common_chat_msg message_assist_thoughts_unparsed_deepseek = simple_assist_msg("<think>I'm\nthinking</think>Hello, world!\nWhat's up?");
  376. const common_chat_msg message_assist_thoughts_unparsed_md = simple_assist_msg("<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```");
  377. const common_chat_msg message_assist_thoughts_unparsed_md_partial = simple_assist_msg("<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}");
  378. const common_chat_msg message_assist_thoughts_unparsed_r7b = simple_assist_msg("<|START_THINKING|>I'm\nthinking<|END_THINKING|>Hello, world!\nWhat's up?");
  379. const common_chat_msg message_assist_thoughts = simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking");
  380. const common_chat_msg message_assist_thoughts_unopened_unparsed = simple_assist_msg("I'm\nthinking</think>Hello, world!\nWhat's up?");
  381. const common_chat_msg message_assist_thoughts_no_content = simple_assist_msg("", "I'm\nthinking");
  382. const common_chat_msg message_assist_call = simple_assist_msg("", "", "special_function", "{\"arg1\": 1}");
  383. const common_chat_msg message_assist_call_content = simple_assist_msg("Hello, world!\nWhat's up?", "", "special_function", "{\"arg1\":1}");
  384. const common_chat_msg message_assist_call_empty_args = simple_assist_msg("", "", "special_function");
  385. const common_chat_msg message_assist_call_cutoff_args = simple_assist_msg("", "", "special_function", "{\"arg");
  386. const common_chat_msg message_assist_call_thoughts = simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\":1}");
  387. const common_chat_msg message_assist_call_thoughts_unparsed = simple_assist_msg("<think>I'm\nthinking</think>\n\n", "", "special_function", "{\"arg1\": 1}");
  388. const common_chat_msg message_assist_call_id = simple_assist_msg("", "", "special_function", "{\"arg1\":1}", /* .id = */ "123456789");
  389. const common_chat_msg message_assist_call_idx = simple_assist_msg("", "", "special_function", "{\"arg1\":1}", /* .id = */ "0");
  390. const common_chat_msg message_assist_thoughts_call_idx = simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}", /* id = */ "0");
  391. const common_chat_msg message_assist_call_python = simple_assist_msg("", "", "python", "{\"code\":\"print('hey')\"}");
  392. const common_chat_msg message_assist_call_python_lines = simple_assist_msg("", "", "python", "{\"code\":\"# This is a program:\\nprint('hey')\"}");
  393. const common_chat_msg message_assist_call_python_lines_unclosed = simple_assist_msg("", "", "python", "{\"code\":\"# This is a program:\\nprint('hey')");
  394. const common_chat_msg message_assist_call_code_interpreter = simple_assist_msg("", "", "code_interpreter", "{\"code\":\"print('hey')\"}");
  395. static void test_msgs_oaicompat_json_conversion() {
  396. printf("[%s]\n", __func__);
  397. std::vector<common_chat_msg> msgs{
  398. message_user,
  399. message_user_parts,
  400. message_assist_call,
  401. message_assist_call_thoughts,
  402. message_assist_call_thoughts_unparsed,
  403. message_assist_call_id,
  404. message_assist_call_idx,
  405. message_assist_call_python,
  406. message_assist_call_code_interpreter,
  407. };
  408. for (const auto & msg : msgs) {
  409. auto oai_json = common_chat_msgs_to_json_oaicompat<json>({msg});
  410. auto msgs2 = common_chat_msgs_parse_oaicompat(oai_json);
  411. assert_equals((size_t) 1, msgs2.size());
  412. auto msg2 = msgs2[0];
  413. assert_msg_equals(msg, msg2);
  414. }
  415. assert_equals(
  416. std::string(
  417. "[\n"
  418. " {\n"
  419. " \"role\": \"user\",\n"
  420. " \"content\": [\n"
  421. " {\n"
  422. " \"type\": \"text\",\n"
  423. " \"text\": \"Hey\"\n"
  424. " },\n"
  425. " {\n"
  426. " \"type\": \"text\",\n"
  427. " \"text\": \"there\"\n"
  428. " }\n"
  429. " ]\n"
  430. " }\n"
  431. "]"
  432. ),
  433. common_chat_msgs_to_json_oaicompat<json>({message_user_parts}).dump(2));
  434. assert_equals(
  435. std::string(
  436. "[\n"
  437. " {\n"
  438. " \"role\": \"assistant\",\n"
  439. " \"content\": null,\n"
  440. " \"tool_calls\": [\n"
  441. " {\n"
  442. " \"type\": \"function\",\n"
  443. " \"function\": {\n"
  444. " \"name\": \"python\",\n"
  445. " \"arguments\": \"{\\\"code\\\":\\\"print('hey')\\\"}\"\n"
  446. " }\n"
  447. " }\n"
  448. " ]\n"
  449. " }\n"
  450. "]"
  451. ),
  452. common_chat_msgs_to_json_oaicompat<json>({message_assist_call_python}).dump(2));
  453. auto res = common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\", \"tool_calls\": []}]"));
  454. assert_equals<size_t>(1, res.size());
  455. assert_equals<std::string>(res[0].role, "assistant");
  456. assert_equals(true, res[0].content.empty());
  457. assert_equals(true, res[0].tool_calls.empty());
  458. try {
  459. common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\"}]"));
  460. throw std::runtime_error("Expected exception");
  461. } catch (const std::exception & e) {
  462. if (std::string(e.what()).find("'content'") == std::string::npos) {
  463. throw std::runtime_error("Expected exception about missing 'content'");
  464. }
  465. }
  466. }
  467. static void test_tools_oaicompat_json_conversion() {
  468. printf("[%s]\n", __func__);
  469. std::vector<common_chat_tool> tools{
  470. special_function_tool,
  471. python_tool,
  472. code_interpreter_tool,
  473. };
  474. for (const auto & tool : tools) {
  475. auto oai_json = common_chat_tools_to_json_oaicompat<json>({tool});
  476. auto tools2 = common_chat_tools_parse_oaicompat(oai_json);
  477. assert_equals((size_t) 1, tools2.size());
  478. auto tool2 = tools2[0];
  479. assert_equals(tool.name, tool2.name);
  480. assert_equals(tool.description, tool2.description);
  481. assert_equals(json::parse(tool.parameters).dump(2), json::parse(tool2.parameters).dump(2));
  482. }
  483. assert_equals(
  484. std::string(
  485. "[\n"
  486. " {\n"
  487. " \"type\": \"function\",\n"
  488. " \"function\": {\n"
  489. " \"name\": \"special_function\",\n"
  490. " \"description\": \"I'm special\",\n"
  491. " \"parameters\": {\n"
  492. " \"type\": \"object\",\n"
  493. " \"properties\": {\n"
  494. " \"arg1\": {\n"
  495. " \"type\": \"integer\",\n"
  496. " \"description\": \"The arg.\"\n"
  497. " }\n"
  498. " },\n"
  499. " \"required\": [\n"
  500. " \"arg1\"\n"
  501. " ]\n"
  502. " }\n"
  503. " }\n"
  504. " }\n"
  505. "]"
  506. ),
  507. common_chat_tools_to_json_oaicompat<json>({special_function_tool}).dump(2));
  508. }
  509. static void test_template_output_parsers() {
  510. printf("[%s]\n", __func__);
  511. common_chat_templates_inputs inputs_no_tools;
  512. inputs_no_tools.messages = {message_user};
  513. common_chat_templates_inputs inputs_tools;
  514. inputs_tools.messages = {message_user};
  515. inputs_tools.tools = {special_function_tool};
  516. common_chat_templates_inputs inputs_tools_builtin;
  517. inputs_tools_builtin.messages = {message_user};
  518. inputs_tools_builtin.tools = {python_tool};
  519. {
  520. // Not supported yet
  521. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r-plus-tool_use.jinja");
  522. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  523. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  524. }
  525. {
  526. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r7b-12-2024-tool_use.jinja");
  527. std::vector<std::string> end_tokens{ "<|END_OF_TURN_TOKEN|>" };
  528. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  529. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  530. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B, params.format);
  531. assert_equals(false, params.thinking_forced_open);
  532. }
  533. assert_msg_equals(message_assist,
  534. common_chat_parse(
  535. "Hello, world!\nWhat's up?",
  536. /* is_partial= */ false,
  537. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  538. assert_msg_equals(message_assist,
  539. common_chat_parse(
  540. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  541. /* is_partial= */ false,
  542. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  543. assert_msg_equals(message_assist_thoughts,
  544. common_chat_parse(
  545. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  546. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  547. /* is_partial= */ false,
  548. {
  549. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  550. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  551. }));
  552. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  553. common_chat_parse(
  554. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  555. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  556. /* is_partial= */ false,
  557. {
  558. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  559. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  560. /* .reasoning_in_content = */ true,
  561. /* .thinking_forced_open = */ false,
  562. }));
  563. assert_msg_equals(message_assist_thoughts_unparsed_r7b,
  564. common_chat_parse(
  565. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  566. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  567. /* is_partial= */ false,
  568. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  569. assert_msg_equals(message_assist_thoughts,
  570. common_chat_parse(
  571. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  572. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  573. /* is_partial= */ false,
  574. {
  575. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  576. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  577. }));
  578. assert_msg_equals(message_assist_thoughts_call_idx,
  579. common_chat_parse(
  580. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  581. "<|START_ACTION|>[\n"
  582. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  583. "]<|END_ACTION|>",
  584. /* is_partial= */ false,
  585. {
  586. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  587. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  588. }));
  589. assert_msg_equals(message_assist_thoughts_no_content,
  590. common_chat_parse(
  591. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  592. "<|START_ACTION|>[\n"
  593. " {\"tool_call_id\": \"0\", \"tool_name\": \"special",
  594. /* is_partial= */ true,
  595. {
  596. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  597. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  598. }));
  599. test_templates(tmpls.get(), end_tokens, message_assist_call_idx, tools,
  600. "<|START_THINKING|><|END_THINKING|>"
  601. "<|START_ACTION|>[\n"
  602. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  603. "]<|END_ACTION|>",
  604. /* expect_grammar_triggered= */ true,
  605. /* test_grammar_if_triggered= */ true,
  606. COMMON_REASONING_FORMAT_DEEPSEEK);
  607. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  608. "<|START_RESPONSE|>Hello, world!\n"
  609. "What's up?<|END_RESPONSE|>",
  610. /* expect_grammar_triggered= */ false);
  611. }
  612. {
  613. auto tmpls = read_templates("models/templates/google-gemma-2-2b-it.jinja");
  614. std::vector<std::string> end_tokens{ "<end_of_turn>" };
  615. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  616. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  617. assert_equals(COMMON_CHAT_FORMAT_GENERIC,
  618. common_chat_templates_apply(
  619. read_templates("models/templates/microsoft-Phi-3.5-mini-instruct.jinja").get(),
  620. inputs_tools)
  621. .format);
  622. // Generic tool calls doesn't generate / parse content-only messages symmetrically.
  623. assert_equals(
  624. simple_assist_msg("{ \"tool_call\" : { \"name\" : \"t"),
  625. common_chat_parse(
  626. "{ \"tool_call\" : { \"name\" : \"t",
  627. /* is_partial= */ true,
  628. {
  629. /* .format = */ COMMON_CHAT_FORMAT_GENERIC,
  630. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  631. /* .reasoning_in_content = */ false,
  632. /* .thinking_forced_open = */ true,
  633. /* .parse_tool_calls = */ false,
  634. }));
  635. assert_equals(
  636. message_assist_empty,
  637. common_chat_parse(
  638. "{ \"tool_call\" : { \"name\" : \"t",
  639. /* is_partial= */ true,
  640. {COMMON_CHAT_FORMAT_GENERIC}));
  641. assert_equals(
  642. simple_assist_msg("", "", "puppeteer_screenshot", "{\"name\":\"servethehome_homepage\","),
  643. common_chat_parse(
  644. R"({"tool_call": {"name": "puppeteer_screenshot", "arguments": {"name": "servethehome_homepage",)",
  645. /* is_partial= */ true,
  646. {COMMON_CHAT_FORMAT_GENERIC}));
  647. assert_equals(
  648. message_assist_call_empty_args,
  649. common_chat_parse(
  650. "{ \"tool_call\" : { \"name\" : \"special_function\"",
  651. /* is_partial= */ true,
  652. {COMMON_CHAT_FORMAT_GENERIC}));
  653. assert_equals(
  654. message_assist_call_cutoff_args,
  655. common_chat_parse(
  656. "{ \"tool_call\" : { \"name\" : \"special_function\", \"arguments\" : { \"arg",
  657. /* is_partial= */ true,
  658. {COMMON_CHAT_FORMAT_GENERIC}));
  659. assert_msg_equals(message_assist,
  660. common_chat_parse(
  661. "{\n"
  662. " \"response\": \"Hello, world!\\nWhat's up?\"\n"
  663. "}",
  664. /* is_partial= */ false,
  665. {COMMON_CHAT_FORMAT_GENERIC}));
  666. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  667. "{\n"
  668. " \"tool_calls\": [\n"
  669. " {\n"
  670. " \"name\": \"special_function\",\n"
  671. " \"arguments\": {\n"
  672. " \"arg1\": 1\n"
  673. " },\n"
  674. " \"id\": \"123456789\"\n"
  675. " }\n"
  676. " ]\n"
  677. "}");
  678. }
  679. {
  680. auto tmpls = read_templates("models/templates/mistralai-Mistral-Nemo-Instruct-2407.jinja");
  681. std::vector<std::string> end_tokens{ "</s>" };
  682. assert_equals(COMMON_CHAT_FORMAT_MISTRAL_NEMO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  683. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  684. test_templates(
  685. tmpls.get(), end_tokens, message_assist_call_id, tools,
  686. "[TOOL_CALLS][{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, \"id\": \"123456789\"}]");
  687. }
  688. {
  689. auto tmpls = read_templates("models/templates/Qwen-QwQ-32B.jinja");
  690. std::vector<std::string> end_tokens{ "<|im_end|>" };
  691. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  692. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  693. }
  694. {
  695. auto tmpls = read_templates("models/templates/NousResearch-Hermes-2-Pro-Llama-3-8B-tool_use.jinja");
  696. std::vector<std::string> end_tokens{ "<|im_end|>" };
  697. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  698. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  699. assert_equals(
  700. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  701. common_chat_templates_apply(
  702. read_templates("models/templates/NousResearch-Hermes-3-Llama-3.1-8B-tool_use.jinja").get(),
  703. inputs_tools)
  704. .format);
  705. assert_equals(
  706. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  707. common_chat_templates_apply(
  708. read_templates("models/templates/Qwen-Qwen2.5-7B-Instruct.jinja").get(),
  709. inputs_tools)
  710. .format);
  711. // Test parsing
  712. assert_msg_equals(
  713. simple_assist_msg("", "", "python", ""),
  714. common_chat_parse(
  715. "```json\n"
  716. "<function_call> { \"name\" : \"python\"",
  717. /* is_partial= */ true,
  718. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  719. assert_msg_equals(
  720. simple_assist_msg("Let's call something\n"),
  721. common_chat_parse(
  722. "Let's call something\n"
  723. "<tool_call>{\"name\"",
  724. /* is_partial= */ true,
  725. {
  726. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  727. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  728. }));
  729. assert_msg_equals(
  730. simple_assist_msg("Let's call something\n"),
  731. common_chat_parse(
  732. "Let's call something\n"
  733. "<tool_call>{\"name",
  734. /* is_partial= */ true,
  735. {
  736. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  737. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  738. }));
  739. assert_msg_equals(message_assist_call_thoughts,
  740. common_chat_parse(
  741. // QwQ-32B's template adds a trailing <think> if add_generation_prompt
  742. "I'm\nthinking</think>\n"
  743. "<tool_call>{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}</tool_call>",
  744. /* is_partial= */ false,
  745. {
  746. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  747. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  748. /* .reasoning_in_content = */ false,
  749. /* .thinking_forced_open = */ true,
  750. }));
  751. assert_msg_equals(
  752. message_assist_call,
  753. common_chat_parse(
  754. "<tool_call>\n"
  755. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  756. "</tool_call>",
  757. /* is_partial= */ false,
  758. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  759. assert_msg_equals(message_assist_call_content,
  760. common_chat_parse(
  761. "Hello, world!\nWhat's up?<tool_call>\n"
  762. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  763. "</tool_call>",
  764. /* is_partial= */ false,
  765. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  766. assert_msg_equals(
  767. message_assist_call,
  768. common_chat_parse(
  769. "<function=special_function>{\"arg1\": 1}</function>",
  770. /* is_partial= */ false,
  771. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  772. assert_msg_equals(
  773. message_assist_call,
  774. common_chat_parse(
  775. "<function name=\"special_function\">\n"
  776. "{\"arg1\": 1}\n"
  777. "</function>",
  778. /* is_partial= */ false,
  779. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  780. assert_msg_equals(
  781. message_assist_call,
  782. common_chat_parse(
  783. "<tool>\n"
  784. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  785. "</tool>",
  786. /* is_partial= */ false,
  787. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  788. assert_msg_equals(
  789. message_assist_call,
  790. common_chat_parse(
  791. "<tools>\n"
  792. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  793. "</tools>",
  794. /* is_partial= */ false,
  795. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  796. assert_msg_equals(
  797. message_assist_call,
  798. common_chat_parse(
  799. "<response>\n"
  800. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  801. "</response>",
  802. /* is_partial= */ false,
  803. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  804. assert_msg_equals(
  805. message_assist_call,
  806. common_chat_parse(
  807. "```xml\n"
  808. "<response>\n"
  809. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  810. "</response>\n"
  811. "```",
  812. /* is_partial= */ false,
  813. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  814. assert_msg_equals(
  815. message_assist_call,
  816. common_chat_parse(
  817. "```xml\n"
  818. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  819. "```",
  820. /* is_partial= */ false,
  821. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  822. assert_msg_equals(
  823. message_assist_call,
  824. common_chat_parse(
  825. "```\n"
  826. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  827. "```",
  828. /* is_partial= */ false,
  829. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  830. assert_msg_equals(
  831. message_assist_call,
  832. common_chat_parse(
  833. "```\n"
  834. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  835. "```",
  836. /* is_partial= */ false,
  837. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  838. assert_msg_equals(
  839. message_assist_call,
  840. common_chat_parse(
  841. "```json\n"
  842. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  843. "```",
  844. /* is_partial= */ false,
  845. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  846. assert_msg_equals(
  847. message_assist_call,
  848. common_chat_parse(
  849. "```json\n"
  850. "\n"
  851. " <function_call> {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}} \n"
  852. " </function_call> \n"
  853. "``` ",
  854. /* is_partial= */ false,
  855. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  856. assert_msg_equals(
  857. message_assist_call,
  858. common_chat_parse(
  859. "<json>\n"
  860. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  861. "</json>",
  862. /* is_partial= */ false,
  863. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  864. assert_msg_equals(
  865. message_assist_call,
  866. common_chat_parse(
  867. "<xml>\n"
  868. " {\n"
  869. " \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}\n"
  870. " }\n"
  871. "</xml>",
  872. /* is_partial= */ false,
  873. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  874. assert_msg_equals(
  875. message_assist_call,
  876. common_chat_parse(
  877. "<JSON>\n"
  878. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  879. "</JSON>",
  880. /* is_partial= */ false,
  881. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  882. assert_msg_equals(
  883. message_assist_call,
  884. common_chat_parse(
  885. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  886. /* is_partial= */ false,
  887. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  888. assert_msg_equals(
  889. message_assist_call,
  890. common_chat_parse(
  891. "{\n \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  892. /* is_partial= */ false,
  893. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  894. // Test multiple tool calls
  895. common_chat_msg message_assist_multiple_calls;
  896. message_assist_multiple_calls.role = "assistant";
  897. message_assist_multiple_calls.content = "";
  898. message_assist_multiple_calls.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  899. message_assist_multiple_calls.tool_calls.push_back({"python", "{\"code\":\"print('hello')\"}", ""});
  900. assert_msg_equals(
  901. message_assist_multiple_calls,
  902. common_chat_parse(
  903. "<tool_call>\n"
  904. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  905. "</tool_call>\n"
  906. "<tool_call>\n"
  907. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('hello')\"}}\n"
  908. "</tool_call>",
  909. /* is_partial= */ false,
  910. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  911. assert_msg_equals(
  912. message_assist_multiple_calls,
  913. common_chat_parse(
  914. "<function=special_function>{\"arg1\": 1}</function>\n"
  915. "<function=python>{\"code\":\"print('hello')\"}</function>",
  916. /* is_partial= */ false,
  917. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  918. assert_msg_equals(
  919. simple_assist_msg(
  920. "This is not a tool call:",
  921. "",
  922. "special_function",
  923. "{\"arg1\": 1}"),
  924. common_chat_parse(
  925. "This is not a tool call:\n"
  926. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  927. /* is_partial= */ false,
  928. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  929. assert_msg_equals(message_assist,
  930. common_chat_parse(
  931. "Hello, world!\nWhat's up?",
  932. /* is_partial= */ false,
  933. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  934. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  935. common_chat_parse(
  936. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  937. /* is_partial= */ false,
  938. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  939. // assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  940. // common_chat_parse(
  941. // "I'm\nthinking</think>Hello, world!\nWhat's up?",
  942. // COMMON_CHAT_FORMAT_HERMES_2_PRO));
  943. assert_msg_equals(message_assist_thoughts,
  944. common_chat_parse(
  945. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  946. /* is_partial= */ false,
  947. {
  948. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  949. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  950. }));
  951. assert_msg_equals(message_assist_thoughts,
  952. common_chat_parse(
  953. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  954. /* is_partial= */ true,
  955. {
  956. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  957. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  958. }));
  959. assert_msg_equals(message_assist_thoughts_unparsed_md,
  960. common_chat_parse(
  961. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  962. /* is_partial= */ false,
  963. {
  964. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  965. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  966. /* .reasoning_in_content = */ true,
  967. /* .thinking_forced_open = */ false,
  968. /* .parse_tool_calls = */ false,
  969. }));
  970. assert_msg_equals(message_assist_thoughts_unparsed_md_partial,
  971. common_chat_parse(
  972. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  973. /* is_partial= */ true,
  974. {
  975. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  976. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  977. /* .reasoning_in_content = */ true,
  978. /* .thinking_forced_open = */ false,
  979. }));
  980. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  981. common_chat_parse(
  982. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  983. /* is_partial= */ false,
  984. {
  985. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  986. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  987. }));
  988. assert_msg_equals(message_assist_thoughts,
  989. common_chat_parse(
  990. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  991. /* is_partial= */ false,
  992. {
  993. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  994. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  995. /* .reasoning_in_content = */ false,
  996. /* .thinking_forced_open = */ true,
  997. }));
  998. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  999. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1000. "<tool_call>\n"
  1001. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1002. "</tool_call>");
  1003. // Test multiple tool calls with template
  1004. common_chat_msg message_assist_multiple_calls_template;
  1005. message_assist_multiple_calls_template.role = "assistant";
  1006. message_assist_multiple_calls_template.content = "";
  1007. message_assist_multiple_calls_template.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  1008. message_assist_multiple_calls_template.tool_calls.push_back({"python", "{\"code\":\"print('test')\"}", ""});
  1009. test_templates(tmpls.get(), end_tokens, message_assist_multiple_calls_template, tools,
  1010. "<tool_call>\n"
  1011. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1012. "</tool_call>\n"
  1013. "<tool_call>\n"
  1014. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('test')\"}}\n"
  1015. "</tool_call>");
  1016. test_templates(tmpls.get(), end_tokens, message_assist_call_python_lines, tools,
  1017. "<tool_call>\n"
  1018. "{\"name\": \"python\", \"arguments\": {\"code\":\"# This is a program:\\nprint('hey')\"}}\n"
  1019. "</tool_call>");
  1020. assert_msg_equals(
  1021. simple_assist_msg("", /* reasoning_content= */ "<tool_call>nah uhg</tool_call>"),
  1022. common_chat_parse(
  1023. "<think><tool_call>nah uhg</tool_call>",
  1024. /* is_partial= */ false,
  1025. {
  1026. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1027. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1028. }));
  1029. }
  1030. {
  1031. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.1-8B-Instruct.jinja");
  1032. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1033. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1034. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1035. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1036. common_chat_templates_apply(tmpls.get(), inputs_tools_builtin).format);
  1037. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1038. common_chat_templates_apply(
  1039. read_templates("models/templates/meta-llama-Llama-3.3-70B-Instruct.jinja").get(),
  1040. inputs_tools_builtin)
  1041. .format);
  1042. assert_equals(
  1043. message_assist_call,
  1044. common_chat_parse(
  1045. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}",
  1046. /* is_partial= */ false,
  1047. {COMMON_CHAT_FORMAT_LLAMA_3_X}));
  1048. // test_templates(tmpls.get(), end_tokens, message_assist, tools, R"(?)", /* expect_grammar_triggered= */ false);
  1049. test_templates(tmpls.get(), end_tokens, message_assist_call_code_interpreter, llama_3_1_tools,
  1050. "<|python_tag|>code_interpreter.call(code=\"print('hey')\")");
  1051. test_templates(tmpls.get(), end_tokens, message_assist_call_python, tools,
  1052. "<|python_tag|>python.call(code=\"print('hey')\")");
  1053. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1054. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1055. }
  1056. {
  1057. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.2-3B-Instruct.jinja");
  1058. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1059. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1060. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1061. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1062. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1063. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1064. }
  1065. {
  1066. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.1.jinja");
  1067. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1068. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1069. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1070. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1,
  1071. common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1072. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1073. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1074. for (auto is_partial : { false, true }) {
  1075. assert_equals(
  1076. message_assist_call,
  1077. common_chat_parse(
  1078. "<function=special_function>{\"arg1\": 1}</function>",
  1079. is_partial,
  1080. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1081. }
  1082. assert_equals(
  1083. message_assist_call,
  1084. common_chat_parse(
  1085. "<function=special_function>{\"arg1\": 1}<",
  1086. /* is_partial= */ true,
  1087. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1088. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1089. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1090. "<function=special_function>{\"arg1\": 1}</function>");
  1091. }
  1092. {
  1093. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.2.jinja");
  1094. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1095. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1096. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1097. assert_msg_equals(
  1098. simple_assist_msg(
  1099. "Hello, world!\nnono\nWhat's up?",
  1100. "",
  1101. "special_function",
  1102. "{\"arg1\": 1}"),
  1103. common_chat_parse(
  1104. "all\n"
  1105. "Hello, world!\n"
  1106. "nono\n"
  1107. "What's up?>>>special_function\n"
  1108. "{\"arg1\": 1}\n",
  1109. /* is_partial= */ false,
  1110. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1111. assert_msg_equals(message_assist_call_python_lines,
  1112. common_chat_parse(
  1113. "python\n"
  1114. "# This is a program:\n"
  1115. "print('hey')",
  1116. /* is_partial= */ false,
  1117. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1118. assert_msg_equals(message_assist_call_python_lines_unclosed,
  1119. common_chat_parse(
  1120. "python\n"
  1121. "# This is a program:\n"
  1122. "print('hey')",
  1123. /* is_partial= */ true,
  1124. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1125. assert_msg_equals(message_assist_call,
  1126. common_chat_parse(
  1127. "special_function\n"
  1128. "{\"arg1\": 1} \n ",
  1129. /* is_partial= */ false,
  1130. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1131. assert_msg_equals(message_assist,
  1132. common_chat_parse(
  1133. "all\n"
  1134. "Hello, world!\nWhat's up?",
  1135. /* is_partial= */ false,
  1136. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1137. test_templates(tmpls.get(), end_tokens, message_assist, {},
  1138. "all\n"
  1139. "Hello, world!\n"
  1140. "What's up?",
  1141. /* expect_grammar_triggered= */ false);
  1142. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1143. "special_function\n"
  1144. "{\"arg1\": 1}");
  1145. }
  1146. {
  1147. auto tmpls = read_templates("models/templates/fireworks-ai-llama-3-firefunction-v2.jinja");
  1148. std::vector<std::string> end_tokens{ "<|eot_id|>" };
  1149. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1150. assert_equals(COMMON_CHAT_FORMAT_FIREFUNCTION_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1151. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1152. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1153. " functools[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]");
  1154. }
  1155. {
  1156. // Original DeepSeek R1 template. Leaves <|tool▁calls▁begin|> and others unclosed. Our logic fixes the prompt.
  1157. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-R1-Distill-Llama-8B.jinja");
  1158. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1159. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  1160. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  1161. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, params.format);
  1162. assert_equals(true, params.thinking_forced_open);
  1163. }
  1164. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1165. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1166. assert_msg_equals(
  1167. simple_assist_msg("Hello, world!\nWhat's up?", "<think>I'm\nthinking"),
  1168. common_chat_parse(
  1169. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1170. /* is_partial= */ false,
  1171. {
  1172. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1173. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1174. /* .reasoning_in_content = */ false,
  1175. /* .thinking_forced_open = */ true,
  1176. }));
  1177. assert_msg_equals(
  1178. simple_assist_msg("", "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with"),
  1179. common_chat_parse(
  1180. "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with",
  1181. /* is_partial= */ true,
  1182. {
  1183. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1184. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1185. /* .reasoning_in_content = */ false,
  1186. /* .thinking_forced_open = */ true,
  1187. }));
  1188. assert_msg_equals(message_assist_thoughts,
  1189. common_chat_parse(
  1190. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1191. /* is_partial= */ false,
  1192. {
  1193. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1194. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1195. }));
  1196. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  1197. common_chat_parse(
  1198. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1199. /* is_partial= */ false,
  1200. {
  1201. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1202. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1203. }));
  1204. assert_msg_equals(message_assist_thoughts,
  1205. common_chat_parse(
  1206. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1207. /* is_partial= */ false,
  1208. {
  1209. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1210. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1211. /* .reasoning_in_content = */ false,
  1212. /* .thinking_forced_open = */ true,
  1213. }));
  1214. assert_msg_equals(message_assist_thoughts,
  1215. // Latest template update (ast of 20250209) adds a trailing <think>\n if add_generation_prompt is true.
  1216. common_chat_parse(
  1217. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1218. /* is_partial= */ false,
  1219. {
  1220. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1221. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1222. /* .reasoning_in_content = */ false,
  1223. /* .thinking_forced_open = */ true,
  1224. }));
  1225. // test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1226. // "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1227. // "```json\n"
  1228. // "{\"arg1\": 1}\n"
  1229. // // 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)
  1230. // "```<|tool▁call▁end|>",
  1231. // /* expect_grammar_triggered= */ true,
  1232. // /* test_grammar_if_triggered= */ false);
  1233. }
  1234. {
  1235. // Replacement DeepSeek R1 template. Makes the Distill Qwen 7B/32B models happy to call tools and all.
  1236. auto tmpls = read_templates("models/templates/llama-cpp-deepseek-r1.jinja");
  1237. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1238. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1239. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1240. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1241. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1242. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1243. common_chat_parse(
  1244. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1245. /* is_partial= */ false,
  1246. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1247. assert_msg_equals(message_assist_thoughts,
  1248. common_chat_parse(
  1249. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1250. /* is_partial= */ false,
  1251. {
  1252. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1253. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1254. }));
  1255. assert_msg_equals(message_assist_thoughts,
  1256. common_chat_parse(
  1257. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1258. /* is_partial= */ false,
  1259. {
  1260. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1261. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1262. /* .reasoning_in_content = */ false,
  1263. /* .thinking_forced_open = */ true,
  1264. }));
  1265. assert_msg_equals(message_assist_call_thoughts_unparsed,
  1266. common_chat_parse(
  1267. "<think>I'm\nthinking</think>\n\n"
  1268. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1269. "```json\n"
  1270. "{\"arg1\": 1}\n"
  1271. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1272. /* is_partial= */ false,
  1273. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1274. assert_msg_equals(message_assist_call,
  1275. common_chat_parse(
  1276. "<|tool▁calls|>function<|tool▁sep|>special_function\n"
  1277. "```json\n"
  1278. "{\"arg1\": 1}\n"
  1279. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1280. /* is_partial= */ false,
  1281. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1282. assert_msg_equals(message_assist_call_thoughts,
  1283. common_chat_parse(
  1284. "<think>I'm\nthinking</think>\n\n"
  1285. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1286. "```json\n"
  1287. "{\"arg1\": 1}\n"
  1288. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1289. /* is_partial= */ false,
  1290. {
  1291. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1292. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1293. }));
  1294. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1295. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1296. "```json\n"
  1297. "{\"arg1\": 1}\n"
  1298. "```<|tool▁call▁end|><|tool▁calls▁end|>");
  1299. }
  1300. }
  1301. static void test_msg_diffs_compute() {
  1302. printf("[%s]\n", __func__);
  1303. {
  1304. common_chat_msg msg1;
  1305. common_chat_msg msg2;
  1306. msg2.content = "Hello, world!";
  1307. common_chat_msg_diff diff;
  1308. diff.content_delta = "Hello, world!";
  1309. assert_equals(
  1310. {diff},
  1311. common_chat_msg_diff::compute_diffs(msg1, msg2));
  1312. }
  1313. {
  1314. common_chat_msg msg1;
  1315. msg1.content = "Hello,";
  1316. common_chat_msg msg2;
  1317. msg2.content = "Hello, world!";
  1318. common_chat_msg_diff diff;
  1319. diff.content_delta = " world!";
  1320. assert_equals(
  1321. {diff},
  1322. common_chat_msg_diff::compute_diffs(msg1, msg2));
  1323. }
  1324. {
  1325. common_chat_msg msg0;
  1326. common_chat_msg msg1;
  1327. msg1.tool_calls = { { "special_function", "{\"ar", /* .id = */ "123" } };
  1328. common_chat_msg msg2;
  1329. msg2.tool_calls = { { "special_function", "{\"arg1\": 1}", /* .id = */ "123" } };
  1330. common_chat_msg_diff diff01;
  1331. diff01.tool_call_index = 0;
  1332. diff01.tool_call_delta.name = "special_function";
  1333. diff01.tool_call_delta.id = "123";
  1334. diff01.tool_call_delta.arguments = "{\"ar";
  1335. assert_equals(
  1336. {diff01},
  1337. common_chat_msg_diff::compute_diffs(msg0, msg1));
  1338. common_chat_msg_diff diff12;
  1339. diff12.tool_call_index = 0;
  1340. // Note: neither id nor name change here.
  1341. diff12.tool_call_delta.arguments = "g1\": 1}";
  1342. assert_equals(
  1343. {diff12},
  1344. common_chat_msg_diff::compute_diffs(msg1, msg2));
  1345. }
  1346. {
  1347. common_chat_msg msg0;
  1348. common_chat_msg msg2;
  1349. msg2.tool_calls = {
  1350. { "f1", "{\"arg1\": 1}", /* .id = */ "123" },
  1351. { "f2", "{\"arg2\": 2}", /* .id = */ "222" },
  1352. };
  1353. common_chat_msg_diff diff1;
  1354. diff1.tool_call_index = 0;
  1355. diff1.tool_call_delta.name = "f1";
  1356. diff1.tool_call_delta.id = "123";
  1357. diff1.tool_call_delta.arguments = "{\"arg1\": 1}";
  1358. common_chat_msg_diff diff2;
  1359. diff2.tool_call_index = 1;
  1360. diff2.tool_call_delta.name = "f2";
  1361. diff2.tool_call_delta.id = "222";
  1362. diff2.tool_call_delta.arguments = "{\"arg2\": 2}";
  1363. assert_equals(
  1364. {diff1, diff2},
  1365. common_chat_msg_diff::compute_diffs(msg0, msg2));
  1366. }
  1367. }
  1368. int main(int argc, char ** argv) {
  1369. common_log_set_verbosity_thold(999);
  1370. // try {
  1371. #ifndef _WIN32
  1372. if (argc > 1) {
  1373. common_chat_templates_inputs inputs;
  1374. common_chat_msg msg;
  1375. msg.role = "user";
  1376. msg.content = "Hey";
  1377. inputs.messages = {msg};
  1378. inputs.tools = { special_function_tool };
  1379. std::cout << "| Template | Format |\n";
  1380. std::cout << "|----------|--------|\n";
  1381. for (int i = 1; i < argc; i++) {
  1382. try {
  1383. std::string path = argv[i];
  1384. if (path.rfind(".jinja") != path.size() - 6) {
  1385. std::cerr << "Skipping non-jinja file: " << path << '\n';
  1386. continue;
  1387. }
  1388. auto tmpls = read_templates(path);
  1389. auto parts = string_split(path, "/");
  1390. auto name = parts[parts.size() - 1];
  1391. auto format = common_chat_format_name(common_chat_templates_apply(tmpls.get(), inputs).format);
  1392. std::cout << "| " << name << " | " << format << " |\n";
  1393. } catch (const std::exception & e) {
  1394. std::cerr << "Failed to process " << argv[i] << ": " << e.what() << '\n';
  1395. }
  1396. }
  1397. } else
  1398. #endif
  1399. {
  1400. test_msg_diffs_compute();
  1401. test_msgs_oaicompat_json_conversion();
  1402. test_tools_oaicompat_json_conversion();
  1403. test_template_output_parsers();
  1404. std::cout << "\n[chat] All tests passed!" << '\n';
  1405. }
  1406. return 0;
  1407. // } catch (const std::exception & e) {
  1408. // std::cerr << "Error: " << e.what() << '\n';
  1409. // return 1;
  1410. // }
  1411. }