test-chat.cpp 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  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. auto tmpls = read_templates("models/templates/ibm-granite-granite-3.3-2B-Instruct.jinja");
  1302. std::vector<std::string> end_tokens{ "<|end_of_text|>" };
  1303. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1304. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1305. // Test parsing regular content
  1306. assert_msg_equals(message_assist,
  1307. common_chat_parse(
  1308. "Hello, world!\nWhat's up?",
  1309. /* is_partial= */ false,
  1310. {COMMON_CHAT_FORMAT_GRANITE}));
  1311. // Test parsing content with thinking
  1312. assert_msg_equals(message_assist_thoughts,
  1313. common_chat_parse(
  1314. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1315. /* is_partial= */ false,
  1316. {
  1317. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1318. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1319. }));
  1320. // Test parsing tool calls
  1321. assert_msg_equals(message_assist_call,
  1322. common_chat_parse(
  1323. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]",
  1324. /* is_partial= */ false,
  1325. {COMMON_CHAT_FORMAT_GRANITE}));
  1326. // Test template generation for regular content
  1327. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1328. "Hello, world!\nWhat's up?",
  1329. /* expect_grammar_triggered= */ false);
  1330. // Test template generation for tool calls
  1331. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  1332. "{\n"
  1333. " \"tool_calls\": [\n"
  1334. " {\n"
  1335. " \"name\": \"special_function\",\n"
  1336. " \"arguments\": {\n"
  1337. " \"arg1\": 1\n"
  1338. " },\n"
  1339. " \"id\": \"123456789\"\n"
  1340. " }\n"
  1341. " ]\n"
  1342. "}",
  1343. /* expect_grammar_triggered= */ false
  1344. );
  1345. }
  1346. {
  1347. auto tmpls = read_templates("models/templates/openai-gpt-oss-120b.jinja");
  1348. std::vector<std::string> end_tokens{ "<|return|>", "<|call|>" };
  1349. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1350. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1351. assert_msg_equals(simple_assist_msg("", "I'm\nthink"),
  1352. common_chat_parse(
  1353. "<|channel|>analysis<|message|>I'm\nthink",
  1354. /* is_partial= */ true,
  1355. {
  1356. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1357. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1358. }));
  1359. assert_msg_equals(simple_assist_msg("", "I'm\nthinking"),
  1360. common_chat_parse(
  1361. "<|channel|>analysis<|message|>I'm\nthinking<|end|>",
  1362. /* is_partial= */ true,
  1363. {
  1364. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1365. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1366. }));
  1367. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1368. common_chat_parse(
  1369. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1370. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1371. /* is_partial= */ false,
  1372. {
  1373. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1374. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1375. }));
  1376. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1377. common_chat_parse(
  1378. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1379. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1",
  1380. /* is_partial= */ true,
  1381. {
  1382. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1383. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1384. }));
  1385. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1386. common_chat_parse(
  1387. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1388. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1389. /* is_partial= */ true,
  1390. {
  1391. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1392. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1393. }));
  1394. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1395. common_chat_parse(
  1396. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1397. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1398. /* is_partial= */ false,
  1399. {
  1400. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1401. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1402. }));
  1403. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1404. common_chat_parse(
  1405. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1406. "<|start|>assistant<|channel|>analysis to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1407. /* is_partial= */ false,
  1408. {
  1409. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1410. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1411. }));
  1412. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1413. common_chat_parse(
  1414. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1415. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?",
  1416. /* is_partial= */ true,
  1417. {
  1418. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1419. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1420. }));
  1421. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1422. common_chat_parse(
  1423. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1424. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?<|end|>"
  1425. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1426. /* is_partial= */ true,
  1427. {
  1428. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1429. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1430. }));
  1431. // Test parse_tool_calls == false
  1432. assert_msg_equals(
  1433. simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1434. common_chat_parse(
  1435. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1436. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1437. /* is_partial= */ true,
  1438. {
  1439. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1440. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1441. /* .reasoning_in_content = */ false,
  1442. /* .thinking_forced_open = */ false,
  1443. /* .parse_tool_calls = */ false,
  1444. }));
  1445. assert_msg_equals(
  1446. simple_assist_msg("", "I'm\nthinking"),
  1447. common_chat_parse(
  1448. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1449. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1450. /* is_partial= */ true,
  1451. {
  1452. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1453. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1454. /* .reasoning_in_content = */ false,
  1455. /* .thinking_forced_open = */ false,
  1456. /* .parse_tool_calls = */ false,
  1457. }));
  1458. assert_msg_equals(
  1459. simple_assist_msg("", "I'm\nthinking"),
  1460. common_chat_parse(
  1461. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1462. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1463. /* is_partial= */ false,
  1464. {
  1465. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1466. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1467. /* .reasoning_in_content = */ false,
  1468. /* .thinking_forced_open = */ false,
  1469. /* .parse_tool_calls = */ false,
  1470. }));
  1471. // Test reasoning formats
  1472. assert_msg_equals(
  1473. simple_assist_msg(
  1474. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1475. common_chat_parse(
  1476. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1477. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1478. /* is_partial= */ false,
  1479. {
  1480. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1481. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  1482. }));
  1483. assert_msg_equals(
  1484. simple_assist_msg(
  1485. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1486. common_chat_parse(
  1487. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1488. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1489. /* is_partial= */ false,
  1490. {
  1491. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1492. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1493. /* .reasoning_in_content = */ true,
  1494. }));
  1495. // Test tool calling in role header
  1496. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1497. common_chat_parse(
  1498. " to=functions.special_function<|channel|>commentary <|constrain|>json<|message|>{\"arg1\": 1}",
  1499. /* is_partial= */ false,
  1500. {
  1501. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1502. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1503. }));
  1504. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1505. common_chat_parse(
  1506. " to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1507. /* is_partial= */ false,
  1508. {
  1509. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1510. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1511. }));
  1512. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1513. common_chat_parse(
  1514. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1515. "<|start|>assistant to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1516. /* is_partial= */ false,
  1517. {
  1518. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1519. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1520. }));
  1521. }
  1522. }
  1523. static void test_msg_diffs_compute() {
  1524. printf("[%s]\n", __func__);
  1525. {
  1526. common_chat_msg msg1;
  1527. common_chat_msg msg2;
  1528. msg2.content = "Hello, world!";
  1529. common_chat_msg_diff diff;
  1530. diff.content_delta = "Hello, world!";
  1531. assert_equals(
  1532. {diff},
  1533. common_chat_msg_diff::compute_diffs(msg1, msg2));
  1534. }
  1535. {
  1536. common_chat_msg msg1;
  1537. msg1.content = "Hello,";
  1538. common_chat_msg msg2;
  1539. msg2.content = "Hello, world!";
  1540. common_chat_msg_diff diff;
  1541. diff.content_delta = " world!";
  1542. assert_equals(
  1543. {diff},
  1544. common_chat_msg_diff::compute_diffs(msg1, msg2));
  1545. }
  1546. {
  1547. common_chat_msg msg0;
  1548. common_chat_msg msg1;
  1549. msg1.tool_calls = { { "special_function", "{\"ar", /* .id = */ "123" } };
  1550. common_chat_msg msg2;
  1551. msg2.tool_calls = { { "special_function", "{\"arg1\": 1}", /* .id = */ "123" } };
  1552. common_chat_msg_diff diff01;
  1553. diff01.tool_call_index = 0;
  1554. diff01.tool_call_delta.name = "special_function";
  1555. diff01.tool_call_delta.id = "123";
  1556. diff01.tool_call_delta.arguments = "{\"ar";
  1557. assert_equals(
  1558. {diff01},
  1559. common_chat_msg_diff::compute_diffs(msg0, msg1));
  1560. common_chat_msg_diff diff12;
  1561. diff12.tool_call_index = 0;
  1562. // Note: neither id nor name change here.
  1563. diff12.tool_call_delta.arguments = "g1\": 1}";
  1564. assert_equals(
  1565. {diff12},
  1566. common_chat_msg_diff::compute_diffs(msg1, msg2));
  1567. }
  1568. {
  1569. common_chat_msg msg0;
  1570. common_chat_msg msg2;
  1571. msg2.tool_calls = {
  1572. { "f1", "{\"arg1\": 1}", /* .id = */ "123" },
  1573. { "f2", "{\"arg2\": 2}", /* .id = */ "222" },
  1574. };
  1575. common_chat_msg_diff diff1;
  1576. diff1.tool_call_index = 0;
  1577. diff1.tool_call_delta.name = "f1";
  1578. diff1.tool_call_delta.id = "123";
  1579. diff1.tool_call_delta.arguments = "{\"arg1\": 1}";
  1580. common_chat_msg_diff diff2;
  1581. diff2.tool_call_index = 1;
  1582. diff2.tool_call_delta.name = "f2";
  1583. diff2.tool_call_delta.id = "222";
  1584. diff2.tool_call_delta.arguments = "{\"arg2\": 2}";
  1585. assert_equals(
  1586. {diff1, diff2},
  1587. common_chat_msg_diff::compute_diffs(msg0, msg2));
  1588. }
  1589. }
  1590. int main(int argc, char ** argv) {
  1591. common_log_set_verbosity_thold(999);
  1592. // try {
  1593. #ifndef _WIN32
  1594. if (argc > 1) {
  1595. common_chat_templates_inputs inputs;
  1596. common_chat_msg msg;
  1597. msg.role = "user";
  1598. msg.content = "Hey";
  1599. inputs.messages = {msg};
  1600. inputs.tools = { special_function_tool };
  1601. std::cout << "| Template | Format |\n";
  1602. std::cout << "|----------|--------|\n";
  1603. for (int i = 1; i < argc; i++) {
  1604. try {
  1605. std::string path = argv[i];
  1606. if (path.rfind(".jinja") != path.size() - 6) {
  1607. std::cerr << "Skipping non-jinja file: " << path << '\n';
  1608. continue;
  1609. }
  1610. auto tmpls = read_templates(path);
  1611. auto parts = string_split(path, "/");
  1612. auto name = parts[parts.size() - 1];
  1613. auto format = common_chat_format_name(common_chat_templates_apply(tmpls.get(), inputs).format);
  1614. std::cout << "| " << name << " | " << format << " |\n";
  1615. } catch (const std::exception & e) {
  1616. std::cerr << "Failed to process " << argv[i] << ": " << e.what() << '\n';
  1617. }
  1618. }
  1619. } else
  1620. #endif
  1621. {
  1622. test_msg_diffs_compute();
  1623. test_msgs_oaicompat_json_conversion();
  1624. test_tools_oaicompat_json_conversion();
  1625. test_template_output_parsers();
  1626. std::cout << "\n[chat] All tests passed!" << '\n';
  1627. }
  1628. return 0;
  1629. // } catch (const std::exception & e) {
  1630. // std::cerr << "Error: " << e.what() << '\n';
  1631. // return 1;
  1632. // }
  1633. }