test-chat.cpp 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098
  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_thoughts_content = simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": 1}");
  389. const common_chat_msg message_assist_call_id = simple_assist_msg("", "", "special_function", "{\"arg1\":1}", /* .id = */ "123456789");
  390. const common_chat_msg message_assist_call_idx = simple_assist_msg("", "", "special_function", "{\"arg1\":1}", /* .id = */ "0");
  391. const common_chat_msg message_assist_thoughts_call_idx = simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}", /* id = */ "0");
  392. const common_chat_msg message_assist_call_python = simple_assist_msg("", "", "python", "{\"code\":\"print('hey')\"}");
  393. const common_chat_msg message_assist_call_python_lines = simple_assist_msg("", "", "python", "{\"code\":\"# This is a program:\\nprint('hey')\"}");
  394. const common_chat_msg message_assist_call_python_lines_unclosed = simple_assist_msg("", "", "python", "{\"code\":\"# This is a program:\\nprint('hey')");
  395. const common_chat_msg message_assist_call_code_interpreter = simple_assist_msg("", "", "code_interpreter", "{\"code\":\"print('hey')\"}");
  396. static void test_msgs_oaicompat_json_conversion() {
  397. printf("[%s]\n", __func__);
  398. std::vector<common_chat_msg> msgs{
  399. message_user,
  400. message_user_parts,
  401. message_assist_call,
  402. message_assist_call_thoughts,
  403. message_assist_call_thoughts_unparsed,
  404. message_assist_call_thoughts_content,
  405. message_assist_call_id,
  406. message_assist_call_idx,
  407. message_assist_call_python,
  408. message_assist_call_code_interpreter,
  409. };
  410. for (const auto & msg : msgs) {
  411. auto oai_json = common_chat_msgs_to_json_oaicompat<json>({msg});
  412. auto msgs2 = common_chat_msgs_parse_oaicompat(oai_json);
  413. assert_equals((size_t) 1, msgs2.size());
  414. auto msg2 = msgs2[0];
  415. assert_msg_equals(msg, msg2);
  416. }
  417. assert_equals(
  418. std::string(
  419. "[\n"
  420. " {\n"
  421. " \"role\": \"user\",\n"
  422. " \"content\": [\n"
  423. " {\n"
  424. " \"type\": \"text\",\n"
  425. " \"text\": \"Hey\"\n"
  426. " },\n"
  427. " {\n"
  428. " \"type\": \"text\",\n"
  429. " \"text\": \"there\"\n"
  430. " }\n"
  431. " ]\n"
  432. " }\n"
  433. "]"
  434. ),
  435. common_chat_msgs_to_json_oaicompat<json>({message_user_parts}).dump(2));
  436. assert_equals(
  437. std::string(
  438. "[\n"
  439. " {\n"
  440. " \"role\": \"assistant\",\n"
  441. " \"content\": null,\n"
  442. " \"tool_calls\": [\n"
  443. " {\n"
  444. " \"type\": \"function\",\n"
  445. " \"function\": {\n"
  446. " \"name\": \"python\",\n"
  447. " \"arguments\": \"{\\\"code\\\":\\\"print('hey')\\\"}\"\n"
  448. " }\n"
  449. " }\n"
  450. " ]\n"
  451. " }\n"
  452. "]"
  453. ),
  454. common_chat_msgs_to_json_oaicompat<json>({message_assist_call_python}).dump(2));
  455. auto res = common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\", \"tool_calls\": []}]"));
  456. assert_equals<size_t>(1, res.size());
  457. assert_equals<std::string>(res[0].role, "assistant");
  458. assert_equals(true, res[0].content.empty());
  459. assert_equals(true, res[0].tool_calls.empty());
  460. try {
  461. common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\"}]"));
  462. throw std::runtime_error("Expected exception");
  463. } catch (const std::exception & e) {
  464. if (std::string(e.what()).find("'content'") == std::string::npos) {
  465. throw std::runtime_error("Expected exception about missing 'content'");
  466. }
  467. }
  468. }
  469. static void test_tools_oaicompat_json_conversion() {
  470. printf("[%s]\n", __func__);
  471. std::vector<common_chat_tool> tools{
  472. special_function_tool,
  473. python_tool,
  474. code_interpreter_tool,
  475. };
  476. for (const auto & tool : tools) {
  477. auto oai_json = common_chat_tools_to_json_oaicompat<json>({tool});
  478. auto tools2 = common_chat_tools_parse_oaicompat(oai_json);
  479. assert_equals((size_t) 1, tools2.size());
  480. auto tool2 = tools2[0];
  481. assert_equals(tool.name, tool2.name);
  482. assert_equals(tool.description, tool2.description);
  483. assert_equals(json::parse(tool.parameters).dump(2), json::parse(tool2.parameters).dump(2));
  484. }
  485. assert_equals(
  486. std::string(
  487. "[\n"
  488. " {\n"
  489. " \"type\": \"function\",\n"
  490. " \"function\": {\n"
  491. " \"name\": \"special_function\",\n"
  492. " \"description\": \"I'm special\",\n"
  493. " \"parameters\": {\n"
  494. " \"type\": \"object\",\n"
  495. " \"properties\": {\n"
  496. " \"arg1\": {\n"
  497. " \"type\": \"integer\",\n"
  498. " \"description\": \"The arg.\"\n"
  499. " }\n"
  500. " },\n"
  501. " \"required\": [\n"
  502. " \"arg1\"\n"
  503. " ]\n"
  504. " }\n"
  505. " }\n"
  506. " }\n"
  507. "]"
  508. ),
  509. common_chat_tools_to_json_oaicompat<json>({special_function_tool}).dump(2));
  510. }
  511. static void test_template_output_parsers() {
  512. printf("[%s]\n", __func__);
  513. common_chat_templates_inputs inputs_no_tools;
  514. inputs_no_tools.messages = {message_user};
  515. common_chat_templates_inputs inputs_tools;
  516. inputs_tools.messages = {message_user};
  517. inputs_tools.tools = {special_function_tool};
  518. common_chat_templates_inputs inputs_tools_builtin;
  519. inputs_tools_builtin.messages = {message_user};
  520. inputs_tools_builtin.tools = {python_tool};
  521. {
  522. // Not supported yet
  523. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r-plus-tool_use.jinja");
  524. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  525. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  526. }
  527. {
  528. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r7b-12-2024-tool_use.jinja");
  529. std::vector<std::string> end_tokens{ "<|END_OF_TURN_TOKEN|>" };
  530. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  531. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  532. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B, params.format);
  533. assert_equals(false, params.thinking_forced_open);
  534. }
  535. assert_msg_equals(message_assist,
  536. common_chat_parse(
  537. "Hello, world!\nWhat's up?",
  538. /* is_partial= */ false,
  539. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  540. assert_msg_equals(message_assist,
  541. common_chat_parse(
  542. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  543. /* is_partial= */ false,
  544. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  545. assert_msg_equals(message_assist_thoughts,
  546. common_chat_parse(
  547. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  548. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  549. /* is_partial= */ false,
  550. {
  551. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  552. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  553. }));
  554. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  555. common_chat_parse(
  556. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  557. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  558. /* is_partial= */ false,
  559. {
  560. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  561. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  562. /* .reasoning_in_content = */ true,
  563. /* .thinking_forced_open = */ false,
  564. }));
  565. assert_msg_equals(message_assist_thoughts_unparsed_r7b,
  566. common_chat_parse(
  567. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  568. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  569. /* is_partial= */ false,
  570. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  571. assert_msg_equals(message_assist_thoughts,
  572. common_chat_parse(
  573. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  574. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  575. /* is_partial= */ false,
  576. {
  577. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  578. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  579. }));
  580. assert_msg_equals(message_assist_thoughts_call_idx,
  581. common_chat_parse(
  582. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  583. "<|START_ACTION|>[\n"
  584. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  585. "]<|END_ACTION|>",
  586. /* is_partial= */ false,
  587. {
  588. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  589. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  590. }));
  591. assert_msg_equals(message_assist_thoughts_no_content,
  592. common_chat_parse(
  593. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  594. "<|START_ACTION|>[\n"
  595. " {\"tool_call_id\": \"0\", \"tool_name\": \"special",
  596. /* is_partial= */ true,
  597. {
  598. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  599. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  600. }));
  601. test_templates(tmpls.get(), end_tokens, message_assist_call_idx, tools,
  602. "<|START_THINKING|><|END_THINKING|>"
  603. "<|START_ACTION|>[\n"
  604. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  605. "]<|END_ACTION|>",
  606. /* expect_grammar_triggered= */ true,
  607. /* test_grammar_if_triggered= */ true,
  608. COMMON_REASONING_FORMAT_DEEPSEEK);
  609. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  610. "<|START_RESPONSE|>Hello, world!\n"
  611. "What's up?<|END_RESPONSE|>",
  612. /* expect_grammar_triggered= */ false);
  613. }
  614. {
  615. auto tmpls = read_templates("models/templates/google-gemma-2-2b-it.jinja");
  616. std::vector<std::string> end_tokens{ "<end_of_turn>" };
  617. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  618. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  619. assert_equals(COMMON_CHAT_FORMAT_GENERIC,
  620. common_chat_templates_apply(
  621. read_templates("models/templates/microsoft-Phi-3.5-mini-instruct.jinja").get(),
  622. inputs_tools)
  623. .format);
  624. // Generic tool calls doesn't generate / parse content-only messages symmetrically.
  625. assert_equals(
  626. simple_assist_msg("{ \"tool_call\" : { \"name\" : \"t"),
  627. common_chat_parse(
  628. "{ \"tool_call\" : { \"name\" : \"t",
  629. /* is_partial= */ true,
  630. {
  631. /* .format = */ COMMON_CHAT_FORMAT_GENERIC,
  632. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  633. /* .reasoning_in_content = */ false,
  634. /* .thinking_forced_open = */ true,
  635. /* .parse_tool_calls = */ false,
  636. }));
  637. assert_equals(
  638. message_assist_empty,
  639. common_chat_parse(
  640. "{ \"tool_call\" : { \"name\" : \"t",
  641. /* is_partial= */ true,
  642. {COMMON_CHAT_FORMAT_GENERIC}));
  643. assert_equals(
  644. simple_assist_msg("", "", "puppeteer_screenshot", "{\"name\":\"servethehome_homepage\","),
  645. common_chat_parse(
  646. R"({"tool_call": {"name": "puppeteer_screenshot", "arguments": {"name": "servethehome_homepage",)",
  647. /* is_partial= */ true,
  648. {COMMON_CHAT_FORMAT_GENERIC}));
  649. assert_equals(
  650. message_assist_call_empty_args,
  651. common_chat_parse(
  652. "{ \"tool_call\" : { \"name\" : \"special_function\"",
  653. /* is_partial= */ true,
  654. {COMMON_CHAT_FORMAT_GENERIC}));
  655. assert_equals(
  656. message_assist_call_cutoff_args,
  657. common_chat_parse(
  658. "{ \"tool_call\" : { \"name\" : \"special_function\", \"arguments\" : { \"arg",
  659. /* is_partial= */ true,
  660. {COMMON_CHAT_FORMAT_GENERIC}));
  661. assert_msg_equals(message_assist,
  662. common_chat_parse(
  663. "{\n"
  664. " \"response\": \"Hello, world!\\nWhat's up?\"\n"
  665. "}",
  666. /* is_partial= */ false,
  667. {COMMON_CHAT_FORMAT_GENERIC}));
  668. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  669. "{\n"
  670. " \"tool_calls\": [\n"
  671. " {\n"
  672. " \"name\": \"special_function\",\n"
  673. " \"arguments\": {\n"
  674. " \"arg1\": 1\n"
  675. " },\n"
  676. " \"id\": \"123456789\"\n"
  677. " }\n"
  678. " ]\n"
  679. "}");
  680. }
  681. {
  682. auto tmpls = read_templates("models/templates/mistralai-Mistral-Nemo-Instruct-2407.jinja");
  683. std::vector<std::string> end_tokens{ "</s>" };
  684. assert_equals(COMMON_CHAT_FORMAT_MISTRAL_NEMO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  685. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  686. test_templates(
  687. tmpls.get(), end_tokens, message_assist_call_id, tools,
  688. "[TOOL_CALLS][{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, \"id\": \"123456789\"}]");
  689. }
  690. {
  691. auto tmpls = read_templates("models/templates/Qwen-QwQ-32B.jinja");
  692. std::vector<std::string> end_tokens{ "<|im_end|>" };
  693. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  694. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  695. }
  696. {
  697. auto tmpls = read_templates("models/templates/NousResearch-Hermes-2-Pro-Llama-3-8B-tool_use.jinja");
  698. std::vector<std::string> end_tokens{ "<|im_end|>" };
  699. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  700. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  701. assert_equals(
  702. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  703. common_chat_templates_apply(
  704. read_templates("models/templates/NousResearch-Hermes-3-Llama-3.1-8B-tool_use.jinja").get(),
  705. inputs_tools)
  706. .format);
  707. assert_equals(
  708. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  709. common_chat_templates_apply(
  710. read_templates("models/templates/Qwen-Qwen2.5-7B-Instruct.jinja").get(),
  711. inputs_tools)
  712. .format);
  713. // Test parsing
  714. assert_msg_equals(
  715. simple_assist_msg("", "", "python", ""),
  716. common_chat_parse(
  717. "```json\n"
  718. "<function_call> { \"name\" : \"python\"",
  719. /* is_partial= */ true,
  720. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  721. assert_msg_equals(
  722. simple_assist_msg("Let's call something\n"),
  723. common_chat_parse(
  724. "Let's call something\n"
  725. "<tool_call>{\"name\"",
  726. /* is_partial= */ true,
  727. {
  728. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  729. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  730. }));
  731. assert_msg_equals(
  732. simple_assist_msg("Let's call something\n"),
  733. common_chat_parse(
  734. "Let's call something\n"
  735. "<tool_call>{\"name",
  736. /* is_partial= */ true,
  737. {
  738. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  739. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  740. }));
  741. assert_msg_equals(message_assist_call_thoughts,
  742. common_chat_parse(
  743. // QwQ-32B's template adds a trailing <think> if add_generation_prompt
  744. "I'm\nthinking</think>\n"
  745. "<tool_call>{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}</tool_call>",
  746. /* is_partial= */ false,
  747. {
  748. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  749. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  750. /* .reasoning_in_content = */ false,
  751. /* .thinking_forced_open = */ true,
  752. }));
  753. assert_msg_equals(
  754. message_assist_call,
  755. common_chat_parse(
  756. "<tool_call>\n"
  757. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  758. "</tool_call>",
  759. /* is_partial= */ false,
  760. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  761. assert_msg_equals(message_assist_call_content,
  762. common_chat_parse(
  763. "Hello, world!\nWhat's up?<tool_call>\n"
  764. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  765. "</tool_call>",
  766. /* is_partial= */ false,
  767. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  768. assert_msg_equals(
  769. message_assist_call,
  770. common_chat_parse(
  771. "<function=special_function>{\"arg1\": 1}</function>",
  772. /* is_partial= */ false,
  773. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  774. assert_msg_equals(
  775. message_assist_call,
  776. common_chat_parse(
  777. "<function name=\"special_function\">\n"
  778. "{\"arg1\": 1}\n"
  779. "</function>",
  780. /* is_partial= */ false,
  781. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  782. assert_msg_equals(
  783. message_assist_call,
  784. common_chat_parse(
  785. "<tool>\n"
  786. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  787. "</tool>",
  788. /* is_partial= */ false,
  789. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  790. assert_msg_equals(
  791. message_assist_call,
  792. common_chat_parse(
  793. "<tools>\n"
  794. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  795. "</tools>",
  796. /* is_partial= */ false,
  797. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  798. assert_msg_equals(
  799. message_assist_call,
  800. common_chat_parse(
  801. "<response>\n"
  802. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  803. "</response>",
  804. /* is_partial= */ false,
  805. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  806. assert_msg_equals(
  807. message_assist_call,
  808. common_chat_parse(
  809. "```xml\n"
  810. "<response>\n"
  811. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  812. "</response>\n"
  813. "```",
  814. /* is_partial= */ false,
  815. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  816. assert_msg_equals(
  817. message_assist_call,
  818. common_chat_parse(
  819. "```xml\n"
  820. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  821. "```",
  822. /* is_partial= */ false,
  823. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  824. assert_msg_equals(
  825. message_assist_call,
  826. common_chat_parse(
  827. "```\n"
  828. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  829. "```",
  830. /* is_partial= */ false,
  831. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  832. assert_msg_equals(
  833. message_assist_call,
  834. common_chat_parse(
  835. "```\n"
  836. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  837. "```",
  838. /* is_partial= */ false,
  839. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  840. assert_msg_equals(
  841. message_assist_call,
  842. common_chat_parse(
  843. "```json\n"
  844. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  845. "```",
  846. /* is_partial= */ false,
  847. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  848. assert_msg_equals(
  849. message_assist_call,
  850. common_chat_parse(
  851. "```json\n"
  852. "\n"
  853. " <function_call> {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}} \n"
  854. " </function_call> \n"
  855. "``` ",
  856. /* is_partial= */ false,
  857. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  858. assert_msg_equals(
  859. message_assist_call,
  860. common_chat_parse(
  861. "<json>\n"
  862. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  863. "</json>",
  864. /* is_partial= */ false,
  865. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  866. assert_msg_equals(
  867. message_assist_call,
  868. common_chat_parse(
  869. "<xml>\n"
  870. " {\n"
  871. " \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}\n"
  872. " }\n"
  873. "</xml>",
  874. /* is_partial= */ false,
  875. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  876. assert_msg_equals(
  877. message_assist_call,
  878. common_chat_parse(
  879. "<JSON>\n"
  880. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  881. "</JSON>",
  882. /* is_partial= */ false,
  883. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  884. assert_msg_equals(
  885. message_assist_call,
  886. common_chat_parse(
  887. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  888. /* is_partial= */ false,
  889. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  890. assert_msg_equals(
  891. message_assist_call,
  892. common_chat_parse(
  893. "{\n \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  894. /* is_partial= */ false,
  895. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  896. // Test multiple tool calls
  897. common_chat_msg message_assist_multiple_calls;
  898. message_assist_multiple_calls.role = "assistant";
  899. message_assist_multiple_calls.content = "";
  900. message_assist_multiple_calls.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  901. message_assist_multiple_calls.tool_calls.push_back({"python", "{\"code\":\"print('hello')\"}", ""});
  902. assert_msg_equals(
  903. message_assist_multiple_calls,
  904. common_chat_parse(
  905. "<tool_call>\n"
  906. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  907. "</tool_call>\n"
  908. "<tool_call>\n"
  909. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('hello')\"}}\n"
  910. "</tool_call>",
  911. /* is_partial= */ false,
  912. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  913. assert_msg_equals(
  914. message_assist_multiple_calls,
  915. common_chat_parse(
  916. "<function=special_function>{\"arg1\": 1}</function>\n"
  917. "<function=python>{\"code\":\"print('hello')\"}</function>",
  918. /* is_partial= */ false,
  919. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  920. assert_msg_equals(
  921. simple_assist_msg(
  922. "This is not a tool call:",
  923. "",
  924. "special_function",
  925. "{\"arg1\": 1}"),
  926. common_chat_parse(
  927. "This is not a tool call:\n"
  928. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  929. /* is_partial= */ false,
  930. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  931. assert_msg_equals(message_assist,
  932. common_chat_parse(
  933. "Hello, world!\nWhat's up?",
  934. /* is_partial= */ false,
  935. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  936. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  937. common_chat_parse(
  938. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  939. /* is_partial= */ false,
  940. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  941. // assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  942. // common_chat_parse(
  943. // "I'm\nthinking</think>Hello, world!\nWhat's up?",
  944. // COMMON_CHAT_FORMAT_HERMES_2_PRO));
  945. assert_msg_equals(message_assist_thoughts,
  946. common_chat_parse(
  947. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  948. /* is_partial= */ false,
  949. {
  950. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  951. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  952. }));
  953. assert_msg_equals(message_assist_thoughts,
  954. common_chat_parse(
  955. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  956. /* is_partial= */ true,
  957. {
  958. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  959. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  960. }));
  961. assert_msg_equals(message_assist_thoughts_unparsed_md,
  962. common_chat_parse(
  963. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  964. /* is_partial= */ false,
  965. {
  966. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  967. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  968. /* .reasoning_in_content = */ true,
  969. /* .thinking_forced_open = */ false,
  970. /* .parse_tool_calls = */ false,
  971. }));
  972. assert_msg_equals(message_assist_thoughts_unparsed_md_partial,
  973. common_chat_parse(
  974. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  975. /* is_partial= */ true,
  976. {
  977. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  978. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  979. /* .reasoning_in_content = */ true,
  980. /* .thinking_forced_open = */ false,
  981. }));
  982. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  983. common_chat_parse(
  984. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  985. /* is_partial= */ false,
  986. {
  987. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  988. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  989. }));
  990. assert_msg_equals(message_assist_thoughts,
  991. common_chat_parse(
  992. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  993. /* is_partial= */ false,
  994. {
  995. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  996. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  997. /* .reasoning_in_content = */ false,
  998. /* .thinking_forced_open = */ true,
  999. }));
  1000. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1001. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1002. "<tool_call>\n"
  1003. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1004. "</tool_call>");
  1005. // Test multiple tool calls with template
  1006. common_chat_msg message_assist_multiple_calls_template;
  1007. message_assist_multiple_calls_template.role = "assistant";
  1008. message_assist_multiple_calls_template.content = "";
  1009. message_assist_multiple_calls_template.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  1010. message_assist_multiple_calls_template.tool_calls.push_back({"python", "{\"code\":\"print('test')\"}", ""});
  1011. test_templates(tmpls.get(), end_tokens, message_assist_multiple_calls_template, tools,
  1012. "<tool_call>\n"
  1013. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1014. "</tool_call>\n"
  1015. "<tool_call>\n"
  1016. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('test')\"}}\n"
  1017. "</tool_call>");
  1018. test_templates(tmpls.get(), end_tokens, message_assist_call_python_lines, tools,
  1019. "<tool_call>\n"
  1020. "{\"name\": \"python\", \"arguments\": {\"code\":\"# This is a program:\\nprint('hey')\"}}\n"
  1021. "</tool_call>");
  1022. assert_msg_equals(
  1023. simple_assist_msg("", /* reasoning_content= */ "<tool_call>nah uhg</tool_call>"),
  1024. common_chat_parse(
  1025. "<think><tool_call>nah uhg</tool_call>",
  1026. /* is_partial= */ false,
  1027. {
  1028. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1029. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1030. }));
  1031. }
  1032. {
  1033. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.1-8B-Instruct.jinja");
  1034. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1035. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1036. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1037. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1038. common_chat_templates_apply(tmpls.get(), inputs_tools_builtin).format);
  1039. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1040. common_chat_templates_apply(
  1041. read_templates("models/templates/meta-llama-Llama-3.3-70B-Instruct.jinja").get(),
  1042. inputs_tools_builtin)
  1043. .format);
  1044. assert_equals(
  1045. message_assist_call,
  1046. common_chat_parse(
  1047. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}",
  1048. /* is_partial= */ false,
  1049. {COMMON_CHAT_FORMAT_LLAMA_3_X}));
  1050. // test_templates(tmpls.get(), end_tokens, message_assist, tools, R"(?)", /* expect_grammar_triggered= */ false);
  1051. test_templates(tmpls.get(), end_tokens, message_assist_call_code_interpreter, llama_3_1_tools,
  1052. "<|python_tag|>code_interpreter.call(code=\"print('hey')\")");
  1053. test_templates(tmpls.get(), end_tokens, message_assist_call_python, tools,
  1054. "<|python_tag|>python.call(code=\"print('hey')\")");
  1055. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1056. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1057. }
  1058. {
  1059. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.2-3B-Instruct.jinja");
  1060. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1061. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1062. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1063. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1064. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1065. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1066. }
  1067. {
  1068. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.1.jinja");
  1069. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1070. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1071. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1072. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1,
  1073. common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1074. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1075. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1076. for (auto is_partial : { false, true }) {
  1077. assert_equals(
  1078. message_assist_call,
  1079. common_chat_parse(
  1080. "<function=special_function>{\"arg1\": 1}</function>",
  1081. is_partial,
  1082. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1083. }
  1084. assert_equals(
  1085. message_assist_call,
  1086. common_chat_parse(
  1087. "<function=special_function>{\"arg1\": 1}<",
  1088. /* is_partial= */ true,
  1089. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1090. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1091. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1092. "<function=special_function>{\"arg1\": 1}</function>");
  1093. }
  1094. {
  1095. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.2.jinja");
  1096. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1097. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1098. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1099. assert_msg_equals(
  1100. simple_assist_msg(
  1101. "Hello, world!\nnono\nWhat's up?",
  1102. "",
  1103. "special_function",
  1104. "{\"arg1\": 1}"),
  1105. common_chat_parse(
  1106. "all\n"
  1107. "Hello, world!\n"
  1108. "nono\n"
  1109. "What's up?>>>special_function\n"
  1110. "{\"arg1\": 1}\n",
  1111. /* is_partial= */ false,
  1112. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1113. assert_msg_equals(message_assist_call_python_lines,
  1114. common_chat_parse(
  1115. "python\n"
  1116. "# This is a program:\n"
  1117. "print('hey')",
  1118. /* is_partial= */ false,
  1119. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1120. assert_msg_equals(message_assist_call_python_lines_unclosed,
  1121. common_chat_parse(
  1122. "python\n"
  1123. "# This is a program:\n"
  1124. "print('hey')",
  1125. /* is_partial= */ true,
  1126. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1127. assert_msg_equals(message_assist_call,
  1128. common_chat_parse(
  1129. "special_function\n"
  1130. "{\"arg1\": 1} \n ",
  1131. /* is_partial= */ false,
  1132. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1133. assert_msg_equals(message_assist,
  1134. common_chat_parse(
  1135. "all\n"
  1136. "Hello, world!\nWhat's up?",
  1137. /* is_partial= */ false,
  1138. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1139. test_templates(tmpls.get(), end_tokens, message_assist, {},
  1140. "all\n"
  1141. "Hello, world!\n"
  1142. "What's up?",
  1143. /* expect_grammar_triggered= */ false);
  1144. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1145. "special_function\n"
  1146. "{\"arg1\": 1}");
  1147. }
  1148. {
  1149. auto tmpls = read_templates("models/templates/fireworks-ai-llama-3-firefunction-v2.jinja");
  1150. std::vector<std::string> end_tokens{ "<|eot_id|>" };
  1151. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1152. assert_equals(COMMON_CHAT_FORMAT_FIREFUNCTION_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1153. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1154. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1155. " functools[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]");
  1156. }
  1157. {
  1158. // Original DeepSeek R1 template. Leaves <|tool▁calls▁begin|> and others unclosed. Our logic fixes the prompt.
  1159. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-R1-Distill-Llama-8B.jinja");
  1160. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1161. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  1162. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  1163. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, params.format);
  1164. assert_equals(true, params.thinking_forced_open);
  1165. }
  1166. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1167. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1168. assert_msg_equals(
  1169. simple_assist_msg("Hello, world!\nWhat's up?", "<think>I'm\nthinking"),
  1170. common_chat_parse(
  1171. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1172. /* is_partial= */ false,
  1173. {
  1174. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1175. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1176. /* .reasoning_in_content = */ false,
  1177. /* .thinking_forced_open = */ true,
  1178. }));
  1179. assert_msg_equals(
  1180. simple_assist_msg("", "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with"),
  1181. common_chat_parse(
  1182. "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with",
  1183. /* is_partial= */ true,
  1184. {
  1185. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1186. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1187. /* .reasoning_in_content = */ false,
  1188. /* .thinking_forced_open = */ true,
  1189. }));
  1190. assert_msg_equals(message_assist_thoughts,
  1191. common_chat_parse(
  1192. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1193. /* is_partial= */ false,
  1194. {
  1195. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1196. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1197. }));
  1198. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  1199. common_chat_parse(
  1200. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1201. /* is_partial= */ false,
  1202. {
  1203. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1204. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1205. }));
  1206. assert_msg_equals(message_assist_thoughts,
  1207. common_chat_parse(
  1208. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1209. /* is_partial= */ false,
  1210. {
  1211. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1212. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1213. /* .reasoning_in_content = */ false,
  1214. /* .thinking_forced_open = */ true,
  1215. }));
  1216. assert_msg_equals(message_assist_thoughts,
  1217. // Latest template update (ast of 20250209) adds a trailing <think>\n if add_generation_prompt is true.
  1218. common_chat_parse(
  1219. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1220. /* is_partial= */ false,
  1221. {
  1222. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1223. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1224. /* .reasoning_in_content = */ false,
  1225. /* .thinking_forced_open = */ true,
  1226. }));
  1227. // test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1228. // "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1229. // "```json\n"
  1230. // "{\"arg1\": 1}\n"
  1231. // // 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)
  1232. // "```<|tool▁call▁end|>",
  1233. // /* expect_grammar_triggered= */ true,
  1234. // /* test_grammar_if_triggered= */ false);
  1235. }
  1236. {
  1237. // Replacement DeepSeek R1 template. Makes the Distill Qwen 7B/32B models happy to call tools and all.
  1238. auto tmpls = read_templates("models/templates/llama-cpp-deepseek-r1.jinja");
  1239. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1240. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1241. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1242. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1243. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1244. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1245. common_chat_parse(
  1246. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1247. /* is_partial= */ false,
  1248. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1249. assert_msg_equals(message_assist_thoughts,
  1250. common_chat_parse(
  1251. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1252. /* is_partial= */ false,
  1253. {
  1254. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1255. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1256. }));
  1257. assert_msg_equals(message_assist_thoughts,
  1258. common_chat_parse(
  1259. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1260. /* is_partial= */ false,
  1261. {
  1262. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1263. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1264. /* .reasoning_in_content = */ false,
  1265. /* .thinking_forced_open = */ true,
  1266. }));
  1267. assert_msg_equals(message_assist_call_thoughts_unparsed,
  1268. common_chat_parse(
  1269. "<think>I'm\nthinking</think>\n\n"
  1270. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1271. "```json\n"
  1272. "{\"arg1\": 1}\n"
  1273. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1274. /* is_partial= */ false,
  1275. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1276. assert_msg_equals(message_assist_call,
  1277. common_chat_parse(
  1278. "<|tool▁calls|>function<|tool▁sep|>special_function\n"
  1279. "```json\n"
  1280. "{\"arg1\": 1}\n"
  1281. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1282. /* is_partial= */ false,
  1283. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1284. assert_msg_equals(message_assist_call_thoughts,
  1285. common_chat_parse(
  1286. "<think>I'm\nthinking</think>\n\n"
  1287. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1288. "```json\n"
  1289. "{\"arg1\": 1}\n"
  1290. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1291. /* is_partial= */ false,
  1292. {
  1293. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1294. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1295. }));
  1296. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1297. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1298. "```json\n"
  1299. "{\"arg1\": 1}\n"
  1300. "```<|tool▁call▁end|><|tool▁calls▁end|>");
  1301. }
  1302. {
  1303. auto tmpls = read_templates("models/templates/ibm-granite-granite-3.3-2B-Instruct.jinja");
  1304. std::vector<std::string> end_tokens{ "<|end_of_text|>" };
  1305. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1306. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1307. // Test parsing regular content
  1308. assert_msg_equals(message_assist,
  1309. common_chat_parse(
  1310. "Hello, world!\nWhat's up?",
  1311. /* is_partial= */ false,
  1312. {COMMON_CHAT_FORMAT_GRANITE}));
  1313. // Test parsing content with thinking
  1314. assert_msg_equals(message_assist_thoughts,
  1315. common_chat_parse(
  1316. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1317. /* is_partial= */ false,
  1318. {
  1319. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1320. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1321. }));
  1322. // Test parsing tool calls
  1323. assert_msg_equals(message_assist_call,
  1324. common_chat_parse(
  1325. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]",
  1326. /* is_partial= */ false,
  1327. {COMMON_CHAT_FORMAT_GRANITE}));
  1328. // Test template generation for regular content
  1329. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1330. "Hello, world!\nWhat's up?",
  1331. /* expect_grammar_triggered= */ false);
  1332. // Test template generation for tool calls
  1333. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  1334. "{\n"
  1335. " \"tool_calls\": [\n"
  1336. " {\n"
  1337. " \"name\": \"special_function\",\n"
  1338. " \"arguments\": {\n"
  1339. " \"arg1\": 1\n"
  1340. " },\n"
  1341. " \"id\": \"123456789\"\n"
  1342. " }\n"
  1343. " ]\n"
  1344. "}",
  1345. /* expect_grammar_triggered= */ false
  1346. );
  1347. }
  1348. {
  1349. auto tmpls = read_templates("models/templates/openai-gpt-oss-120b.jinja");
  1350. std::vector<std::string> end_tokens{ "<|return|>", "<|call|>" };
  1351. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1352. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1353. assert_msg_equals(simple_assist_msg("", "I'm\nthink"),
  1354. common_chat_parse(
  1355. "<|channel|>analysis<|message|>I'm\nthink",
  1356. /* is_partial= */ true,
  1357. {
  1358. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1359. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1360. }));
  1361. assert_msg_equals(simple_assist_msg("", "I'm\nthinking"),
  1362. common_chat_parse(
  1363. "<|channel|>analysis<|message|>I'm\nthinking<|end|>",
  1364. /* is_partial= */ true,
  1365. {
  1366. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1367. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1368. }));
  1369. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1370. common_chat_parse(
  1371. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1372. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1373. /* is_partial= */ false,
  1374. {
  1375. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1376. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1377. }));
  1378. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1379. common_chat_parse(
  1380. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1381. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1",
  1382. /* is_partial= */ true,
  1383. {
  1384. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1385. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1386. }));
  1387. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1388. common_chat_parse(
  1389. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1390. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1391. /* is_partial= */ true,
  1392. {
  1393. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1394. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1395. }));
  1396. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1397. common_chat_parse(
  1398. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1399. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1400. /* is_partial= */ false,
  1401. {
  1402. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1403. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1404. }));
  1405. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1406. common_chat_parse(
  1407. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1408. "<|start|>assistant<|channel|>analysis to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1409. /* is_partial= */ false,
  1410. {
  1411. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1412. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1413. }));
  1414. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1415. common_chat_parse(
  1416. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1417. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?",
  1418. /* is_partial= */ true,
  1419. {
  1420. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1421. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1422. }));
  1423. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1424. common_chat_parse(
  1425. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1426. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?<|end|>"
  1427. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1428. /* is_partial= */ true,
  1429. {
  1430. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1431. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1432. }));
  1433. // Test parse_tool_calls == false
  1434. assert_msg_equals(
  1435. simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1436. common_chat_parse(
  1437. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1438. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1439. /* is_partial= */ true,
  1440. {
  1441. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1442. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1443. /* .reasoning_in_content = */ false,
  1444. /* .thinking_forced_open = */ false,
  1445. /* .parse_tool_calls = */ false,
  1446. }));
  1447. assert_msg_equals(
  1448. simple_assist_msg("", "I'm\nthinking"),
  1449. common_chat_parse(
  1450. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1451. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1452. /* is_partial= */ true,
  1453. {
  1454. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1455. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1456. /* .reasoning_in_content = */ false,
  1457. /* .thinking_forced_open = */ false,
  1458. /* .parse_tool_calls = */ false,
  1459. }));
  1460. assert_msg_equals(
  1461. simple_assist_msg("", "I'm\nthinking"),
  1462. common_chat_parse(
  1463. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1464. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1465. /* is_partial= */ false,
  1466. {
  1467. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1468. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1469. /* .reasoning_in_content = */ false,
  1470. /* .thinking_forced_open = */ false,
  1471. /* .parse_tool_calls = */ false,
  1472. }));
  1473. // Test reasoning formats
  1474. assert_msg_equals(
  1475. simple_assist_msg(
  1476. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1477. common_chat_parse(
  1478. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1479. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1480. /* is_partial= */ false,
  1481. {
  1482. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1483. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  1484. }));
  1485. assert_msg_equals(
  1486. simple_assist_msg(
  1487. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1488. common_chat_parse(
  1489. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1490. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1491. /* is_partial= */ false,
  1492. {
  1493. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1494. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1495. /* .reasoning_in_content = */ true,
  1496. }));
  1497. // Test tool calling in role header
  1498. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1499. common_chat_parse(
  1500. " to=functions.special_function<|channel|>commentary <|constrain|>json<|message|>{\"arg1\": 1}",
  1501. /* is_partial= */ false,
  1502. {
  1503. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1504. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1505. }));
  1506. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1507. common_chat_parse(
  1508. " to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1509. /* is_partial= */ false,
  1510. {
  1511. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1512. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1513. }));
  1514. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1515. common_chat_parse(
  1516. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1517. "<|start|>assistant to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1518. /* is_partial= */ false,
  1519. {
  1520. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1521. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1522. }));
  1523. }
  1524. {
  1525. // Seed-OSS format tests
  1526. auto tmpls = read_templates("models/templates/ByteDance-Seed-OSS.jinja");
  1527. std::vector<std::string> end_tokens{ "<seed:eos>" };
  1528. assert_equals(COMMON_CHAT_FORMAT_SEED_OSS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1529. assert_equals(COMMON_CHAT_FORMAT_SEED_OSS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1530. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1531. // Test simple reasoning content
  1532. assert_msg_equals(
  1533. simple_assist_msg("Hello, world!", "I'm thinking about the answer"),
  1534. common_chat_parse(
  1535. "<seed:think>I'm thinking about the answer</seed:think>Hello, world!",
  1536. /* is_partial= */ false,
  1537. {
  1538. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1539. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1540. }));
  1541. // Test budget reflection tags
  1542. common_chat_msg msg_budget_reflect;
  1543. msg_budget_reflect.role = "assistant";
  1544. msg_budget_reflect.content = "<seed:cot_budget_reflect>Token usage: 45/1000\nI should continue thinking to find the best solution.</seed:cot_budget_reflect>I need to calculate this step by step.";
  1545. msg_budget_reflect.reasoning_content = "Token usage: 45/1000\nI should continue thinking to find the best solution.";
  1546. assert_msg_equals(
  1547. msg_budget_reflect,
  1548. common_chat_parse(
  1549. "<seed:think>Token usage: 45/1000\nI should continue thinking to find the best solution.</seed:think>"
  1550. "<seed:cot_budget_reflect>Token usage: 45/1000\nI should continue thinking to find the best solution.</seed:cot_budget_reflect>"
  1551. "I need to calculate this step by step.",
  1552. /* is_partial= */ false,
  1553. {
  1554. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1555. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1556. }));
  1557. // Test tool calls with Seed-OSS format
  1558. common_chat_msg msg_tool_call;
  1559. msg_tool_call.role = "assistant";
  1560. msg_tool_call.tool_calls.push_back({"calculate_sum", "{\"numbers\": [1, 2, 3]}", ""});
  1561. assert_msg_equals(
  1562. msg_tool_call,
  1563. common_chat_parse(
  1564. "<seed:tool_call>\n"
  1565. "<function=calculate_sum>\n"
  1566. "<parameter=numbers>[1, 2, 3]</parameter>\n"
  1567. "</function>\n"
  1568. "</seed:tool_call>",
  1569. /* is_partial= */ false,
  1570. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1571. // Test reasoning + tool call combination
  1572. common_chat_msg msg_reasoning_tool;
  1573. msg_reasoning_tool.role = "assistant";
  1574. msg_reasoning_tool.content = "";
  1575. msg_reasoning_tool.reasoning_content = "I need to calculate the sum of these numbers";
  1576. msg_reasoning_tool.tool_calls.push_back({"calculate_sum", "{\"numbers\": [1, 2, 3]}", ""});
  1577. assert_msg_equals(
  1578. msg_reasoning_tool,
  1579. common_chat_parse(
  1580. "<seed:think>I need to calculate the sum of these numbers</seed:think>"
  1581. "<seed:tool_call>\n"
  1582. "<function=calculate_sum>\n"
  1583. "<parameter=numbers>[1, 2, 3]</parameter>\n"
  1584. "</function>\n"
  1585. "</seed:tool_call>",
  1586. /* is_partial= */ false,
  1587. {
  1588. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1589. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1590. }));
  1591. // Test deltas: the number of tool calls in partial parses should never decrease
  1592. std::string tool_msg = "<seed:tool_call>\n"
  1593. "<function=fun>\n"
  1594. "<parameter=smth>[1, 2, 3]</parameter>\n"
  1595. "</function>";
  1596. std::size_t previousToolCalls = 0;
  1597. for (std::size_t i = std::string("<seed:tool_call>").length(); i < tool_msg.length() - 1; i++) {
  1598. auto partial = tool_msg.substr(0, i);
  1599. auto partial_res = common_chat_parse(partial, true, { COMMON_CHAT_FORMAT_SEED_OSS, COMMON_REASONING_FORMAT_DEEPSEEK });
  1600. if (partial_res.tool_calls.size() < previousToolCalls) {
  1601. throw std::runtime_error("Tool call size decreased on partial: " + partial + " from " + std::to_string(previousToolCalls) + " to " + std::to_string(partial_res.tool_calls.size()));
  1602. }
  1603. previousToolCalls = partial_res.tool_calls.size();
  1604. }
  1605. // Test multiple parameters in tool call
  1606. common_chat_msg msg_multi_param;
  1607. msg_multi_param.role = "assistant";
  1608. msg_multi_param.tool_calls.push_back({"process_data", "{\"input\": \"test\", \"format\": \"json\"}", ""});
  1609. assert_msg_equals(
  1610. msg_multi_param,
  1611. common_chat_parse(
  1612. "<seed:tool_call>\n"
  1613. "<function=process_data>\n"
  1614. "<parameter=input>test</parameter>\n"
  1615. "<parameter=format>json</parameter>\n"
  1616. "</function>\n"
  1617. "</seed:tool_call>",
  1618. /* is_partial= */ false,
  1619. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1620. // Test partial parsing for incomplete tool call - don't actually add the call until parsing parameters is done
  1621. assert_msg_equals(
  1622. simple_assist_msg("", ""),
  1623. common_chat_parse(
  1624. "<seed:tool_call>\n"
  1625. "<function=calculate_sum>\n"
  1626. "<parameter=numbers>[1,\n",
  1627. /* is_partial= */ true,
  1628. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1629. // Test incomplete reasoning tag
  1630. assert_msg_equals(
  1631. simple_assist_msg("", "I was thinking"),
  1632. common_chat_parse(
  1633. "<seed:think>I was thinking",
  1634. /* is_partial= */ true,
  1635. {
  1636. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1637. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1638. }));
  1639. // Test content without reasoning
  1640. assert_msg_equals(
  1641. simple_assist_msg("This is a simple response without reasoning."),
  1642. common_chat_parse(
  1643. "This is a simple response without reasoning.",
  1644. /* is_partial= */ false,
  1645. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1646. }
  1647. {
  1648. auto tmpls = read_templates("models/templates/NVIDIA-Nemotron-Nano-v2.jinja");
  1649. std::vector<std::string> end_tokens{ "<SPECIAL_12>" };
  1650. assert_equals(COMMON_CHAT_FORMAT_NEMOTRON_V2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1651. assert_equals(COMMON_CHAT_FORMAT_NEMOTRON_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1652. // Test parsing regular content
  1653. assert_msg_equals(message_assist,
  1654. common_chat_parse(
  1655. "Hello, world!\nWhat's up?",
  1656. /* is_partial= */ false,
  1657. {COMMON_CHAT_FORMAT_NEMOTRON_V2}));
  1658. // Test parsing content with thinking
  1659. assert_msg_equals(message_assist_thoughts,
  1660. common_chat_parse(
  1661. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1662. /* is_partial= */ false,
  1663. {
  1664. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1665. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1666. }));
  1667. // Test parsing tool calls
  1668. assert_msg_equals(message_assist_call,
  1669. common_chat_parse(
  1670. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1671. /* is_partial= */ false,
  1672. {COMMON_CHAT_FORMAT_NEMOTRON_V2}));
  1673. // Test parsing tool calls with thinking
  1674. assert_msg_equals(message_assist_call_thoughts,
  1675. common_chat_parse(
  1676. "<think>I'm\nthinking</think><TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1677. /* is_partial= */ false,
  1678. {
  1679. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1680. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1681. }));
  1682. // Test tool calls with extra content
  1683. assert_msg_equals(message_assist_call_content,
  1684. common_chat_parse(
  1685. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>Hello, world!\nWhat's up?",
  1686. /* is_partial= */ false,
  1687. {COMMON_CHAT_FORMAT_NEMOTRON_V2}
  1688. ));
  1689. // Test tool calls with extra content AND thinking
  1690. assert_msg_equals(message_assist_call_thoughts_content,
  1691. common_chat_parse(
  1692. "<think>I'm\nthinking</think><TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>Hello, world!\nWhat's up?",
  1693. /* is_partial= */ false,
  1694. {
  1695. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1696. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1697. }));
  1698. // Test template generation for regular content
  1699. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1700. "Hello, world!\nWhat's up?\n",
  1701. /* expect_grammar_triggered= */ false);
  1702. // Test template generation for tool calls
  1703. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1704. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1705. /* expect_grammar_triggered= */ true
  1706. );
  1707. }
  1708. {
  1709. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-V3.1.jinja");
  1710. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1711. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  1712. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  1713. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_V3_1, params.format);
  1714. assert_equals(true, params.thinking_forced_open);
  1715. }
  1716. test_templates(tmpls.get(), end_tokens, message_assist, tools, "</think>Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1717. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "</think>Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1718. assert_msg_equals(
  1719. simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1720. common_chat_parse(
  1721. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1722. /* is_partial= */ false,
  1723. {
  1724. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1725. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1726. /* .reasoning_in_content = */ false,
  1727. /* .thinking_forced_open = */ true,
  1728. }));
  1729. // variant: thinking forced open, reasoning_format none
  1730. assert_msg_equals(
  1731. simple_assist_msg("REASONING</think>ok", ""),
  1732. common_chat_parse(
  1733. "REASONING</think>ok",
  1734. /* is_partial= */ false,
  1735. {
  1736. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1737. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  1738. /* .reasoning_in_content = */ false,
  1739. /* .thinking_forced_open = */ true,
  1740. /* .parse_tool_calls = */ true,
  1741. }));
  1742. // variant: happy path for when it works as the model card says it should
  1743. assert_msg_equals(
  1744. simple_assist_msg("", "", "get_time", "{\"city\":\"Tokyo\"}"),
  1745. common_chat_parse(
  1746. "<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1747. /* is_partial= */ false,
  1748. {
  1749. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1750. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1751. /* .reasoning_in_content = */ false,
  1752. /* .thinking_forced_open = */ false,
  1753. /* .parse_tool_calls = */ true,
  1754. }));
  1755. // variant: simple + thinking open
  1756. assert_msg_equals(
  1757. simple_assist_msg("", "REASONING", "get_time", "{\"city\":\"Tokyo\"}"),
  1758. common_chat_parse(
  1759. "REASONING</think><|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1760. /* is_partial= */ false,
  1761. {
  1762. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1763. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1764. /* .reasoning_in_content = */ false,
  1765. /* .thinking_forced_open = */ true,
  1766. /* .parse_tool_calls = */ true,
  1767. }));
  1768. // variant: simple + multiple tool calls
  1769. common_chat_msg message_assist_multiple_calls;
  1770. message_assist_multiple_calls.role = "assistant";
  1771. message_assist_multiple_calls.content = "CONTENT";
  1772. message_assist_multiple_calls.tool_calls.push_back({"get_time", "{\"city\":\"Paris\"}", ""});
  1773. message_assist_multiple_calls.tool_calls.push_back({"get_weather", "{\"city\":\"Paris\"}", ""});
  1774. assert_msg_equals(
  1775. message_assist_multiple_calls,
  1776. common_chat_parse(
  1777. "CONTENT<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Paris\"}<|tool▁call▁end|><|tool▁call▁begin|>get_weather<|tool▁sep|>{\"city\": \"Paris\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1778. /* is_partial= */ false,
  1779. {
  1780. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1781. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1782. /* .reasoning_in_content = */ false,
  1783. /* .thinking_forced_open = */ false,
  1784. /* .parse_tool_calls = */ true,
  1785. }));
  1786. // variant: thinking forced open + tool call in reasoning content
  1787. assert_msg_equals(
  1788. simple_assist_msg("", "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time2<|tool▁sep|>{\"city\": \"Tokyo2\"}<|tool▁call▁end|><|tool▁calls▁end|>REASONING", "get_time", "{\"city\":\"Tokyo\"}"),
  1789. common_chat_parse(
  1790. "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time2<|tool▁sep|>{\"city\": \"Tokyo2\"}<|tool▁call▁end|><|tool▁calls▁end|>REASONING</think><|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1791. /* is_partial= */ false,
  1792. {
  1793. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1794. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1795. /* .reasoning_in_content = */ false,
  1796. /* .thinking_forced_open = */ true,
  1797. /* .parse_tool_calls = */ true,
  1798. }));
  1799. // variant: thinking forced open + tool call in reasoning content + no closing think + not partial
  1800. // This is a bit of a fine tuning issue on the model's part IMO. It really should not be attempting
  1801. // to make tool calls in reasoning content according to the model card, but it does sometimes, so
  1802. // add the reasoning content as regular content and parse the tool calls.
  1803. assert_msg_equals(
  1804. simple_assist_msg("REASONING", "", "get_time", "{\"city\":\"Tokyo\"}"),
  1805. common_chat_parse(
  1806. "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1807. /* is_partial= */ false,
  1808. {
  1809. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1810. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1811. /* .reasoning_in_content = */ false,
  1812. /* .thinking_forced_open = */ true,
  1813. /* .parse_tool_calls = */ true,
  1814. }));
  1815. // variant: thinking forced open + tool call in reasoning content + no closing think + partial
  1816. assert_msg_equals(
  1817. simple_assist_msg("", "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>", "", ""),
  1818. common_chat_parse(
  1819. "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1820. /* is_partial= */ true,
  1821. {
  1822. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1823. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1824. /* .reasoning_in_content = */ false,
  1825. /* .thinking_forced_open = */ true,
  1826. /* .parse_tool_calls = */ true,
  1827. }));
  1828. // variant: thinking not forced open + missing reasoning + no tool calls
  1829. assert_msg_equals(
  1830. simple_assist_msg("CONTENT", ""),
  1831. common_chat_parse(
  1832. "CONTENT",
  1833. /* is_partial= */ false,
  1834. {
  1835. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1836. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1837. /* .reasoning_in_content = */ false,
  1838. /* .thinking_forced_open = */ false,
  1839. /* .parse_tool_calls = */ true,
  1840. }));
  1841. }
  1842. }
  1843. static void test_msg_diffs_compute() {
  1844. printf("[%s]\n", __func__);
  1845. {
  1846. common_chat_msg msg1;
  1847. common_chat_msg msg2;
  1848. msg2.content = "Hello, world!";
  1849. common_chat_msg_diff diff;
  1850. diff.content_delta = "Hello, world!";
  1851. assert_equals(
  1852. {diff},
  1853. common_chat_msg_diff::compute_diffs(msg1, msg2));
  1854. }
  1855. {
  1856. common_chat_msg msg1;
  1857. msg1.content = "Hello,";
  1858. common_chat_msg msg2;
  1859. msg2.content = "Hello, world!";
  1860. common_chat_msg_diff diff;
  1861. diff.content_delta = " world!";
  1862. assert_equals(
  1863. {diff},
  1864. common_chat_msg_diff::compute_diffs(msg1, msg2));
  1865. }
  1866. {
  1867. common_chat_msg msg0;
  1868. common_chat_msg msg1;
  1869. msg1.tool_calls = { { "special_function", "{\"ar", /* .id = */ "123" } };
  1870. common_chat_msg msg2;
  1871. msg2.tool_calls = { { "special_function", "{\"arg1\": 1}", /* .id = */ "123" } };
  1872. common_chat_msg_diff diff01;
  1873. diff01.tool_call_index = 0;
  1874. diff01.tool_call_delta.name = "special_function";
  1875. diff01.tool_call_delta.id = "123";
  1876. diff01.tool_call_delta.arguments = "{\"ar";
  1877. assert_equals(
  1878. {diff01},
  1879. common_chat_msg_diff::compute_diffs(msg0, msg1));
  1880. common_chat_msg_diff diff12;
  1881. diff12.tool_call_index = 0;
  1882. // Note: neither id nor name change here.
  1883. diff12.tool_call_delta.arguments = "g1\": 1}";
  1884. assert_equals(
  1885. {diff12},
  1886. common_chat_msg_diff::compute_diffs(msg1, msg2));
  1887. }
  1888. {
  1889. common_chat_msg msg0;
  1890. common_chat_msg msg2;
  1891. msg2.tool_calls = {
  1892. { "f1", "{\"arg1\": 1}", /* .id = */ "123" },
  1893. { "f2", "{\"arg2\": 2}", /* .id = */ "222" },
  1894. };
  1895. common_chat_msg_diff diff1;
  1896. diff1.tool_call_index = 0;
  1897. diff1.tool_call_delta.name = "f1";
  1898. diff1.tool_call_delta.id = "123";
  1899. diff1.tool_call_delta.arguments = "{\"arg1\": 1}";
  1900. common_chat_msg_diff diff2;
  1901. diff2.tool_call_index = 1;
  1902. diff2.tool_call_delta.name = "f2";
  1903. diff2.tool_call_delta.id = "222";
  1904. diff2.tool_call_delta.arguments = "{\"arg2\": 2}";
  1905. assert_equals(
  1906. {diff1, diff2},
  1907. common_chat_msg_diff::compute_diffs(msg0, msg2));
  1908. }
  1909. }
  1910. int main(int argc, char ** argv) {
  1911. common_log_set_verbosity_thold(999);
  1912. // try {
  1913. #ifndef _WIN32
  1914. if (argc > 1) {
  1915. common_chat_templates_inputs inputs;
  1916. common_chat_msg msg;
  1917. msg.role = "user";
  1918. msg.content = "Hey";
  1919. inputs.messages = {msg};
  1920. inputs.tools = { special_function_tool };
  1921. std::cout << "| Template | Format |\n";
  1922. std::cout << "|----------|--------|\n";
  1923. for (int i = 1; i < argc; i++) {
  1924. try {
  1925. std::string path = argv[i];
  1926. if (path.rfind(".jinja") != path.size() - 6) {
  1927. std::cerr << "Skipping non-jinja file: " << path << '\n';
  1928. continue;
  1929. }
  1930. auto tmpls = read_templates(path);
  1931. auto parts = string_split(path, "/");
  1932. auto name = parts[parts.size() - 1];
  1933. auto format = common_chat_format_name(common_chat_templates_apply(tmpls.get(), inputs).format);
  1934. std::cout << "| " << name << " | " << format << " |\n";
  1935. } catch (const std::exception & e) {
  1936. std::cerr << "Failed to process " << argv[i] << ": " << e.what() << '\n';
  1937. }
  1938. }
  1939. } else
  1940. #endif
  1941. {
  1942. test_msg_diffs_compute();
  1943. test_msgs_oaicompat_json_conversion();
  1944. test_tools_oaicompat_json_conversion();
  1945. test_template_output_parsers();
  1946. std::cout << "\n[chat] All tests passed!" << '\n';
  1947. }
  1948. return 0;
  1949. // } catch (const std::exception & e) {
  1950. // std::cerr << "Error: " << e.what() << '\n';
  1951. // return 1;
  1952. // }
  1953. }