1
0

test-chat.cpp 180 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724
  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 <functional>
  16. #include <string>
  17. using json = nlohmann::ordered_json;
  18. static std::ostream & operator<<(std::ostream & os, const common_chat_msg_diff & diff) {
  19. os << "{ content_delta: " << diff.content_delta << "; ";
  20. os << "reasoning_content_delta: " << diff.reasoning_content_delta << "; ";
  21. if (diff.tool_call_index != std::string::npos) {
  22. os << "tool_call_index: " << diff.tool_call_index << "; ";
  23. os << "tool_call_delta.name: " << diff.tool_call_delta.name << "; ";
  24. os << "tool_call_delta.id: " << diff.tool_call_delta.id << "; ";
  25. os << "tool_call_delta.arguments: " << diff.tool_call_delta.arguments << "; ";
  26. }
  27. os << "}";
  28. return os;
  29. }
  30. // operator<< for vector<common_chat_msg_diff>:
  31. static std::ostream & operator<<(std::ostream & os, const std::vector<common_chat_msg_diff> & diffs) {
  32. os << "[\n";
  33. for (const auto & diff : diffs) {
  34. os << " " << diff << ",\n";
  35. }
  36. os << "]";
  37. return os;
  38. }
  39. static std::ostream & operator<<(std::ostream & os, const common_chat_msg & msg) {
  40. os << "{ role: " << msg.role << "; ";
  41. os << "content: " << msg.content << "; ";
  42. os << "content_parts: [\n";
  43. for (const auto & part : msg.content_parts) {
  44. os << " { type: " << part.type << "; text: " << part.text << " },\n";
  45. }
  46. os << "]; ";
  47. os << "reasoning_content: " << msg.reasoning_content << "; ";
  48. os << "tool_calls: [\n";
  49. for (const auto & tool_call : msg.tool_calls) {
  50. os << " { name: " << tool_call.name << "; arguments: " << tool_call.arguments << "; id: " << tool_call.id << " },\n";
  51. }
  52. os << "]";
  53. os << "}";
  54. return os;
  55. }
  56. template <class T> static bool equals(const T & expected, const T & actual) {
  57. return expected == actual;
  58. }
  59. static common_chat_msg normalize(const common_chat_msg & msg) {
  60. common_chat_msg normalized = msg;
  61. for (auto & tool_call : normalized.tool_calls) {
  62. try {
  63. tool_call.arguments = json::parse(tool_call.arguments).dump();
  64. } catch (const std::exception &) {
  65. // Do nothing
  66. }
  67. }
  68. return normalized;
  69. }
  70. template <>
  71. bool equals(const common_chat_msg & expected, const common_chat_msg & actual) {
  72. return normalize(expected) == normalize(actual);
  73. }
  74. template <class T> static void assert_equals(const T & expected, const T & actual) {
  75. if (!equals(expected, actual)) {
  76. std::cerr << "Expected: " << expected << std::endl;
  77. std::cerr << "Actual: " << actual << std::endl;
  78. std::cerr << std::flush;
  79. throw std::runtime_error("Test failed");
  80. }
  81. }
  82. static std::string read_file(const std::string & path) {
  83. std::cerr << "# Reading: " << path << '\n' << std::flush;
  84. std::ifstream fs(path, std::ios_base::binary);
  85. if (!fs.is_open()) {
  86. fs = std::ifstream("../" + path, std::ios_base::binary);
  87. if (!fs.is_open()) {
  88. throw std::runtime_error("Failed to open file: " + path);
  89. }
  90. }
  91. fs.seekg(0, std::ios_base::end);
  92. auto size = fs.tellg();
  93. fs.seekg(0);
  94. std::string out;
  95. out.resize(static_cast<size_t>(size));
  96. fs.read(out.data(), static_cast<std::streamsize>(size));
  97. return out;
  98. }
  99. static common_chat_templates_ptr read_templates(const std::string & path) {
  100. return common_chat_templates_ptr(common_chat_templates_init(/* model= */ nullptr, read_file(path)));
  101. }
  102. static std::unique_ptr<llama_grammar> build_grammar(const std::string & grammar_str) {
  103. return std::unique_ptr<llama_grammar>(
  104. llama_grammar_init_impl(nullptr, grammar_str.c_str(), "root", false, nullptr, 0, nullptr, 0));
  105. }
  106. // TODO: extract to common helper (copied from test-grammar-integration.cpp)
  107. static bool match_string(const std::string & input, llama_grammar * grammar) {
  108. const auto cpts = unicode_cpts_from_utf8(input);
  109. auto & stacks_cur = llama_grammar_get_stacks(grammar);
  110. for (const auto & cpt : cpts) {
  111. llama_grammar_accept(grammar, cpt);
  112. if (stacks_cur.empty()) {
  113. // no stacks means that the grammar failed to match at this point
  114. return false;
  115. }
  116. }
  117. if (std::any_of(stacks_cur.begin(), stacks_cur.end(), [](const auto & stack) { return stack.empty(); })) {
  118. // An empty stack means that the grammar has been completed
  119. return true;
  120. }
  121. return false;
  122. }
  123. static std::string renormalize_json(const std::string & json_str) {
  124. try {
  125. auto json_obj = json::parse(json_str);
  126. return json_obj.dump();
  127. } catch (const std::exception & e) {
  128. std::cerr << "Failed to parse JSON: " << e.what() << '\n';
  129. return json_str;
  130. }
  131. }
  132. static void assert_msg_equals(const common_chat_msg & expected, const common_chat_msg & actual, bool ignore_whitespace_differences = false) {
  133. assert_equals(expected.role, actual.role);
  134. if (ignore_whitespace_differences) {
  135. assert_equals(string_strip(expected.content), string_strip(actual.content));
  136. } else {
  137. assert_equals(expected.content, actual.content);
  138. }
  139. assert_equals(expected.content_parts.size(), actual.content_parts.size());
  140. for (size_t i = 0; i < expected.content_parts.size(); i++) {
  141. const auto & expected_part = expected.content_parts[i];
  142. const auto & actual_part = actual.content_parts[i];
  143. assert_equals(expected_part.type, actual_part.type);
  144. if (ignore_whitespace_differences) {
  145. assert_equals(string_strip(expected_part.text), string_strip(actual_part.text));
  146. } else {
  147. assert_equals(expected_part.text, actual_part.text);
  148. }
  149. }
  150. if (ignore_whitespace_differences) {
  151. assert_equals(string_strip(expected.reasoning_content), string_strip(actual.reasoning_content));
  152. } else {
  153. assert_equals(expected.reasoning_content, actual.reasoning_content);
  154. }
  155. assert_equals(expected.tool_calls.size(), actual.tool_calls.size());
  156. for (size_t i = 0; i < expected.tool_calls.size(); i++) {
  157. const auto & expected_tool_call = expected.tool_calls[i];
  158. const auto & actual_tool_call = actual.tool_calls[i];
  159. assert_equals(expected_tool_call.name, actual_tool_call.name);
  160. assert_equals(renormalize_json(expected_tool_call.arguments), renormalize_json(actual_tool_call.arguments));
  161. assert_equals(expected_tool_call.id, actual_tool_call.id);
  162. }
  163. }
  164. common_chat_tool special_function_tool {
  165. /* .name = */ "special_function",
  166. /* .description = */ "I'm special",
  167. /* .parameters = */ R"({
  168. "type": "object",
  169. "properties": {
  170. "arg1": {
  171. "type": "integer",
  172. "description": "The arg."
  173. }
  174. },
  175. "required": ["arg1"]
  176. })",
  177. };
  178. common_chat_tool special_function_tool_with_optional_param {
  179. /* .name = */ "special_function_with_opt",
  180. /* .description = */ "I'm special but have optional stuff",
  181. /* .parameters = */ R"({
  182. "type": "object",
  183. "properties": {
  184. "arg1": {
  185. "type": "integer",
  186. "description": "The arg."
  187. },
  188. "arg2": {
  189. "type": "integer",
  190. "description": "The optional arg."
  191. }
  192. },
  193. "required": ["arg1"]
  194. })",
  195. };
  196. common_chat_tool python_tool {
  197. /* .name = */ "python",
  198. /* .description = */ "an ipython interpreter",
  199. /* .parameters = */ R"({
  200. "type": "object",
  201. "properties": {
  202. "code": {
  203. "type": "string",
  204. "description": "Python code to execute."
  205. }
  206. },
  207. "required": ["code"]
  208. })",
  209. };
  210. common_chat_tool code_interpreter_tool {
  211. /* .name = */ "code_interpreter",
  212. /* .description = */ "an ipython interpreter",
  213. /* .parameters = */ R"({
  214. "type": "object",
  215. "properties": {
  216. "code": {
  217. "type": "string",
  218. "description": "Python code to execute."
  219. }
  220. },
  221. "required": ["code"]
  222. })",
  223. };
  224. std::vector<common_chat_tool> tools { special_function_tool, special_function_tool_with_optional_param, python_tool };
  225. std::vector<common_chat_tool> llama_3_1_tools { special_function_tool, code_interpreter_tool };
  226. struct delta_data {
  227. std::string delta;
  228. common_chat_params params;
  229. };
  230. 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 = "") {
  231. common_chat_msg msg;
  232. msg.role = "assistant";
  233. msg.content = content;
  234. msg.reasoning_content = reasoning_content;
  235. if (!tool_name.empty()) {
  236. msg.tool_calls.push_back({ tool_name, arguments, id });
  237. }
  238. return msg;
  239. }
  240. static delta_data init_delta(const struct common_chat_templates * tmpls, const std::vector<std::string> & end_tokens,
  241. const common_chat_msg & user_message,
  242. const common_chat_msg & delta_message,
  243. const std::vector<common_chat_tool> & tools,
  244. const common_chat_tool_choice & tool_choice) {
  245. common_chat_templates_inputs inputs;
  246. inputs.parallel_tool_calls = true;
  247. inputs.messages.push_back(user_message);
  248. inputs.tools = tools;
  249. inputs.tool_choice = tool_choice;
  250. auto params_prefix = common_chat_templates_apply(tmpls, inputs);
  251. inputs.messages.push_back(delta_message);
  252. inputs.add_generation_prompt = false;
  253. auto params_full = common_chat_templates_apply(tmpls, inputs);
  254. std::string prefix = params_prefix.prompt;
  255. std::string full = params_full.prompt;
  256. if (full == prefix) {
  257. throw std::runtime_error("Full message is the same as the prefix");
  258. }
  259. size_t common_prefix_length = 0;
  260. for (size_t i = 0; i < prefix.size() && i < full.size(); ++i) {
  261. if (prefix[i] != full[i]) {
  262. break;
  263. }
  264. if (prefix[i] == '<') {
  265. // DeepSeek R1's template (as of 20250209) adds a trailing <think> if add_generation_prompt,
  266. // but it removes thinking tags for past messages.
  267. // The prefix and full strings diverge at <think> vs. <|tool▁calls▁begin|>, we avoid consuming the leading <.
  268. continue;
  269. }
  270. common_prefix_length = i + 1;
  271. }
  272. auto delta = full.substr(common_prefix_length);
  273. // Strip end tokens
  274. for (const auto & end_token : end_tokens) {
  275. // rfind to find the last occurrence
  276. auto pos = delta.rfind(end_token);
  277. if (pos != std::string::npos) {
  278. delta = delta.substr(0, pos);
  279. break;
  280. }
  281. }
  282. return { delta, params_full };
  283. }
  284. /*
  285. Applies the template to 1 user message w/ add_generation_prompt=true, then w/ the test message w/ add_generation_prompt=false,
  286. gets the diff, removes any end tokens and parses the result w/ the grammar, checking that
  287. the parsed message is the same as the test_message
  288. */
  289. static void test_templates(const struct common_chat_templates * tmpls, const std::vector<std::string> & end_tokens,
  290. const common_chat_msg & test_message,
  291. const std::vector<common_chat_tool> & tools = {},
  292. const std::string & expected_delta = "",
  293. bool expect_grammar_triggered = true,
  294. bool test_grammar_if_triggered = true,
  295. common_reasoning_format reasoning_format = COMMON_REASONING_FORMAT_NONE,
  296. bool ignore_whitespace_differences = false
  297. ) {
  298. common_chat_msg user_message;
  299. user_message.role = "user";
  300. user_message.content = "Hello, world!";
  301. for (const auto & tool_choice : std::vector<common_chat_tool_choice> {COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED}) {
  302. auto data = init_delta(tmpls, end_tokens, user_message, test_message, tools, tool_choice);
  303. if (!expected_delta.empty()) {
  304. if (ignore_whitespace_differences) {
  305. assert_equals(string_strip(expected_delta), string_strip(data.delta));
  306. } else {
  307. assert_equals(expected_delta, data.delta);
  308. }
  309. }
  310. if (expect_grammar_triggered) {
  311. common_chat_syntax syntax;
  312. syntax.format = data.params.format;
  313. syntax.reasoning_format = reasoning_format;
  314. const auto msg = common_chat_parse(data.delta, /* is_partial= */ false, syntax);
  315. assert_msg_equals(test_message, msg, ignore_whitespace_differences);
  316. }
  317. if (!test_message.tool_calls.empty()) {
  318. GGML_ASSERT(!data.params.grammar.empty());
  319. }
  320. if (!data.params.grammar.empty()) {
  321. auto grammar = build_grammar(data.params.grammar);
  322. if (!grammar) {
  323. throw std::runtime_error("Failed to build grammar");
  324. }
  325. auto earliest_trigger_pos = std::string::npos;
  326. auto constrained = data.delta;
  327. for (const auto & trigger : data.params.grammar_triggers) {
  328. size_t pos = std::string::npos;
  329. std::smatch match;
  330. switch (trigger.type) {
  331. case COMMON_GRAMMAR_TRIGGER_TYPE_WORD:
  332. {
  333. const auto & word = trigger.value;
  334. pos = constrained.find(word);
  335. break;
  336. }
  337. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN:
  338. {
  339. const auto & pattern = trigger.value;
  340. if (std::regex_search(constrained, match, std::regex(pattern))) {
  341. pos = match.position(1);
  342. }
  343. break;
  344. }
  345. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL:
  346. {
  347. const auto & pattern = trigger.value;
  348. if (std::regex_match(constrained, match, std::regex(pattern))) {
  349. auto mpos = std::string::npos;
  350. for (size_t i = 1; i < match.size(); ++i) {
  351. if (match[i].length() > 0) {
  352. mpos = match.position(i);
  353. break;
  354. }
  355. }
  356. if (mpos == std::string::npos) {
  357. mpos = match.position(0);
  358. }
  359. pos = mpos;
  360. }
  361. break;
  362. }
  363. default:
  364. throw std::runtime_error("Unknown trigger type");
  365. }
  366. if (pos == std::string::npos) {
  367. continue;
  368. }
  369. if (earliest_trigger_pos == std::string::npos || pos < earliest_trigger_pos) {
  370. earliest_trigger_pos = pos;
  371. }
  372. }
  373. auto grammar_triggered = false;
  374. if (earliest_trigger_pos != std::string::npos) {
  375. constrained = constrained.substr(earliest_trigger_pos);
  376. grammar_triggered = true;
  377. }
  378. if (data.params.grammar_lazy) {
  379. assert_equals(expect_grammar_triggered, grammar_triggered);
  380. }
  381. if (grammar_triggered && test_grammar_if_triggered && !match_string(constrained, grammar.get())) {
  382. throw std::runtime_error("Failed to match delta against grammar:\n\n" + data.delta +
  383. "\n\nConstrained: " + constrained +
  384. "\n\nGrammar: " + data.params.grammar);
  385. }
  386. }
  387. }
  388. }
  389. /**
  390. * Test if streaming=true is consistant with streaming=false for given partial parser
  391. * Also test if there is any problem with partial message
  392. */
  393. template <typename T>
  394. static void test_parser_with_streaming(const common_chat_msg & expected, const std::string & raw_message, T parse_msg) {
  395. constexpr auto utf8_truncate_safe_len = [](const std::string_view s) -> size_t {
  396. auto len = s.size();
  397. if (len == 0) return 0;
  398. auto i = len;
  399. for (size_t back = 0; back < 4 && i > 0; ++back) {
  400. --i;
  401. unsigned char c = s[i];
  402. if ((c & 0x80) == 0) {
  403. return len;
  404. } else if ((c & 0xC0) == 0xC0) {
  405. size_t expected_len = 0;
  406. if ((c & 0xE0) == 0xC0) expected_len = 2;
  407. else if ((c & 0xF0) == 0xE0) expected_len = 3;
  408. else if ((c & 0xF8) == 0xF0) expected_len = 4;
  409. else return i;
  410. if (len - i >= expected_len) {
  411. return len;
  412. } else {
  413. return i;
  414. }
  415. }
  416. }
  417. return len - std::min(len, size_t(3));
  418. };
  419. constexpr auto utf8_truncate_safe_view = [utf8_truncate_safe_len](const std::string_view s) {
  420. return s.substr(0, utf8_truncate_safe_len(s));
  421. };
  422. auto merged = simple_assist_msg("");
  423. auto last_msg = parse_msg("");
  424. for (size_t i = 1; i <= raw_message.size(); ++i) {
  425. auto curr_msg = parse_msg(std::string(utf8_truncate_safe_view(std::string_view(raw_message).substr(0, i))));
  426. if (curr_msg == simple_assist_msg("")) continue;
  427. LOG_INF("Streaming msg: %s\n", common_chat_msgs_to_json_oaicompat<json>({curr_msg}).dump().c_str());
  428. for (auto diff: common_chat_msg_diff::compute_diffs(last_msg, curr_msg)) {
  429. LOG_INF("Streaming diff: %s\n", common_chat_msg_diff_to_json_oaicompat<json>(diff).dump().c_str());
  430. if (!diff.reasoning_content_delta.empty()) {
  431. merged.reasoning_content += diff.reasoning_content_delta;
  432. }
  433. if (!diff.content_delta.empty()) {
  434. merged.content += diff.content_delta;
  435. }
  436. if (diff.tool_call_index != std::string::npos) {
  437. if (!diff.tool_call_delta.name.empty()) {
  438. merged.tool_calls.push_back({diff.tool_call_delta.name, "", ""});
  439. }
  440. if (!diff.tool_call_delta.arguments.empty()) {
  441. GGML_ASSERT(!merged.tool_calls.empty());
  442. merged.tool_calls.back().arguments += diff.tool_call_delta.arguments;
  443. }
  444. }
  445. LOG_INF("Streaming merged: %s\n", common_chat_msgs_to_json_oaicompat<json>({merged}).dump().c_str());
  446. }
  447. assert_msg_equals(curr_msg, merged, true);
  448. last_msg = curr_msg;
  449. }
  450. assert_msg_equals(expected, parse_msg(raw_message), true);
  451. assert_msg_equals(expected, merged, true);
  452. }
  453. const common_chat_msg message_user {
  454. "user",
  455. "Hey there!",
  456. /* .content_parts = */ {},
  457. /* .tool_calls = */ {},
  458. /* .reasoning_content = */ "",
  459. /* .tool_name = */ "",
  460. /* .tool_call_id = */ "",
  461. };
  462. const common_chat_msg message_user_parts {
  463. "user",
  464. /* .content = */ "",
  465. /* .content_parts = */ {
  466. { "text", "Hey" },
  467. { "text", "there" },
  468. },
  469. /* .tool_calls = */ {},
  470. /* .reasoning_content = */ "",
  471. /* .tool_name = */ "",
  472. /* .tool_call_id = */ "",
  473. };
  474. const common_chat_msg message_assist = simple_assist_msg("Hello, world!\nWhat's up?");
  475. const common_chat_msg message_assist_empty = simple_assist_msg("");
  476. const common_chat_msg message_assist_thoughts_unparsed_deepseek = simple_assist_msg("<think>I'm\nthinking</think>Hello, world!\nWhat's up?");
  477. 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{}```");
  478. 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{}");
  479. const common_chat_msg message_assist_thoughts_unparsed_r7b = simple_assist_msg("<|START_THINKING|>I'm\nthinking<|END_THINKING|>Hello, world!\nWhat's up?");
  480. const common_chat_msg message_assist_thoughts_unparsed_magistral = simple_assist_msg("[THINK]raisonnement[/THINK]Réponse");
  481. const common_chat_msg message_assist_thoughts = simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking");
  482. const common_chat_msg message_assist_thoughts_unopened_unparsed = simple_assist_msg("I'm\nthinking</think>Hello, world!\nWhat's up?");
  483. const common_chat_msg message_assist_thoughts_no_content = simple_assist_msg("", "I'm\nthinking");
  484. const common_chat_msg message_assist_call = simple_assist_msg("", "", "special_function", "{\"arg1\": 1}");
  485. const common_chat_msg message_assist_call_noopt = simple_assist_msg("", "", "special_function_with_opt", "{\"arg1\": 1}");
  486. const common_chat_msg message_assist_call_withopt = simple_assist_msg("", "", "special_function_with_opt", "{\"arg1\": 1, \"arg2\": 2}");
  487. const common_chat_msg message_assist_call_content = simple_assist_msg("Hello, world!\nWhat's up?", "", "special_function", "{\"arg1\":1}");
  488. const common_chat_msg message_assist_call_empty_args = simple_assist_msg("", "", "special_function");
  489. const common_chat_msg message_assist_call_cutoff_args = simple_assist_msg("", "", "special_function", "{\"arg");
  490. const common_chat_msg message_assist_call_thoughts = simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\":1}");
  491. const common_chat_msg message_assist_call_thoughts_unparsed = simple_assist_msg("<think>I'm\nthinking</think>\n\n", "", "special_function", "{\"arg1\": 1}");
  492. const common_chat_msg message_assist_call_thoughts_content = simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": 1}");
  493. const common_chat_msg message_assist_call_id = simple_assist_msg("", "", "special_function", "{\"arg1\":1}", /* .id = */ "123456789");
  494. const common_chat_msg message_assist_call_idx = simple_assist_msg("", "", "special_function", "{\"arg1\":1}", /* .id = */ "0");
  495. const common_chat_msg message_assist_thoughts_call_idx = simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}", /* id = */ "0");
  496. const common_chat_msg message_assist_call_python = simple_assist_msg("", "", "python", "{\"code\":\"print('hey')\"}");
  497. const common_chat_msg message_assist_call_python_lines = simple_assist_msg("", "", "python", "{\"code\":\"# This is a program:\\nprint('hey')\"}");
  498. const common_chat_msg message_assist_call_python_lines_unclosed = simple_assist_msg("", "", "python", "{\"code\":\"# This is a program:\\nprint('hey')");
  499. const common_chat_msg message_assist_call_code_interpreter = simple_assist_msg("", "", "code_interpreter", "{\"code\":\"print('hey')\"}");
  500. // Use for PEG parser implementations
  501. struct peg_test_case {
  502. common_chat_templates_inputs params;
  503. std::string input;
  504. common_chat_msg expect;
  505. };
  506. struct make_peg_parser {
  507. common_chat_params params_;
  508. common_peg_arena arena_;
  509. make_peg_parser(common_chat_templates * tmpls, const common_chat_templates_inputs & inputs) {
  510. params_ = common_chat_templates_apply(tmpls, inputs);
  511. arena_.load(params_.parser);
  512. }
  513. common_chat_msg parse(const std::string & msg, bool is_partial) {
  514. return common_chat_peg_parse(arena_, msg, is_partial, /* syntax = */ {params_.format});
  515. }
  516. };
  517. static void test_peg_parser(common_chat_templates * tmpls, const std::function<void(peg_test_case &)> & init) {
  518. peg_test_case tc;
  519. init(tc);
  520. if (tc.params.messages.empty()) {
  521. tc.params.messages = {message_user};
  522. }
  523. if (tc.expect.role.empty()) {
  524. tc.expect.role = "assistant";
  525. }
  526. auto parser = make_peg_parser(tmpls, tc.params);
  527. common_chat_msg msg_accum;
  528. common_chat_msg msg_prev;
  529. msg_accum.role = msg_prev.role = "assistant";
  530. for (size_t i = 1; i <= tc.input.size(); ++i) {
  531. auto is_partial = i < tc.input.size();
  532. common_chat_msg msg_current = parser.parse(tc.input.substr(0, i), is_partial);
  533. for (const auto & diff : common_chat_msg_diff::compute_diffs(msg_prev, msg_current)) {
  534. if (!diff.reasoning_content_delta.empty()) {
  535. msg_accum.reasoning_content += diff.reasoning_content_delta;
  536. }
  537. if (!diff.content_delta.empty()) {
  538. msg_accum.content += diff.content_delta;
  539. }
  540. if (diff.tool_call_index != std::string::npos) {
  541. if (!diff.tool_call_delta.name.empty()) {
  542. msg_accum.tool_calls.push_back({diff.tool_call_delta.name, "", ""});
  543. }
  544. if (!diff.tool_call_delta.arguments.empty()) {
  545. msg_accum.tool_calls.back().arguments += diff.tool_call_delta.arguments;
  546. }
  547. }
  548. }
  549. assert_msg_equals(msg_current, msg_accum, true);
  550. msg_prev = msg_current;
  551. }
  552. assert_msg_equals(tc.expect, parser.parse(tc.input, false), true);
  553. assert_msg_equals(tc.expect, msg_accum, true);
  554. }
  555. static void test_msgs_oaicompat_json_conversion() {
  556. printf("[%s]\n", __func__);
  557. std::vector<common_chat_msg> msgs{
  558. message_user,
  559. message_user_parts,
  560. message_assist_call,
  561. message_assist_call_thoughts,
  562. message_assist_call_thoughts_unparsed,
  563. message_assist_call_thoughts_content,
  564. message_assist_call_id,
  565. message_assist_call_idx,
  566. message_assist_call_python,
  567. message_assist_call_code_interpreter,
  568. };
  569. for (const auto & msg : msgs) {
  570. auto oai_json = common_chat_msgs_to_json_oaicompat<json>({msg});
  571. auto msgs2 = common_chat_msgs_parse_oaicompat(oai_json);
  572. assert_equals((size_t) 1, msgs2.size());
  573. auto msg2 = msgs2[0];
  574. assert_msg_equals(msg, msg2);
  575. }
  576. assert_equals(
  577. std::string(
  578. "[\n"
  579. " {\n"
  580. " \"role\": \"user\",\n"
  581. " \"content\": [\n"
  582. " {\n"
  583. " \"type\": \"text\",\n"
  584. " \"text\": \"Hey\"\n"
  585. " },\n"
  586. " {\n"
  587. " \"type\": \"text\",\n"
  588. " \"text\": \"there\"\n"
  589. " }\n"
  590. " ]\n"
  591. " }\n"
  592. "]"
  593. ),
  594. common_chat_msgs_to_json_oaicompat<json>({message_user_parts}).dump(2));
  595. assert_equals(
  596. std::string(
  597. "[\n"
  598. " {\n"
  599. " \"role\": \"assistant\",\n"
  600. " \"content\": null,\n"
  601. " \"tool_calls\": [\n"
  602. " {\n"
  603. " \"type\": \"function\",\n"
  604. " \"function\": {\n"
  605. " \"name\": \"python\",\n"
  606. " \"arguments\": \"{\\\"code\\\":\\\"print('hey')\\\"}\"\n"
  607. " }\n"
  608. " }\n"
  609. " ]\n"
  610. " }\n"
  611. "]"
  612. ),
  613. common_chat_msgs_to_json_oaicompat<json>({message_assist_call_python}).dump(2));
  614. auto res = common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\", \"tool_calls\": []}]"));
  615. assert_equals<size_t>(1, res.size());
  616. assert_equals<std::string>(res[0].role, "assistant");
  617. assert_equals(true, res[0].content.empty());
  618. assert_equals(true, res[0].tool_calls.empty());
  619. try {
  620. common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\"}]"));
  621. throw std::runtime_error("Expected exception");
  622. } catch (const std::exception & e) {
  623. if (std::string(e.what()).find("'content'") == std::string::npos) {
  624. throw std::runtime_error("Expected exception about missing 'content'");
  625. }
  626. }
  627. }
  628. static void test_tools_oaicompat_json_conversion() {
  629. printf("[%s]\n", __func__);
  630. std::vector<common_chat_tool> tools{
  631. special_function_tool,
  632. python_tool,
  633. code_interpreter_tool,
  634. };
  635. for (const auto & tool : tools) {
  636. auto oai_json = common_chat_tools_to_json_oaicompat<json>({tool});
  637. auto tools2 = common_chat_tools_parse_oaicompat(oai_json);
  638. assert_equals((size_t) 1, tools2.size());
  639. auto tool2 = tools2[0];
  640. assert_equals(tool.name, tool2.name);
  641. assert_equals(tool.description, tool2.description);
  642. assert_equals(json::parse(tool.parameters).dump(2), json::parse(tool2.parameters).dump(2));
  643. }
  644. assert_equals(
  645. std::string(
  646. "[\n"
  647. " {\n"
  648. " \"type\": \"function\",\n"
  649. " \"function\": {\n"
  650. " \"name\": \"special_function\",\n"
  651. " \"description\": \"I'm special\",\n"
  652. " \"parameters\": {\n"
  653. " \"type\": \"object\",\n"
  654. " \"properties\": {\n"
  655. " \"arg1\": {\n"
  656. " \"type\": \"integer\",\n"
  657. " \"description\": \"The arg.\"\n"
  658. " }\n"
  659. " },\n"
  660. " \"required\": [\n"
  661. " \"arg1\"\n"
  662. " ]\n"
  663. " }\n"
  664. " }\n"
  665. " }\n"
  666. "]"
  667. ),
  668. common_chat_tools_to_json_oaicompat<json>({special_function_tool}).dump(2));
  669. }
  670. static void test_template_output_parsers() {
  671. printf("[%s]\n", __func__);
  672. common_chat_templates_inputs inputs_no_tools;
  673. inputs_no_tools.messages = {message_user};
  674. common_chat_templates_inputs inputs_tools;
  675. inputs_tools.messages = {message_user};
  676. inputs_tools.tools = {special_function_tool};
  677. common_chat_templates_inputs inputs_tools_builtin;
  678. inputs_tools_builtin.messages = {message_user};
  679. inputs_tools_builtin.tools = {python_tool};
  680. {
  681. // Not supported yet
  682. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r-plus-tool_use.jinja");
  683. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  684. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  685. }
  686. {
  687. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r7b-12-2024-tool_use.jinja");
  688. std::vector<std::string> end_tokens{ "<|END_OF_TURN_TOKEN|>" };
  689. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  690. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  691. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B, params.format);
  692. assert_equals(false, params.thinking_forced_open);
  693. }
  694. assert_msg_equals(message_assist,
  695. common_chat_parse(
  696. "Hello, world!\nWhat's up?",
  697. /* is_partial= */ false,
  698. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  699. assert_msg_equals(message_assist,
  700. common_chat_parse(
  701. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  702. /* is_partial= */ false,
  703. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  704. assert_msg_equals(message_assist_thoughts,
  705. common_chat_parse(
  706. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  707. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  708. /* is_partial= */ false,
  709. {
  710. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  711. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  712. }));
  713. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  714. common_chat_parse(
  715. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  716. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  717. /* is_partial= */ false,
  718. {
  719. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  720. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  721. /* .reasoning_in_content = */ true,
  722. /* .thinking_forced_open = */ false,
  723. }));
  724. assert_msg_equals(message_assist_thoughts_unparsed_r7b,
  725. common_chat_parse(
  726. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  727. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  728. /* is_partial= */ false,
  729. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  730. assert_msg_equals(message_assist_thoughts,
  731. common_chat_parse(
  732. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  733. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  734. /* is_partial= */ false,
  735. {
  736. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  737. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  738. }));
  739. assert_msg_equals(message_assist_thoughts_call_idx,
  740. common_chat_parse(
  741. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  742. "<|START_ACTION|>[\n"
  743. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  744. "]<|END_ACTION|>",
  745. /* is_partial= */ false,
  746. {
  747. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  748. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  749. }));
  750. assert_msg_equals(message_assist_thoughts_no_content,
  751. common_chat_parse(
  752. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  753. "<|START_ACTION|>[\n"
  754. " {\"tool_call_id\": \"0\", \"tool_name\": \"special",
  755. /* is_partial= */ true,
  756. {
  757. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  758. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  759. }));
  760. test_templates(tmpls.get(), end_tokens, message_assist_call_idx, tools,
  761. "<|START_THINKING|><|END_THINKING|>"
  762. "<|START_ACTION|>[\n"
  763. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  764. "]<|END_ACTION|>",
  765. /* expect_grammar_triggered= */ true,
  766. /* test_grammar_if_triggered= */ true,
  767. COMMON_REASONING_FORMAT_DEEPSEEK);
  768. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  769. "<|START_RESPONSE|>Hello, world!\n"
  770. "What's up?<|END_RESPONSE|>",
  771. /* expect_grammar_triggered= */ false);
  772. }
  773. {
  774. auto tmpls = read_templates("models/templates/google-gemma-2-2b-it.jinja");
  775. std::vector<std::string> end_tokens{ "<end_of_turn>" };
  776. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  777. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  778. assert_equals(COMMON_CHAT_FORMAT_GENERIC,
  779. common_chat_templates_apply(
  780. read_templates("models/templates/microsoft-Phi-3.5-mini-instruct.jinja").get(),
  781. inputs_tools)
  782. .format);
  783. // Generic tool calls doesn't generate / parse content-only messages symmetrically.
  784. assert_equals(
  785. simple_assist_msg("{ \"tool_call\" : { \"name\" : \"t"),
  786. common_chat_parse(
  787. "{ \"tool_call\" : { \"name\" : \"t",
  788. /* is_partial= */ true,
  789. {
  790. /* .format = */ COMMON_CHAT_FORMAT_GENERIC,
  791. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  792. /* .reasoning_in_content = */ false,
  793. /* .thinking_forced_open = */ true,
  794. /* .parse_tool_calls = */ false,
  795. }));
  796. assert_equals(
  797. message_assist_empty,
  798. common_chat_parse(
  799. "{ \"tool_call\" : { \"name\" : \"t",
  800. /* is_partial= */ true,
  801. {COMMON_CHAT_FORMAT_GENERIC}));
  802. assert_equals(
  803. simple_assist_msg("", "", "puppeteer_screenshot", "{\"name\":\"servethehome_homepage\","),
  804. common_chat_parse(
  805. R"({"tool_call": {"name": "puppeteer_screenshot", "arguments": {"name": "servethehome_homepage",)",
  806. /* is_partial= */ true,
  807. {COMMON_CHAT_FORMAT_GENERIC}));
  808. assert_equals(
  809. message_assist_call_empty_args,
  810. common_chat_parse(
  811. "{ \"tool_call\" : { \"name\" : \"special_function\"",
  812. /* is_partial= */ true,
  813. {COMMON_CHAT_FORMAT_GENERIC}));
  814. assert_equals(
  815. message_assist_call_cutoff_args,
  816. common_chat_parse(
  817. "{ \"tool_call\" : { \"name\" : \"special_function\", \"arguments\" : { \"arg",
  818. /* is_partial= */ true,
  819. {COMMON_CHAT_FORMAT_GENERIC}));
  820. assert_msg_equals(message_assist,
  821. common_chat_parse(
  822. "{\n"
  823. " \"response\": \"Hello, world!\\nWhat's up?\"\n"
  824. "}",
  825. /* is_partial= */ false,
  826. {COMMON_CHAT_FORMAT_GENERIC}));
  827. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  828. "{\n"
  829. " \"tool_calls\": [\n"
  830. " {\n"
  831. " \"name\": \"special_function\",\n"
  832. " \"arguments\": {\n"
  833. " \"arg1\": 1\n"
  834. " },\n"
  835. " \"id\": \"123456789\"\n"
  836. " }\n"
  837. " ]\n"
  838. "}");
  839. }
  840. {
  841. auto tmpls = read_templates("models/templates/mistralai-Mistral-Nemo-Instruct-2407.jinja");
  842. std::vector<std::string> end_tokens{ "</s>" };
  843. assert_equals(COMMON_CHAT_FORMAT_MISTRAL_NEMO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  844. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  845. test_templates(
  846. tmpls.get(), end_tokens, message_assist_call_id, tools,
  847. "[TOOL_CALLS][{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, \"id\": \"123456789\"}]");
  848. }
  849. {
  850. assert_msg_equals(
  851. simple_assist_msg("Réponse", "raisonnement"),
  852. common_chat_parse(
  853. message_assist_thoughts_unparsed_magistral.content,
  854. /* is_partial= */ false,
  855. {
  856. /* .format = */ COMMON_CHAT_FORMAT_MAGISTRAL,
  857. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  858. }));
  859. }
  860. {
  861. auto tmpls = read_templates("models/templates/Qwen-QwQ-32B.jinja");
  862. std::vector<std::string> end_tokens{ "<|im_end|>" };
  863. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  864. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  865. }
  866. {
  867. auto tmpls = read_templates("models/templates/NousResearch-Hermes-2-Pro-Llama-3-8B-tool_use.jinja");
  868. std::vector<std::string> end_tokens{ "<|im_end|>" };
  869. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  870. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  871. assert_equals(
  872. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  873. common_chat_templates_apply(
  874. read_templates("models/templates/NousResearch-Hermes-3-Llama-3.1-8B-tool_use.jinja").get(),
  875. inputs_tools)
  876. .format);
  877. assert_equals(
  878. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  879. common_chat_templates_apply(
  880. read_templates("models/templates/Qwen-Qwen2.5-7B-Instruct.jinja").get(),
  881. inputs_tools)
  882. .format);
  883. // Test parsing
  884. assert_msg_equals(
  885. simple_assist_msg("", "", "python", ""),
  886. common_chat_parse(
  887. "```json\n"
  888. "<function_call> { \"name\" : \"python\"",
  889. /* is_partial= */ true,
  890. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  891. assert_msg_equals(
  892. simple_assist_msg("Let's call something\n"),
  893. common_chat_parse(
  894. "Let's call something\n"
  895. "<tool_call>{\"name\"",
  896. /* is_partial= */ true,
  897. {
  898. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  899. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  900. }));
  901. assert_msg_equals(
  902. simple_assist_msg("Let's call something\n"),
  903. common_chat_parse(
  904. "Let's call something\n"
  905. "<tool_call>{\"name",
  906. /* is_partial= */ true,
  907. {
  908. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  909. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  910. }));
  911. assert_msg_equals(message_assist_call_thoughts,
  912. common_chat_parse(
  913. // QwQ-32B's template adds a trailing <think> if add_generation_prompt
  914. "I'm\nthinking</think>\n"
  915. "<tool_call>{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}</tool_call>",
  916. /* is_partial= */ false,
  917. {
  918. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  919. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  920. /* .reasoning_in_content = */ false,
  921. /* .thinking_forced_open = */ true,
  922. }));
  923. assert_msg_equals(
  924. message_assist_call,
  925. common_chat_parse(
  926. "<tool_call>\n"
  927. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  928. "</tool_call>",
  929. /* is_partial= */ false,
  930. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  931. assert_msg_equals(message_assist_call_content,
  932. common_chat_parse(
  933. "Hello, world!\nWhat's up?<tool_call>\n"
  934. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  935. "</tool_call>",
  936. /* is_partial= */ false,
  937. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  938. assert_msg_equals(
  939. message_assist_call,
  940. common_chat_parse(
  941. "<function=special_function>{\"arg1\": 1}</function>",
  942. /* is_partial= */ false,
  943. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  944. assert_msg_equals(
  945. message_assist_call,
  946. common_chat_parse(
  947. "<function name=\"special_function\">\n"
  948. "{\"arg1\": 1}\n"
  949. "</function>",
  950. /* is_partial= */ false,
  951. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  952. assert_msg_equals(
  953. message_assist_call,
  954. common_chat_parse(
  955. "<tool>\n"
  956. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  957. "</tool>",
  958. /* is_partial= */ false,
  959. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  960. assert_msg_equals(
  961. message_assist_call,
  962. common_chat_parse(
  963. "<tools>\n"
  964. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  965. "</tools>",
  966. /* is_partial= */ false,
  967. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  968. assert_msg_equals(
  969. message_assist_call,
  970. common_chat_parse(
  971. "<response>\n"
  972. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  973. "</response>",
  974. /* is_partial= */ false,
  975. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  976. assert_msg_equals(
  977. message_assist_call,
  978. common_chat_parse(
  979. "```xml\n"
  980. "<response>\n"
  981. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  982. "</response>\n"
  983. "```",
  984. /* is_partial= */ false,
  985. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  986. assert_msg_equals(
  987. message_assist_call,
  988. common_chat_parse(
  989. "```xml\n"
  990. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  991. "```",
  992. /* is_partial= */ false,
  993. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  994. assert_msg_equals(
  995. message_assist_call,
  996. common_chat_parse(
  997. "```\n"
  998. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  999. "```",
  1000. /* is_partial= */ false,
  1001. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1002. assert_msg_equals(
  1003. message_assist_call,
  1004. common_chat_parse(
  1005. "```\n"
  1006. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1007. "```",
  1008. /* is_partial= */ false,
  1009. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1010. assert_msg_equals(
  1011. message_assist_call,
  1012. common_chat_parse(
  1013. "```json\n"
  1014. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1015. "```",
  1016. /* is_partial= */ false,
  1017. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1018. assert_msg_equals(
  1019. message_assist_call,
  1020. common_chat_parse(
  1021. "```json\n"
  1022. "\n"
  1023. " <function_call> {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}} \n"
  1024. " </function_call> \n"
  1025. "``` ",
  1026. /* is_partial= */ false,
  1027. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1028. assert_msg_equals(
  1029. message_assist_call,
  1030. common_chat_parse(
  1031. "<json>\n"
  1032. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1033. "</json>",
  1034. /* is_partial= */ false,
  1035. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1036. assert_msg_equals(
  1037. message_assist_call,
  1038. common_chat_parse(
  1039. "<xml>\n"
  1040. " {\n"
  1041. " \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}\n"
  1042. " }\n"
  1043. "</xml>",
  1044. /* is_partial= */ false,
  1045. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1046. assert_msg_equals(
  1047. message_assist_call,
  1048. common_chat_parse(
  1049. "<JSON>\n"
  1050. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1051. "</JSON>",
  1052. /* is_partial= */ false,
  1053. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1054. assert_msg_equals(
  1055. message_assist_call,
  1056. common_chat_parse(
  1057. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  1058. /* is_partial= */ false,
  1059. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1060. assert_msg_equals(
  1061. message_assist_call,
  1062. common_chat_parse(
  1063. "{\n \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  1064. /* is_partial= */ false,
  1065. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1066. // Test multiple tool calls
  1067. common_chat_msg message_assist_multiple_calls;
  1068. message_assist_multiple_calls.role = "assistant";
  1069. message_assist_multiple_calls.content = "";
  1070. message_assist_multiple_calls.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  1071. message_assist_multiple_calls.tool_calls.push_back({"python", "{\"code\":\"print('hello')\"}", ""});
  1072. assert_msg_equals(
  1073. message_assist_multiple_calls,
  1074. common_chat_parse(
  1075. "<tool_call>\n"
  1076. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1077. "</tool_call>\n"
  1078. "<tool_call>\n"
  1079. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('hello')\"}}\n"
  1080. "</tool_call>",
  1081. /* is_partial= */ false,
  1082. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1083. assert_msg_equals(
  1084. message_assist_multiple_calls,
  1085. common_chat_parse(
  1086. "<function=special_function>{\"arg1\": 1}</function>\n"
  1087. "<function=python>{\"code\":\"print('hello')\"}</function>",
  1088. /* is_partial= */ false,
  1089. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1090. assert_msg_equals(
  1091. simple_assist_msg(
  1092. "This is not a tool call:",
  1093. "",
  1094. "special_function",
  1095. "{\"arg1\": 1}"),
  1096. common_chat_parse(
  1097. "This is not a tool call:\n"
  1098. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  1099. /* is_partial= */ false,
  1100. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1101. assert_msg_equals(message_assist,
  1102. common_chat_parse(
  1103. "Hello, world!\nWhat's up?",
  1104. /* is_partial= */ false,
  1105. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1106. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1107. common_chat_parse(
  1108. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1109. /* is_partial= */ false,
  1110. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1111. // assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1112. // common_chat_parse(
  1113. // "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1114. // COMMON_CHAT_FORMAT_HERMES_2_PRO));
  1115. assert_msg_equals(message_assist_thoughts,
  1116. common_chat_parse(
  1117. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1118. /* is_partial= */ false,
  1119. {
  1120. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1121. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1122. }));
  1123. assert_msg_equals(message_assist_thoughts,
  1124. common_chat_parse(
  1125. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1126. /* is_partial= */ true,
  1127. {
  1128. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1129. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1130. }));
  1131. assert_msg_equals(message_assist_thoughts_unparsed_md,
  1132. common_chat_parse(
  1133. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  1134. /* is_partial= */ false,
  1135. {
  1136. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1137. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1138. /* .reasoning_in_content = */ true,
  1139. /* .thinking_forced_open = */ false,
  1140. /* .parse_tool_calls = */ false,
  1141. }));
  1142. assert_msg_equals(message_assist_thoughts_unparsed_md_partial,
  1143. common_chat_parse(
  1144. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  1145. /* is_partial= */ true,
  1146. {
  1147. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1148. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1149. /* .reasoning_in_content = */ true,
  1150. /* .thinking_forced_open = */ false,
  1151. }));
  1152. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  1153. common_chat_parse(
  1154. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1155. /* is_partial= */ false,
  1156. {
  1157. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1158. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1159. }));
  1160. assert_msg_equals(message_assist_thoughts,
  1161. common_chat_parse(
  1162. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1163. /* is_partial= */ false,
  1164. {
  1165. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1166. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1167. /* .reasoning_in_content = */ false,
  1168. /* .thinking_forced_open = */ true,
  1169. }));
  1170. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1171. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1172. "<tool_call>\n"
  1173. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1174. "</tool_call>");
  1175. // Test multiple tool calls with template
  1176. common_chat_msg message_assist_multiple_calls_template;
  1177. message_assist_multiple_calls_template.role = "assistant";
  1178. message_assist_multiple_calls_template.content = "";
  1179. message_assist_multiple_calls_template.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  1180. message_assist_multiple_calls_template.tool_calls.push_back({"python", "{\"code\":\"print('test')\"}", ""});
  1181. test_templates(tmpls.get(), end_tokens, message_assist_multiple_calls_template, tools,
  1182. "<tool_call>\n"
  1183. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1184. "</tool_call>\n"
  1185. "<tool_call>\n"
  1186. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('test')\"}}\n"
  1187. "</tool_call>");
  1188. test_templates(tmpls.get(), end_tokens, message_assist_call_python_lines, tools,
  1189. "<tool_call>\n"
  1190. "{\"name\": \"python\", \"arguments\": {\"code\":\"# This is a program:\\nprint('hey')\"}}\n"
  1191. "</tool_call>");
  1192. assert_msg_equals(
  1193. simple_assist_msg("", /* reasoning_content= */ "<tool_call>nah uhg</tool_call>"),
  1194. common_chat_parse(
  1195. "<think><tool_call>nah uhg</tool_call>",
  1196. /* is_partial= */ false,
  1197. {
  1198. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1199. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1200. }));
  1201. }
  1202. {
  1203. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.1-8B-Instruct.jinja");
  1204. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1205. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1206. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1207. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1208. common_chat_templates_apply(tmpls.get(), inputs_tools_builtin).format);
  1209. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1210. common_chat_templates_apply(
  1211. read_templates("models/templates/meta-llama-Llama-3.3-70B-Instruct.jinja").get(),
  1212. inputs_tools_builtin)
  1213. .format);
  1214. assert_equals(
  1215. message_assist_call,
  1216. common_chat_parse(
  1217. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}",
  1218. /* is_partial= */ false,
  1219. {COMMON_CHAT_FORMAT_LLAMA_3_X}));
  1220. // test_templates(tmpls.get(), end_tokens, message_assist, tools, R"(?)", /* expect_grammar_triggered= */ false);
  1221. test_templates(tmpls.get(), end_tokens, message_assist_call_code_interpreter, llama_3_1_tools,
  1222. "<|python_tag|>code_interpreter.call(code=\"print('hey')\")");
  1223. test_templates(tmpls.get(), end_tokens, message_assist_call_python, tools,
  1224. "<|python_tag|>python.call(code=\"print('hey')\")");
  1225. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1226. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1227. }
  1228. {
  1229. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.2-3B-Instruct.jinja");
  1230. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1231. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1232. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1233. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1234. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1235. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1236. }
  1237. {
  1238. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.1.jinja");
  1239. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1240. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1241. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1242. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1,
  1243. common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1244. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1245. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1246. for (auto is_partial : { false, true }) {
  1247. assert_equals(
  1248. message_assist_call,
  1249. common_chat_parse(
  1250. "<function=special_function>{\"arg1\": 1}</function>",
  1251. is_partial,
  1252. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1253. }
  1254. assert_equals(
  1255. message_assist_call,
  1256. common_chat_parse(
  1257. "<function=special_function>{\"arg1\": 1}<",
  1258. /* is_partial= */ true,
  1259. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1260. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1261. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1262. "<function=special_function>{\"arg1\": 1}</function>");
  1263. }
  1264. {
  1265. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.2.jinja");
  1266. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1267. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1268. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1269. assert_msg_equals(
  1270. simple_assist_msg(
  1271. "Hello, world!\nnono\nWhat's up?",
  1272. "",
  1273. "special_function",
  1274. "{\"arg1\": 1}"),
  1275. common_chat_parse(
  1276. "all\n"
  1277. "Hello, world!\n"
  1278. "nono\n"
  1279. "What's up?>>>special_function\n"
  1280. "{\"arg1\": 1}\n",
  1281. /* is_partial= */ false,
  1282. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1283. assert_msg_equals(message_assist_call_python_lines,
  1284. common_chat_parse(
  1285. "python\n"
  1286. "# This is a program:\n"
  1287. "print('hey')",
  1288. /* is_partial= */ false,
  1289. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1290. assert_msg_equals(message_assist_call_python_lines_unclosed,
  1291. common_chat_parse(
  1292. "python\n"
  1293. "# This is a program:\n"
  1294. "print('hey')",
  1295. /* is_partial= */ true,
  1296. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1297. assert_msg_equals(message_assist_call,
  1298. common_chat_parse(
  1299. "special_function\n"
  1300. "{\"arg1\": 1} \n ",
  1301. /* is_partial= */ false,
  1302. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1303. assert_msg_equals(message_assist,
  1304. common_chat_parse(
  1305. "all\n"
  1306. "Hello, world!\nWhat's up?",
  1307. /* is_partial= */ false,
  1308. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1309. test_templates(tmpls.get(), end_tokens, message_assist, {},
  1310. "all\n"
  1311. "Hello, world!\n"
  1312. "What's up?",
  1313. /* expect_grammar_triggered= */ false);
  1314. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1315. "special_function\n"
  1316. "{\"arg1\": 1}");
  1317. }
  1318. {
  1319. auto tmpls = read_templates("models/templates/fireworks-ai-llama-3-firefunction-v2.jinja");
  1320. std::vector<std::string> end_tokens{ "<|eot_id|>" };
  1321. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1322. assert_equals(COMMON_CHAT_FORMAT_FIREFUNCTION_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1323. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1324. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1325. " functools[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]");
  1326. }
  1327. {
  1328. // Original DeepSeek R1 template. Leaves <|tool▁calls▁begin|> and others unclosed. Our logic fixes the prompt.
  1329. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-R1-Distill-Llama-8B.jinja");
  1330. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1331. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  1332. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  1333. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, params.format);
  1334. assert_equals(true, params.thinking_forced_open);
  1335. }
  1336. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1337. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1338. assert_msg_equals(
  1339. simple_assist_msg("Hello, world!\nWhat's up?", "<think>I'm\nthinking"),
  1340. common_chat_parse(
  1341. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1342. /* is_partial= */ false,
  1343. {
  1344. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1345. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1346. /* .reasoning_in_content = */ false,
  1347. /* .thinking_forced_open = */ true,
  1348. }));
  1349. assert_msg_equals(
  1350. simple_assist_msg("", "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with"),
  1351. common_chat_parse(
  1352. "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with",
  1353. /* is_partial= */ true,
  1354. {
  1355. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1356. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1357. /* .reasoning_in_content = */ false,
  1358. /* .thinking_forced_open = */ true,
  1359. }));
  1360. assert_msg_equals(message_assist_thoughts,
  1361. common_chat_parse(
  1362. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1363. /* is_partial= */ false,
  1364. {
  1365. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1366. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1367. }));
  1368. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  1369. common_chat_parse(
  1370. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1371. /* is_partial= */ false,
  1372. {
  1373. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1374. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1375. }));
  1376. assert_msg_equals(message_assist_thoughts,
  1377. common_chat_parse(
  1378. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1379. /* is_partial= */ false,
  1380. {
  1381. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1382. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1383. /* .reasoning_in_content = */ false,
  1384. /* .thinking_forced_open = */ true,
  1385. }));
  1386. assert_msg_equals(message_assist_thoughts,
  1387. // Latest template update (ast of 20250209) adds a trailing <think>\n if add_generation_prompt is true.
  1388. common_chat_parse(
  1389. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1390. /* is_partial= */ false,
  1391. {
  1392. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1393. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1394. /* .reasoning_in_content = */ false,
  1395. /* .thinking_forced_open = */ true,
  1396. }));
  1397. // test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1398. // "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1399. // "```json\n"
  1400. // "{\"arg1\": 1}\n"
  1401. // // 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)
  1402. // "```<|tool▁call▁end|>",
  1403. // /* expect_grammar_triggered= */ true,
  1404. // /* test_grammar_if_triggered= */ false);
  1405. }
  1406. {
  1407. // Replacement DeepSeek R1 template. Makes the Distill Qwen 7B/32B models happy to call tools and all.
  1408. auto tmpls = read_templates("models/templates/llama-cpp-deepseek-r1.jinja");
  1409. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1410. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1411. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1412. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1413. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1414. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1415. common_chat_parse(
  1416. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1417. /* is_partial= */ false,
  1418. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1419. assert_msg_equals(message_assist_thoughts,
  1420. common_chat_parse(
  1421. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1422. /* is_partial= */ false,
  1423. {
  1424. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1425. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1426. }));
  1427. assert_msg_equals(message_assist_thoughts,
  1428. common_chat_parse(
  1429. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1430. /* is_partial= */ false,
  1431. {
  1432. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1433. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1434. /* .reasoning_in_content = */ false,
  1435. /* .thinking_forced_open = */ true,
  1436. }));
  1437. assert_msg_equals(message_assist_call_thoughts_unparsed,
  1438. common_chat_parse(
  1439. "<think>I'm\nthinking</think>\n\n"
  1440. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1441. "```json\n"
  1442. "{\"arg1\": 1}\n"
  1443. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1444. /* is_partial= */ false,
  1445. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1446. assert_msg_equals(message_assist_call,
  1447. common_chat_parse(
  1448. "<|tool▁calls|>function<|tool▁sep|>special_function\n"
  1449. "```json\n"
  1450. "{\"arg1\": 1}\n"
  1451. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1452. /* is_partial= */ false,
  1453. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1454. assert_msg_equals(message_assist_call_thoughts,
  1455. common_chat_parse(
  1456. "<think>I'm\nthinking</think>\n\n"
  1457. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1458. "```json\n"
  1459. "{\"arg1\": 1}\n"
  1460. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1461. /* is_partial= */ false,
  1462. {
  1463. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1464. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1465. }));
  1466. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1467. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1468. "```json\n"
  1469. "{\"arg1\": 1}\n"
  1470. "```<|tool▁call▁end|><|tool▁calls▁end|>");
  1471. }
  1472. {
  1473. auto tmpls = read_templates("models/templates/ibm-granite-granite-3.3-2B-Instruct.jinja");
  1474. std::vector<std::string> end_tokens{ "<|end_of_text|>" };
  1475. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1476. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1477. // Test parsing regular content
  1478. assert_msg_equals(message_assist,
  1479. common_chat_parse(
  1480. "Hello, world!\nWhat's up?",
  1481. /* is_partial= */ false,
  1482. {COMMON_CHAT_FORMAT_GRANITE}));
  1483. assert_msg_equals(
  1484. message_assist,
  1485. common_chat_parse(
  1486. "Hello, world!\nWhat's up?",
  1487. /* is_partial= */ true,
  1488. {COMMON_CHAT_FORMAT_GRANITE}));
  1489. // Test parsing content with thinking
  1490. assert_msg_equals(message_assist_thoughts,
  1491. common_chat_parse(
  1492. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1493. /* is_partial= */ false,
  1494. {
  1495. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1496. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1497. }));
  1498. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1499. common_chat_parse(
  1500. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1501. /* is_partial= */ false,
  1502. {COMMON_CHAT_FORMAT_GRANITE}));
  1503. assert_msg_equals(message_assist_thoughts,
  1504. common_chat_parse(
  1505. "<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?",
  1506. /* is_partial= */ true,
  1507. {
  1508. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1509. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1510. }));
  1511. assert_msg_equals(message_assist_thoughts,
  1512. common_chat_parse(
  1513. "<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?</response>",
  1514. /* is_partial= */ false,
  1515. {
  1516. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1517. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1518. }));
  1519. assert_msg_equals(simple_assist_msg("<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?</response>"),
  1520. common_chat_parse(
  1521. "<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?</response>",
  1522. /* is_partial= */ false,
  1523. {COMMON_CHAT_FORMAT_GRANITE}));
  1524. assert_msg_equals(message_assist_empty,
  1525. common_chat_parse(
  1526. "<think",
  1527. /* is_partial= */ true,
  1528. {
  1529. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1530. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1531. }));
  1532. assert_msg_equals(message_assist_empty,
  1533. common_chat_parse(
  1534. "<think",
  1535. /* is_partial= */ true,
  1536. {COMMON_CHAT_FORMAT_GRANITE}));
  1537. assert_msg_equals(message_assist_thoughts_no_content,
  1538. common_chat_parse(
  1539. "<think>I'm\nthinking",
  1540. /* is_partial= */ true,
  1541. {
  1542. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1543. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1544. }));
  1545. assert_msg_equals(
  1546. message_assist_empty,
  1547. common_chat_parse(
  1548. "<think>I'm\nthinking</think><response",
  1549. /* is_partial= */ true,
  1550. {COMMON_CHAT_FORMAT_GRANITE}));
  1551. // Test parsing tool calls
  1552. assert_msg_equals(message_assist_call,
  1553. common_chat_parse(
  1554. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]",
  1555. /* is_partial= */ false,
  1556. {COMMON_CHAT_FORMAT_GRANITE}));
  1557. assert_msg_equals(
  1558. message_assist_call_empty_args,
  1559. common_chat_parse(
  1560. "<|tool_call|>[{\"name\": \"special_function\"",
  1561. /* is_partial= */ true,
  1562. {COMMON_CHAT_FORMAT_GRANITE}));
  1563. assert_msg_equals(
  1564. message_assist_call_cutoff_args,
  1565. common_chat_parse(
  1566. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg",
  1567. /* is_partial= */ true,
  1568. {COMMON_CHAT_FORMAT_GRANITE}));
  1569. assert_msg_equals(
  1570. message_assist_call_cutoff_args,
  1571. common_chat_parse(
  1572. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg",
  1573. /* is_partial= */ true,
  1574. {
  1575. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1576. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1577. }));
  1578. // Test parsing tool calls with thinking
  1579. assert_msg_equals(
  1580. message_assist_call_thoughts,
  1581. common_chat_parse(
  1582. "<think>I'm\nthinking</think><|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, {",
  1583. /* is_partial= */ true,
  1584. {
  1585. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1586. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1587. }));
  1588. // Test template generation for regular content
  1589. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1590. "Hello, world!\nWhat's up?",
  1591. /* expect_grammar_triggered= */ false);
  1592. // Test template generation for tool calls
  1593. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  1594. "{\n"
  1595. " \"tool_calls\": [\n"
  1596. " {\n"
  1597. " \"name\": \"special_function\",\n"
  1598. " \"arguments\": {\n"
  1599. " \"arg1\": 1\n"
  1600. " },\n"
  1601. " \"id\": \"123456789\"\n"
  1602. " }\n"
  1603. " ]\n"
  1604. "}",
  1605. /* expect_grammar_triggered= */ false
  1606. );
  1607. }
  1608. {
  1609. auto tmpls = read_templates("models/templates/openai-gpt-oss-120b.jinja");
  1610. std::vector<std::string> end_tokens{ "<|return|>", "<|call|>" };
  1611. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1612. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1613. assert_msg_equals(simple_assist_msg("", "I'm\nthink"),
  1614. common_chat_parse(
  1615. "<|channel|>analysis<|message|>I'm\nthink",
  1616. /* is_partial= */ true,
  1617. {
  1618. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1619. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1620. }));
  1621. assert_msg_equals(simple_assist_msg("", "I'm\nthinking"),
  1622. common_chat_parse(
  1623. "<|channel|>analysis<|message|>I'm\nthinking<|end|>",
  1624. /* is_partial= */ true,
  1625. {
  1626. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1627. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1628. }));
  1629. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1630. common_chat_parse(
  1631. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1632. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1633. /* is_partial= */ false,
  1634. {
  1635. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1636. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1637. }));
  1638. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1639. common_chat_parse(
  1640. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1641. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1",
  1642. /* is_partial= */ true,
  1643. {
  1644. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1645. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1646. }));
  1647. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1648. common_chat_parse(
  1649. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1650. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1651. /* is_partial= */ true,
  1652. {
  1653. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1654. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1655. }));
  1656. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1657. common_chat_parse(
  1658. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1659. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1660. /* is_partial= */ false,
  1661. {
  1662. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1663. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1664. }));
  1665. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1666. common_chat_parse(
  1667. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1668. "<|start|>assistant<|channel|>analysis to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1669. /* is_partial= */ false,
  1670. {
  1671. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1672. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1673. }));
  1674. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1675. common_chat_parse(
  1676. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1677. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?",
  1678. /* is_partial= */ true,
  1679. {
  1680. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1681. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1682. }));
  1683. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1684. common_chat_parse(
  1685. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1686. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?<|end|>"
  1687. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1688. /* is_partial= */ true,
  1689. {
  1690. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1691. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1692. }));
  1693. // Test parse_tool_calls == false
  1694. assert_msg_equals(
  1695. simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1696. common_chat_parse(
  1697. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1698. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1699. /* is_partial= */ true,
  1700. {
  1701. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1702. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1703. /* .reasoning_in_content = */ false,
  1704. /* .thinking_forced_open = */ false,
  1705. /* .parse_tool_calls = */ false,
  1706. }));
  1707. assert_msg_equals(
  1708. simple_assist_msg("", "I'm\nthinking"),
  1709. common_chat_parse(
  1710. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1711. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1712. /* is_partial= */ true,
  1713. {
  1714. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1715. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1716. /* .reasoning_in_content = */ false,
  1717. /* .thinking_forced_open = */ false,
  1718. /* .parse_tool_calls = */ false,
  1719. }));
  1720. assert_msg_equals(
  1721. simple_assist_msg("", "I'm\nthinking"),
  1722. common_chat_parse(
  1723. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1724. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1725. /* is_partial= */ false,
  1726. {
  1727. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1728. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1729. /* .reasoning_in_content = */ false,
  1730. /* .thinking_forced_open = */ false,
  1731. /* .parse_tool_calls = */ false,
  1732. }));
  1733. // Test reasoning formats
  1734. assert_msg_equals(
  1735. simple_assist_msg(
  1736. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1737. common_chat_parse(
  1738. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1739. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1740. /* is_partial= */ false,
  1741. {
  1742. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1743. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  1744. }));
  1745. assert_msg_equals(
  1746. simple_assist_msg(
  1747. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1748. common_chat_parse(
  1749. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1750. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1751. /* is_partial= */ false,
  1752. {
  1753. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1754. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1755. /* .reasoning_in_content = */ true,
  1756. }));
  1757. // Test tool calling in role header
  1758. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1759. common_chat_parse(
  1760. " to=functions.special_function<|channel|>commentary <|constrain|>json<|message|>{\"arg1\": 1}",
  1761. /* is_partial= */ false,
  1762. {
  1763. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1764. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1765. }));
  1766. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1767. common_chat_parse(
  1768. " to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1769. /* is_partial= */ false,
  1770. {
  1771. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1772. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1773. }));
  1774. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1775. common_chat_parse(
  1776. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1777. "<|start|>assistant to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1778. /* is_partial= */ false,
  1779. {
  1780. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1781. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1782. }));
  1783. }
  1784. {
  1785. // Seed-OSS format tests
  1786. auto tmpls = read_templates("models/templates/ByteDance-Seed-OSS.jinja");
  1787. std::vector<std::string> end_tokens{ "<seed:eos>" };
  1788. assert_equals(COMMON_CHAT_FORMAT_SEED_OSS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1789. assert_equals(COMMON_CHAT_FORMAT_SEED_OSS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1790. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1791. // Test simple reasoning content
  1792. assert_msg_equals(
  1793. simple_assist_msg("Hello, world!", "I'm thinking about the answer"),
  1794. common_chat_parse(
  1795. "<seed:think>I'm thinking about the answer</seed:think>Hello, world!",
  1796. /* is_partial= */ false,
  1797. {
  1798. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1799. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1800. }));
  1801. // Test budget reflection tags
  1802. common_chat_msg msg_budget_reflect;
  1803. msg_budget_reflect.role = "assistant";
  1804. 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.";
  1805. msg_budget_reflect.reasoning_content = "Token usage: 45/1000\nI should continue thinking to find the best solution.";
  1806. assert_msg_equals(
  1807. msg_budget_reflect,
  1808. common_chat_parse(
  1809. "<seed:think>Token usage: 45/1000\nI should continue thinking to find the best solution.</seed:think>"
  1810. "<seed:cot_budget_reflect>Token usage: 45/1000\nI should continue thinking to find the best solution.</seed:cot_budget_reflect>"
  1811. "I need to calculate this step by step.",
  1812. /* is_partial= */ false,
  1813. {
  1814. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1815. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1816. }));
  1817. // Test tool calls with Seed-OSS format
  1818. common_chat_msg msg_tool_call;
  1819. msg_tool_call.role = "assistant";
  1820. msg_tool_call.tool_calls.push_back({"calculate_sum", "{\"numbers\": [1, 2, 3]}", ""});
  1821. assert_msg_equals(
  1822. msg_tool_call,
  1823. common_chat_parse(
  1824. "<seed:tool_call>\n"
  1825. "<function=calculate_sum>\n"
  1826. "<parameter=numbers>[1, 2, 3]</parameter>\n"
  1827. "</function>\n"
  1828. "</seed:tool_call>",
  1829. /* is_partial= */ false,
  1830. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1831. // Test reasoning + tool call combination
  1832. common_chat_msg msg_reasoning_tool;
  1833. msg_reasoning_tool.role = "assistant";
  1834. msg_reasoning_tool.content = "";
  1835. msg_reasoning_tool.reasoning_content = "I need to calculate the sum of these numbers";
  1836. msg_reasoning_tool.tool_calls.push_back({"calculate_sum", "{\"numbers\": [1, 2, 3]}", ""});
  1837. assert_msg_equals(
  1838. msg_reasoning_tool,
  1839. common_chat_parse(
  1840. "<seed:think>I need to calculate the sum of these numbers</seed:think>"
  1841. "<seed:tool_call>\n"
  1842. "<function=calculate_sum>\n"
  1843. "<parameter=numbers>[1, 2, 3]</parameter>\n"
  1844. "</function>\n"
  1845. "</seed:tool_call>",
  1846. /* is_partial= */ false,
  1847. {
  1848. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1849. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1850. }));
  1851. // Test deltas: the number of tool calls in partial parses should never decrease
  1852. std::string tool_msg = "<seed:tool_call>\n"
  1853. "<function=fun>\n"
  1854. "<parameter=smth>[1, 2, 3]</parameter>\n"
  1855. "</function>";
  1856. std::size_t previousToolCalls = 0;
  1857. for (std::size_t i = std::string("<seed:tool_call>").length(); i < tool_msg.length() - 1; i++) {
  1858. auto partial = tool_msg.substr(0, i);
  1859. auto partial_res = common_chat_parse(partial, true, { COMMON_CHAT_FORMAT_SEED_OSS, COMMON_REASONING_FORMAT_DEEPSEEK });
  1860. if (partial_res.tool_calls.size() < previousToolCalls) {
  1861. 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()));
  1862. }
  1863. previousToolCalls = partial_res.tool_calls.size();
  1864. }
  1865. // Test multiple parameters in tool call
  1866. common_chat_msg msg_multi_param;
  1867. msg_multi_param.role = "assistant";
  1868. msg_multi_param.tool_calls.push_back({"process_data", "{\"input\": \"test\", \"format\": \"json\"}", ""});
  1869. assert_msg_equals(
  1870. msg_multi_param,
  1871. common_chat_parse(
  1872. "<seed:tool_call>\n"
  1873. "<function=process_data>\n"
  1874. "<parameter=input>test</parameter>\n"
  1875. "<parameter=format>json</parameter>\n"
  1876. "</function>\n"
  1877. "</seed:tool_call>",
  1878. /* is_partial= */ false,
  1879. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1880. // Test partial parsing for incomplete tool call - don't actually add the call until parsing parameters is done
  1881. assert_msg_equals(
  1882. simple_assist_msg("", "", "calculate_sum", "{\"numbers\":"),
  1883. common_chat_parse(
  1884. "<seed:tool_call>\n"
  1885. "<function=calculate_sum>\n"
  1886. "<parameter=numbers>[1,\n",
  1887. /* is_partial= */ true,
  1888. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1889. // Test incomplete reasoning tag
  1890. assert_msg_equals(
  1891. simple_assist_msg("", "I was thinking"),
  1892. common_chat_parse(
  1893. "<seed:think>I was thinking",
  1894. /* is_partial= */ true,
  1895. {
  1896. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1897. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1898. }));
  1899. // Test content without reasoning
  1900. assert_msg_equals(
  1901. simple_assist_msg("This is a simple response without reasoning."),
  1902. common_chat_parse(
  1903. "This is a simple response without reasoning.",
  1904. /* is_partial= */ false,
  1905. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1906. }
  1907. {
  1908. auto tmpls = read_templates("models/templates/NVIDIA-Nemotron-Nano-v2.jinja");
  1909. std::vector<std::string> end_tokens{ "<SPECIAL_12>" };
  1910. assert_equals(COMMON_CHAT_FORMAT_NEMOTRON_V2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1911. assert_equals(COMMON_CHAT_FORMAT_NEMOTRON_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1912. // Test parsing regular content
  1913. assert_msg_equals(message_assist,
  1914. common_chat_parse(
  1915. "Hello, world!\nWhat's up?",
  1916. /* is_partial= */ false,
  1917. {COMMON_CHAT_FORMAT_NEMOTRON_V2}));
  1918. // Test parsing content with thinking
  1919. assert_msg_equals(message_assist_thoughts,
  1920. common_chat_parse(
  1921. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1922. /* is_partial= */ false,
  1923. {
  1924. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1925. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1926. }));
  1927. // Test parsing tool calls
  1928. assert_msg_equals(message_assist_call,
  1929. common_chat_parse(
  1930. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1931. /* is_partial= */ false,
  1932. {COMMON_CHAT_FORMAT_NEMOTRON_V2}));
  1933. // Test parsing tool calls with thinking
  1934. assert_msg_equals(message_assist_call_thoughts,
  1935. common_chat_parse(
  1936. "<think>I'm\nthinking</think><TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1937. /* is_partial= */ false,
  1938. {
  1939. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1940. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1941. }));
  1942. // Test tool calls with extra content
  1943. assert_msg_equals(message_assist_call_content,
  1944. common_chat_parse(
  1945. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>Hello, world!\nWhat's up?",
  1946. /* is_partial= */ false,
  1947. {COMMON_CHAT_FORMAT_NEMOTRON_V2}
  1948. ));
  1949. // Test tool calls with extra content AND thinking
  1950. assert_msg_equals(message_assist_call_thoughts_content,
  1951. common_chat_parse(
  1952. "<think>I'm\nthinking</think><TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>Hello, world!\nWhat's up?",
  1953. /* is_partial= */ false,
  1954. {
  1955. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1956. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1957. }));
  1958. // Test template generation for regular content
  1959. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1960. "Hello, world!\nWhat's up?\n",
  1961. /* expect_grammar_triggered= */ false);
  1962. // Test template generation for tool calls
  1963. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1964. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1965. /* expect_grammar_triggered= */ true
  1966. );
  1967. }
  1968. {
  1969. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-V3.1.jinja");
  1970. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1971. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  1972. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  1973. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_V3_1, params.format);
  1974. assert_equals(true, params.thinking_forced_open);
  1975. }
  1976. test_templates(tmpls.get(), end_tokens, message_assist, tools, "</think>Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1977. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "</think>Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1978. assert_msg_equals(
  1979. simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1980. common_chat_parse(
  1981. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1982. /* is_partial= */ false,
  1983. {
  1984. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1985. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1986. /* .reasoning_in_content = */ false,
  1987. /* .thinking_forced_open = */ true,
  1988. }));
  1989. // variant: thinking forced open, reasoning_format none
  1990. assert_msg_equals(
  1991. simple_assist_msg("REASONING</think>ok", ""),
  1992. common_chat_parse(
  1993. "REASONING</think>ok",
  1994. /* is_partial= */ false,
  1995. {
  1996. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1997. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  1998. /* .reasoning_in_content = */ false,
  1999. /* .thinking_forced_open = */ true,
  2000. /* .parse_tool_calls = */ true,
  2001. }));
  2002. // variant: happy path for when it works as the model card says it should
  2003. assert_msg_equals(
  2004. simple_assist_msg("", "", "get_time", "{\"city\":\"Tokyo\"}"),
  2005. common_chat_parse(
  2006. "<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  2007. /* is_partial= */ false,
  2008. {
  2009. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2010. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2011. /* .reasoning_in_content = */ false,
  2012. /* .thinking_forced_open = */ false,
  2013. /* .parse_tool_calls = */ true,
  2014. }));
  2015. // variant: simple + thinking open
  2016. assert_msg_equals(
  2017. simple_assist_msg("", "REASONING", "get_time", "{\"city\":\"Tokyo\"}"),
  2018. common_chat_parse(
  2019. "REASONING</think><|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  2020. /* is_partial= */ false,
  2021. {
  2022. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2023. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2024. /* .reasoning_in_content = */ false,
  2025. /* .thinking_forced_open = */ true,
  2026. /* .parse_tool_calls = */ true,
  2027. }));
  2028. // variant: simple + multiple tool calls
  2029. common_chat_msg message_assist_multiple_calls;
  2030. message_assist_multiple_calls.role = "assistant";
  2031. message_assist_multiple_calls.content = "CONTENT";
  2032. message_assist_multiple_calls.tool_calls.push_back({"get_time", "{\"city\":\"Paris\"}", ""});
  2033. message_assist_multiple_calls.tool_calls.push_back({"get_weather", "{\"city\":\"Paris\"}", ""});
  2034. assert_msg_equals(
  2035. message_assist_multiple_calls,
  2036. common_chat_parse(
  2037. "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|>",
  2038. /* is_partial= */ false,
  2039. {
  2040. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2041. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2042. /* .reasoning_in_content = */ false,
  2043. /* .thinking_forced_open = */ false,
  2044. /* .parse_tool_calls = */ true,
  2045. }));
  2046. // variant: thinking forced open + tool call in reasoning content
  2047. assert_msg_equals(
  2048. 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\"}"),
  2049. common_chat_parse(
  2050. "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|>",
  2051. /* is_partial= */ false,
  2052. {
  2053. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2054. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2055. /* .reasoning_in_content = */ false,
  2056. /* .thinking_forced_open = */ true,
  2057. /* .parse_tool_calls = */ true,
  2058. }));
  2059. // variant: thinking forced open + tool call in reasoning content + no closing think + not partial
  2060. // This is a bit of a fine tuning issue on the model's part IMO. It really should not be attempting
  2061. // to make tool calls in reasoning content according to the model card, but it does sometimes, so
  2062. // add the reasoning content as regular content and parse the tool calls.
  2063. assert_msg_equals(
  2064. simple_assist_msg("REASONING", "", "get_time", "{\"city\":\"Tokyo\"}"),
  2065. common_chat_parse(
  2066. "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  2067. /* is_partial= */ false,
  2068. {
  2069. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2070. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2071. /* .reasoning_in_content = */ false,
  2072. /* .thinking_forced_open = */ true,
  2073. /* .parse_tool_calls = */ true,
  2074. }));
  2075. // variant: thinking forced open + tool call in reasoning content + no closing think + partial
  2076. assert_msg_equals(
  2077. simple_assist_msg("", "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>", "", ""),
  2078. common_chat_parse(
  2079. "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  2080. /* is_partial= */ true,
  2081. {
  2082. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2083. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2084. /* .reasoning_in_content = */ false,
  2085. /* .thinking_forced_open = */ true,
  2086. /* .parse_tool_calls = */ true,
  2087. }));
  2088. // variant: thinking not forced open + missing reasoning + no tool calls
  2089. assert_msg_equals(
  2090. simple_assist_msg("CONTENT", ""),
  2091. common_chat_parse(
  2092. "CONTENT",
  2093. /* is_partial= */ false,
  2094. {
  2095. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2096. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2097. /* .reasoning_in_content = */ false,
  2098. /* .thinking_forced_open = */ false,
  2099. /* .parse_tool_calls = */ true,
  2100. }));
  2101. }
  2102. {
  2103. auto tmpls = read_templates("models/templates/Apertus-8B-Instruct.jinja");
  2104. std::vector<std::string> end_tokens{ "<|assistant_end|>" };
  2105. assert_equals(COMMON_CHAT_FORMAT_APERTUS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  2106. assert_equals(COMMON_CHAT_FORMAT_APERTUS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  2107. // Test parsing regular content
  2108. assert_msg_equals(message_assist,
  2109. common_chat_parse(
  2110. "Hello, world!\nWhat's up?",
  2111. /* is_partial= */ false,
  2112. {COMMON_CHAT_FORMAT_APERTUS}));
  2113. // Test parsing content with thinking
  2114. assert_msg_equals(message_assist_thoughts,
  2115. common_chat_parse(
  2116. "<|inner_prefix|>I'm\nthinking<|inner_suffix|>Hello, world!\nWhat's up?",
  2117. /* is_partial= */ false,
  2118. {
  2119. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  2120. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2121. }));
  2122. // Test parsing tool calls
  2123. assert_msg_equals(message_assist_call,
  2124. common_chat_parse(
  2125. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  2126. /* is_partial= */ false,
  2127. {COMMON_CHAT_FORMAT_APERTUS}));
  2128. // Test parsing tool calls with thinking
  2129. assert_msg_equals(message_assist_call_thoughts,
  2130. common_chat_parse(
  2131. "<|inner_prefix|>I'm\nthinking<|inner_suffix|><|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  2132. /* is_partial= */ false,
  2133. {
  2134. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  2135. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2136. }));
  2137. // Test tool calls with extra content
  2138. assert_msg_equals(message_assist_call_content,
  2139. common_chat_parse(
  2140. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>Hello, world!\nWhat's up?",
  2141. /* is_partial= */ false,
  2142. {COMMON_CHAT_FORMAT_APERTUS}
  2143. ));
  2144. // Test tool calls with extra content AND thinking
  2145. assert_msg_equals(message_assist_call_thoughts_content,
  2146. common_chat_parse(
  2147. "<|inner_prefix|>I'm\nthinking<|inner_suffix|><|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>Hello, world!\nWhat's up?",
  2148. /* is_partial= */ false,
  2149. {
  2150. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  2151. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2152. }));
  2153. // Test template generation for regular content
  2154. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  2155. "Hello, world!\nWhat's up?",
  2156. /* expect_grammar_triggered= */ false);
  2157. // Test template generation for tool calls
  2158. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  2159. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  2160. /* expect_grammar_triggered= */ true
  2161. );
  2162. assert_equals(true, common_chat_templates_support_enable_thinking(tmpls.get()));
  2163. }
  2164. {
  2165. // LFM2 format tests
  2166. auto tmpls = read_templates("models/templates/llama-cpp-lfm2.jinja");
  2167. std::vector<std::string> end_tokens{ "<|im_end|>" };
  2168. auto inputs_tools_forced_json_schema = std::invoke([&]() -> common_chat_templates_inputs {
  2169. common_chat_templates_inputs inputs;
  2170. inputs.messages = {
  2171. std::invoke([&]() -> common_chat_msg {
  2172. common_chat_msg msg;
  2173. msg.role = "system";
  2174. msg.content = "force json schema.\n";
  2175. return msg;
  2176. }),
  2177. message_user,
  2178. };
  2179. inputs.tools = {special_function_tool};
  2180. return inputs;
  2181. });
  2182. {
  2183. auto params = common_chat_templates_apply(tmpls.get(), inputs_no_tools);
  2184. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, params.format);
  2185. assert_equals(false, params.grammar_lazy);
  2186. assert_equals(std::string(R"(<|im_start|>user
  2187. Hey there!<|im_end|>
  2188. <|im_start|>assistant
  2189. )"), params.prompt);
  2190. }
  2191. {
  2192. auto params = common_chat_templates_apply(tmpls.get(), inputs_tools);
  2193. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, params.format);
  2194. assert_equals(false, params.grammar_lazy);
  2195. assert_equals(std::string(R"(<|im_start|>system
  2196. List of tools: <|tool_list_start|>[{"type": "function", "function": {"name": "special_function", "description": "I'm special", "parameters": {"type": "object", "properties": {"arg1": {"type": "integer", "description": "The arg."}}, "required": ["arg1"]}}}]<|tool_list_end|><|im_end|>
  2197. <|im_start|>user
  2198. Hey there!<|im_end|>
  2199. <|im_start|>assistant
  2200. )"), params.prompt);
  2201. assert_equals(true, params.grammar.empty());
  2202. }
  2203. {
  2204. auto params = common_chat_templates_apply(tmpls.get(), inputs_tools_forced_json_schema);
  2205. assert_equals(COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS, params.format);
  2206. assert_equals(true, params.grammar_lazy);
  2207. assert_equals(std::string(R"(<|im_start|>system
  2208. List of tools: <|tool_list_start|>[{"type": "function", "function": {"name": "special_function", "description": "I'm special", "parameters": {"type": "object", "properties": {"arg1": {"type": "integer", "description": "The arg."}}, "required": ["arg1"]}}}]<|tool_list_end|><|im_end|>
  2209. <|im_start|>user
  2210. Hey there!<|im_end|>
  2211. <|im_start|>assistant
  2212. )"), params.prompt);
  2213. assert_equals(false, params.grammar.empty());
  2214. }
  2215. // Test parsing regular content
  2216. assert_msg_equals(message_assist,
  2217. common_chat_parse(
  2218. "Hello, world!\nWhat's up?",
  2219. /* is_partial= */ false,
  2220. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2221. // Test single tool call with JSON format
  2222. common_chat_msg msg_single_tool_call;
  2223. msg_single_tool_call.role = "assistant";
  2224. msg_single_tool_call.tool_calls.push_back({"special_function", "{\"arg1\":1}", ""});
  2225. assert_msg_equals(
  2226. msg_single_tool_call,
  2227. common_chat_parse(
  2228. "<|tool_call_start|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]<|tool_call_end|>",
  2229. /* is_partial= */ false,
  2230. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2231. // Test tool call with string argument
  2232. common_chat_msg msg_tool_call_string;
  2233. msg_tool_call_string.role = "assistant";
  2234. msg_tool_call_string.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2235. assert_msg_equals(
  2236. msg_tool_call_string,
  2237. common_chat_parse(
  2238. "<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}]<|tool_call_end|>",
  2239. /* is_partial= */ false,
  2240. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2241. // Test tool call with multiple arguments
  2242. common_chat_msg msg_multi_args;
  2243. msg_multi_args.role = "assistant";
  2244. msg_multi_args.tool_calls.push_back({"calculate", "{\"x\":10,\"y\":20,\"operation\":\"add\"}", ""});
  2245. assert_msg_equals(
  2246. msg_multi_args,
  2247. common_chat_parse(
  2248. "<|tool_call_start|>[{\"name\": \"calculate\", \"arguments\": {\"x\": 10, \"y\": 20, \"operation\": \"add\"}}]<|tool_call_end|>",
  2249. /* is_partial= */ false,
  2250. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2251. // Test multiple tool calls in single array
  2252. common_chat_msg msg_multiple_tools;
  2253. msg_multiple_tools.role = "assistant";
  2254. msg_multiple_tools.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2255. msg_multiple_tools.tool_calls.push_back({"get_time", "{\"timezone\":\"UTC\"}", ""});
  2256. assert_msg_equals(
  2257. msg_multiple_tools,
  2258. common_chat_parse(
  2259. "<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}, {\"name\": \"get_time\", \"arguments\": {\"timezone\": \"UTC\"}}]<|tool_call_end|>",
  2260. /* is_partial= */ false,
  2261. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2262. // Test tool call with content before
  2263. common_chat_msg msg_content_before_tool;
  2264. msg_content_before_tool.role = "assistant";
  2265. msg_content_before_tool.content = "Let me check the weather for you.";
  2266. msg_content_before_tool.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2267. assert_msg_equals(
  2268. msg_content_before_tool,
  2269. common_chat_parse(
  2270. "Let me check the weather for you.<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}]<|tool_call_end|>",
  2271. /* is_partial= */ false,
  2272. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2273. // Test tool call with content after
  2274. common_chat_msg msg_content_after_tool;
  2275. msg_content_after_tool.role = "assistant";
  2276. msg_content_after_tool.content = "Here's the result.";
  2277. msg_content_after_tool.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2278. assert_msg_equals(
  2279. msg_content_after_tool,
  2280. common_chat_parse(
  2281. "<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}]<|tool_call_end|>Here's the result.",
  2282. /* is_partial= */ false,
  2283. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2284. // Test tool call with newlines (common in LLM output)
  2285. common_chat_msg msg_tool_call_newlines;
  2286. msg_tool_call_newlines.role = "assistant";
  2287. msg_tool_call_newlines.tool_calls.push_back({"get_current_time", "{\"location\":\"Paris\"}", ""});
  2288. assert_msg_equals(
  2289. msg_tool_call_newlines,
  2290. common_chat_parse(
  2291. "<|tool_call_start|>[{\n \"name\": \"get_current_time\",\n \"arguments\": {\n \"location\": \"Paris\"\n }\n}]<|tool_call_end|>",
  2292. /* is_partial= */ false,
  2293. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2294. // Note: LFM2 uses JSON format for tool calls: [{"name": "...", "arguments": {...}}]
  2295. // Unlike other formats, LFM2 template does not render tool calls in conversation history,
  2296. // so we don't use test_templates() for tool call generation. Instead, the parsing tests
  2297. // above verify edge cases and format variations for the tool call output format.
  2298. }
  2299. {
  2300. auto tmpls = read_templates("models/templates/MiniMax-M2.jinja");
  2301. std::vector<std::string> end_tokens{ "[e~[" };
  2302. assert_equals(COMMON_CHAT_FORMAT_MINIMAX_M2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  2303. assert_equals(COMMON_CHAT_FORMAT_MINIMAX_M2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  2304. // Test parsing regular content
  2305. assert_msg_equals(message_assist,
  2306. common_chat_parse(
  2307. "Hello, world!\nWhat's up?",
  2308. /* is_partial= */ false,
  2309. {COMMON_CHAT_FORMAT_MINIMAX_M2}));
  2310. // Test parsing content with thinking
  2311. assert_msg_equals(message_assist_thoughts,
  2312. common_chat_parse(
  2313. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  2314. /* is_partial= */ false,
  2315. {
  2316. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2317. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2318. }));
  2319. // Test parsing tool calls
  2320. assert_msg_equals(message_assist_call,
  2321. common_chat_parse(
  2322. "<minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>",
  2323. /* is_partial= */ false,
  2324. {COMMON_CHAT_FORMAT_MINIMAX_M2}));
  2325. // Test parsing tool calls with thinking
  2326. assert_msg_equals(message_assist_call_thoughts,
  2327. common_chat_parse(
  2328. "<think>I'm\nthinking</think><minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>",
  2329. /* is_partial= */ false,
  2330. {
  2331. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2332. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2333. }));
  2334. // Test tool calls with extra content
  2335. assert_msg_equals(message_assist_call_content,
  2336. common_chat_parse(
  2337. "<minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>Hello, world!\nWhat's up?",
  2338. /* is_partial= */ false,
  2339. {COMMON_CHAT_FORMAT_MINIMAX_M2}
  2340. ));
  2341. // Test tool calls with extra content AND thinking
  2342. assert_msg_equals(message_assist_call_thoughts_content,
  2343. common_chat_parse(
  2344. "<think>I'm\nthinking</think><minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>Hello, world!\nWhat's up?",
  2345. /* is_partial= */ false,
  2346. {
  2347. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2348. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2349. }));
  2350. // Test streaming
  2351. test_parser_with_streaming(message_assist_call_thoughts_content,
  2352. "<think>I'm\nthinking\n</think>Hello, world!\nWhat's up?\n<minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>",
  2353. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2354. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2355. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2356. }); });
  2357. test_parser_with_streaming(message_assist_call_thoughts_unparsed,
  2358. "<think>I'm\nthinking</think>\n\n<minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>",
  2359. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2360. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2361. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2362. }); });
  2363. test_parser_with_streaming(message_assist_call_thoughts_content,
  2364. "<think>I'm\nthinking\n</think>\n\nHello, world!\nWhat's up?\n\n<minimax:tool_call>\n<invoke name=\"special_function\">\n<parameter name=\"arg1\">1</parameter>\n</invoke>\n</minimax:tool_call>\n",
  2365. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2366. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2367. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2368. }); });
  2369. test_parser_with_streaming(message_assist_call_withopt,
  2370. "<minimax:tool_call>\n<invoke name=\"special_function_with_opt\">\n<parameter name=\"arg1\">1</parameter>\n<parameter name=\"arg2\">2</parameter>\n</invoke>\n</minimax:tool_call>",
  2371. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2372. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2373. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2374. }); });
  2375. // Test template generation for regular content
  2376. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  2377. "Hello, world!\nWhat's up?",
  2378. /* expect_grammar_triggered= */ false);
  2379. // Test template generation for tool calls
  2380. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  2381. "<minimax:tool_call>\n<invoke name=\"special_function\">\n<parameter name=\"arg1\">1</parameter>\n</invoke>\n</minimax:tool_call>",
  2382. /* expect_grammar_triggered= */ true,
  2383. /* test_grammar_if_triggered= */ true,
  2384. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_NONE,
  2385. /* ignore_whitespace_differences= */ true
  2386. );
  2387. // Test template generation for tools with optional parameters
  2388. test_templates(tmpls.get(), end_tokens, message_assist_call_noopt, tools,
  2389. "<minimax:tool_call>\n<invoke name=\"special_function_with_opt\">\n<parameter name=\"arg1\">1</parameter>\n</invoke>\n</minimax:tool_call>",
  2390. /* expect_grammar_triggered= */ true,
  2391. /* test_grammar_if_triggered= */ true,
  2392. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_NONE,
  2393. /* ignore_whitespace_differences= */ true
  2394. );
  2395. test_templates(tmpls.get(), end_tokens, message_assist_call_withopt, tools,
  2396. "<minimax:tool_call>\n<invoke name=\"special_function_with_opt\">\n<parameter name=\"arg1\">1</parameter>\n<parameter name=\"arg2\">2</parameter>\n</invoke>\n</minimax:tool_call>",
  2397. /* expect_grammar_triggered= */ true,
  2398. /* test_grammar_if_triggered= */ true,
  2399. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_NONE,
  2400. /* ignore_whitespace_differences= */ true
  2401. );
  2402. }
  2403. {
  2404. auto tmpls = read_templates("models/templates/GLM-4.6.jinja");
  2405. std::vector<std::string> end_tokens{ "<|assistant|>", "<|observation|>" };
  2406. assert_equals(COMMON_CHAT_FORMAT_GLM_4_5, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  2407. assert_equals(COMMON_CHAT_FORMAT_GLM_4_5, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  2408. // Test parsing regular content
  2409. assert_msg_equals(message_assist,
  2410. common_chat_parse(
  2411. "Hello, world!\nWhat's up?",
  2412. /* is_partial= */ false,
  2413. {COMMON_CHAT_FORMAT_GLM_4_5}));
  2414. // Test parsing content with thinking
  2415. assert_msg_equals(message_assist_thoughts,
  2416. common_chat_parse(
  2417. "\n<think>I'm\nthinking</think>\nHello, world!\nWhat's up?",
  2418. /* is_partial= */ false,
  2419. {
  2420. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2421. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2422. }), true);
  2423. // Test parsing tool calls
  2424. assert_msg_equals(message_assist_call,
  2425. common_chat_parse(
  2426. "\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>",
  2427. /* is_partial= */ false,
  2428. {COMMON_CHAT_FORMAT_GLM_4_5}), true);
  2429. // Test parsing tool calls with thinking
  2430. assert_msg_equals(message_assist_call_thoughts,
  2431. common_chat_parse(
  2432. "\n<think>I'm\nthinking</think>\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>",
  2433. /* is_partial= */ false,
  2434. {
  2435. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2436. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2437. }), true);
  2438. // Test tool calls with extra content
  2439. assert_msg_equals(message_assist_call_content,
  2440. common_chat_parse(
  2441. "\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>Hello, world!\nWhat's up?",
  2442. /* is_partial= */ false,
  2443. {COMMON_CHAT_FORMAT_GLM_4_5}
  2444. ), true);
  2445. // Test tool calls with extra content AND thinking
  2446. assert_msg_equals(message_assist_call_thoughts_content,
  2447. common_chat_parse(
  2448. "\n<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>",
  2449. /* is_partial= */ false,
  2450. {
  2451. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2452. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2453. }), true);
  2454. // Test streaming
  2455. test_parser_with_streaming(message_assist_call_thoughts_content,
  2456. "\n<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>",
  2457. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2458. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2459. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2460. }); });
  2461. test_parser_with_streaming(message_assist_call_thoughts_unparsed,
  2462. "\n<think>I'm\nthinking</think>\n\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>",
  2463. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2464. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2465. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2466. }); });
  2467. test_parser_with_streaming(message_assist_call_withopt,
  2468. "\n<think></think>\n<tool_call>special_function_with_opt\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n<arg_key>arg2</arg_key>\n<arg_value>2</arg_value>\n</tool_call>\n",
  2469. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2470. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2471. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2472. }); });
  2473. test_parser_with_streaming(
  2474. simple_assist_msg("", "", "complex_function", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}"),
  2475. "<tool_call>complex_function\n"
  2476. "<arg_key>name</arg_key>\n"
  2477. "<arg_value>John Doe</arg_value>\n"
  2478. "<arg_key>age</arg_key>\n"
  2479. "<arg_value>30</arg_value>\n"
  2480. "<arg_key>active</arg_key>\n"
  2481. "<arg_value>true</arg_value>\n"
  2482. "<arg_key>score</arg_key>\n"
  2483. "<arg_value>95.5</arg_value>\n"
  2484. "</tool_call>",
  2485. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_GLM_4_5}); });
  2486. test_parser_with_streaming(
  2487. simple_assist_msg("", "", "web_search", "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}"),
  2488. "<tool_call>web_search\n"
  2489. "<arg_key>query</arg_key>\n"
  2490. "<arg_value>\"From Zero\" Linkin Park album tracklist complete songs</arg_value>\n"
  2491. "<arg_key>limit</arg_key>\n"
  2492. "<arg_value>3</arg_value>\n"
  2493. "<arg_key>type</arg_key>\n"
  2494. "<arg_value>text</arg_value>\n"
  2495. "</tool_call>",
  2496. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_GLM_4_5}); });
  2497. // Test interleaved thinking
  2498. test_parser_with_streaming(simple_assist_msg("Hello, world!\n\nWhat's up?", "I'm\nthinkingThinking2", "special_function", "{\"arg1\": 1}"),
  2499. "\n<think>I'm\nthinking</think>Hello, world!\n<think>Thinking2</think>What's up?\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>",
  2500. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2501. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2502. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2503. }); });
  2504. test_parser_with_streaming(simple_assist_msg("\n<think>I'm\nthinking</think>Hello, world!\n<think>Thinking2</think>What's up?", "", "special_function", "{\"arg1\": 1}"),
  2505. "\n<think>I'm\nthinking</think>Hello, world!\n<think>Thinking2</think>What's up?\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>",
  2506. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2507. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2508. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2509. }); });
  2510. // Test template generation for regular content
  2511. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  2512. "\n<think></think>\nHello, world!\nWhat's up?",
  2513. /* expect_grammar_triggered= */ false);
  2514. // Test template generation for tool calls
  2515. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  2516. "\n<think></think>\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>\n",
  2517. /* expect_grammar_triggered= */ true,
  2518. /* test_grammar_if_triggered= */ false,
  2519. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2520. /* ignore_whitespace_differences= */ true
  2521. );
  2522. // Test template generation for tools with optional parameters
  2523. test_templates(tmpls.get(), end_tokens, message_assist_call_noopt, tools,
  2524. "\n<think></think>\n<tool_call>special_function_with_opt\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>\n",
  2525. /* expect_grammar_triggered= */ true,
  2526. /* test_grammar_if_triggered= */ false,
  2527. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2528. /* ignore_whitespace_differences= */ true
  2529. );
  2530. test_templates(tmpls.get(), end_tokens, message_assist_call_withopt, tools,
  2531. "\n<think></think>\n<tool_call>special_function_with_opt\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n<arg_key>arg2</arg_key>\n<arg_value>2</arg_value>\n</tool_call>\n",
  2532. /* expect_grammar_triggered= */ true,
  2533. /* test_grammar_if_triggered= */ false,
  2534. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2535. /* ignore_whitespace_differences= */ true
  2536. );
  2537. }
  2538. {
  2539. auto tmpls = read_templates("models/templates/Kimi-K2-Thinking.jinja");
  2540. std::vector<std::string> end_tokens{ "<|im_end|>" };
  2541. assert_equals(COMMON_CHAT_FORMAT_KIMI_K2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  2542. assert_equals(COMMON_CHAT_FORMAT_KIMI_K2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  2543. // Test parsing regular content
  2544. assert_msg_equals(message_assist,
  2545. common_chat_parse(
  2546. "Hello, world!\nWhat's up?",
  2547. /* is_partial= */ false,
  2548. {COMMON_CHAT_FORMAT_KIMI_K2}));
  2549. // Test parsing content with thinking
  2550. assert_msg_equals(message_assist_thoughts,
  2551. common_chat_parse(
  2552. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  2553. /* is_partial= */ false,
  2554. {
  2555. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2556. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2557. }));
  2558. // Test parsing tool calls
  2559. assert_msg_equals(message_assist_call,
  2560. common_chat_parse(
  2561. "<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>",
  2562. /* is_partial= */ false,
  2563. {COMMON_CHAT_FORMAT_KIMI_K2}));
  2564. // Test parsing tool calls with thinking
  2565. assert_msg_equals(message_assist_call_thoughts,
  2566. common_chat_parse(
  2567. "<think>I'm\nthinking</think><|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>",
  2568. /* is_partial= */ false,
  2569. {
  2570. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2571. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2572. }));
  2573. // Test tool calls with extra content
  2574. assert_msg_equals(message_assist_call_content,
  2575. common_chat_parse(
  2576. "<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>Hello, world!\nWhat's up?",
  2577. /* is_partial= */ false,
  2578. {COMMON_CHAT_FORMAT_KIMI_K2}
  2579. ));
  2580. // Test tool calls with extra content AND thinking
  2581. assert_msg_equals(message_assist_call_thoughts_content,
  2582. common_chat_parse(
  2583. "<think>I'm\nthinking</think><|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>Hello, world!\nWhat's up?",
  2584. /* is_partial= */ false,
  2585. {
  2586. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2587. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2588. }));
  2589. // Test streaming
  2590. test_parser_with_streaming(message_assist_call_thoughts_content,
  2591. "<think>I'm\nthinking\n</think>Hello, world!\nWhat's up?\n<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>",
  2592. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2593. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2594. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2595. }); });
  2596. test_parser_with_streaming(message_assist_call_thoughts_unparsed,
  2597. "<think>I'm\nthinking</think>\n\n<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>",
  2598. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2599. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2600. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2601. }); });
  2602. test_parser_with_streaming(message_assist_call_thoughts_content,
  2603. "<think>I'm\nthinking\n</think>\n\nHello, world!\nWhat's up?\n\n<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>\n",
  2604. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2605. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2606. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2607. }); });
  2608. test_parser_with_streaming(message_assist_call_withopt,
  2609. "<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function_with_opt:0<|tool_call_argument_begin|>{\"arg1\": 1, \"arg2\": 2}<|tool_call_end|><|tool_calls_section_end|>",
  2610. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2611. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2612. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2613. }); });
  2614. test_parser_with_streaming(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": \"123456\"}"),
  2615. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": \"123456\"}<|tool_call_end|><|tool_calls_section_end|>",
  2616. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2617. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2618. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2619. }); });
  2620. test_parser_with_streaming(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": [1, 2, \"345\", 6]}"),
  2621. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": [1, 2, \"345\", 6]}<|tool_call_end|><|tool_calls_section_end|>",
  2622. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2623. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2624. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2625. }); });
  2626. test_parser_with_streaming(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": {\"12\": 34, \"5\": [67, 8], \"9\": \"10\"}}"),
  2627. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": {\"12\": 34, \"5\": [67, 8], \"9\": \"10\"}}<|tool_call_end|><|tool_calls_section_end|>",
  2628. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2629. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2630. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2631. }); });
  2632. test_parser_with_streaming(
  2633. simple_assist_msg("", "", "complex_function", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}"),
  2634. "<|tool_calls_section_begin|><|tool_call_begin|>functions.complex_function:0<|tool_call_argument_begin|>"
  2635. "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}"
  2636. "<|tool_call_end|><|tool_calls_section_end|>",
  2637. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_KIMI_K2}); });
  2638. test_parser_with_streaming(
  2639. simple_assist_msg("", "", "web_search", "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}"),
  2640. "<|tool_calls_section_begin|><|tool_call_begin|>functions.web_search:0<|tool_call_argument_begin|>"
  2641. "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}"
  2642. "<|tool_call_end|><|tool_calls_section_end|>",
  2643. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_KIMI_K2}); });
  2644. test_parser_with_streaming(
  2645. simple_assist_msg("", "", "read_file", "{\"args\": [{\"path\": \"src/providers/ThemeProvider.tsx\"}, {\"path\": \"src/components/Header.tsx\"}, {\"path\": \"src/components/ThemeToggle.tsx\"}, {\"path\": \"src/app/globals.css\"}, {\"path\": \"src/app/layout.tsx\"}]}"),
  2646. "<|tool_calls_section_begin|><|tool_call_begin|>functions.read_file:0<|tool_call_argument_begin|>"
  2647. "{\"args\": [{\"path\": \"src/providers/ThemeProvider.tsx\"}, {\"path\": \"src/components/Header.tsx\"}, {\"path\": \"src/components/ThemeToggle.tsx\"}, {\"path\": \"src/app/globals.css\"}, {\"path\": \"src/app/layout.tsx\"}]}"
  2648. "<|tool_call_end|><|tool_calls_section_end|>",
  2649. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_KIMI_K2}); });
  2650. test_parser_with_streaming(
  2651. simple_assist_msg(
  2652. "Let me start by examining the relevant files to understand the current implementation.", "",
  2653. "read_file",
  2654. "{\"files\": [{\"path\": \"src/app/Partners.tsx\", \"line_ranges\": [\"1-100\"]}]}"),
  2655. "Let me start by examining the relevant files to understand the current implementation."
  2656. "<|tool_calls_section_begin|><|tool_call_begin|>functions.read_file:0<|tool_call_argument_begin|>"
  2657. "{\"files\":[{\"path\":\"src/app/Partners.tsx\",\"line_ranges\":[\"1-100\"]}]}"
  2658. "<|tool_call_end|><|tool_calls_section_end|>",
  2659. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_KIMI_K2}); });
  2660. auto multi_tool_msg = simple_assist_msg("Let me call multiple tools.", "I'm thinking.");
  2661. multi_tool_msg.tool_calls.push_back({ "read_file", "{\"files\": [{\"path\": \"src/app/Partners.tsx\", \"line_ranges\": [\"1-100\"]}]}", "" });
  2662. multi_tool_msg.tool_calls.push_back({ "web_search", "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}", "" });
  2663. multi_tool_msg.tool_calls.push_back({ "complex_function", "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}", "" });
  2664. multi_tool_msg.tool_calls.push_back({ "emoji_function", "{\"message\":\"Hello! 👋 🌟 🚀 Testing emojis: 😀😃😄😁 and symbols: ∑∏∆∇\"}", "" });
  2665. test_parser_with_streaming(multi_tool_msg,
  2666. "<think>I'm thinking.</think>Let me call multiple tools."
  2667. "<|tool_calls_section_begin|>"
  2668. "<|tool_call_begin|>functions.read_file:0<|tool_call_argument_begin|>"
  2669. "{\"files\":[{\"path\":\"src/app/Partners.tsx\",\"line_ranges\":[\"1-100\"]}]}"
  2670. "<|tool_call_end|>"
  2671. "<|tool_call_begin|>functions.web_search:1<|tool_call_argument_begin|>"
  2672. "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}"
  2673. "<|tool_call_end|>"
  2674. "<|tool_call_begin|>functions.complex_function:2<|tool_call_argument_begin|>"
  2675. "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}"
  2676. "<|tool_call_end|>"
  2677. "<|tool_call_begin|>functions.emoji_function:3<|tool_call_argument_begin|>"
  2678. "{\"message\":\"Hello! 👋 🌟 🚀 Testing emojis: 😀😃😄😁 and symbols: ∑∏∆∇\"}"
  2679. "<|tool_call_end|>"
  2680. "<|tool_calls_section_end|>",
  2681. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2682. COMMON_CHAT_FORMAT_KIMI_K2,
  2683. COMMON_REASONING_FORMAT_DEEPSEEK
  2684. }); });
  2685. test_parser_with_streaming(
  2686. simple_assist_msg("", "I'm thinking", "complex_function_in_think", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}"),
  2687. "<think>I'm thinking<|tool_calls_section_begin|><|tool_call_begin|>functions.complex_function_in_think:0<|tool_call_argument_begin|>"
  2688. "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}"
  2689. "<|tool_call_end|><|tool_calls_section_end|>",
  2690. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2691. COMMON_CHAT_FORMAT_KIMI_K2,
  2692. COMMON_REASONING_FORMAT_DEEPSEEK
  2693. }); });
  2694. test_parser_with_streaming(
  2695. simple_assist_msg("Hello", "I'm thinkingI'm still thinking", "complex_function_in_think", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}"),
  2696. "<think>I'm thinking<|tool_calls_section_begin|><|tool_call_begin|>functions.complex_function_in_think:0<|tool_call_argument_begin|>"
  2697. "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}"
  2698. "<|tool_call_end|><|tool_calls_section_end|>I'm still thinking</think>Hello",
  2699. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2700. COMMON_CHAT_FORMAT_KIMI_K2,
  2701. COMMON_REASONING_FORMAT_DEEPSEEK
  2702. }); });
  2703. // Test template rendering
  2704. common_chat_templates_inputs conversation_with_tools = inputs_tools;
  2705. conversation_with_tools.messages.push_back(simple_assist_msg("Let's do it", "Think first", "complex_function", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}"));
  2706. conversation_with_tools.messages.push_back({
  2707. "tool",
  2708. "Tool response 1",
  2709. /* .content_parts = */ {},
  2710. /* .tool_calls = */ {},
  2711. /* .reasoning_content = */ "",
  2712. /* .tool_name = */ "complex_function",
  2713. /* .tool_call_id = */ "",
  2714. });
  2715. conversation_with_tools.messages.push_back(simple_assist_msg("Continue", "Think next", "web_search", "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}"));
  2716. conversation_with_tools.messages.push_back({
  2717. "tool",
  2718. "Tool response 2",
  2719. /* .content_parts = */ {},
  2720. /* .tool_calls = */ {},
  2721. /* .reasoning_content = */ "",
  2722. /* .tool_name = */ "web_search",
  2723. /* .tool_call_id = */ "",
  2724. });
  2725. conversation_with_tools.messages.push_back(simple_assist_msg("CC", "Think last", "read_file", "{\"args\": [{\"path\": \"src/providers/ThemeProvider.tsx\"}, {\"path\": \"src/components/Header.tsx\"}, {\"path\": \"src/components/ThemeToggle.tsx\"}, {\"path\": \"src/app/globals.css\"}, {\"path\": \"src/app/layout.tsx\"}]}"));
  2726. conversation_with_tools.messages.push_back({
  2727. "tool",
  2728. "Tool response 3",
  2729. /* .content_parts = */ {},
  2730. /* .tool_calls = */ {},
  2731. /* .reasoning_content = */ "",
  2732. /* .tool_name = */ "read_file",
  2733. /* .tool_call_id = */ "",
  2734. });
  2735. assert_equals(common_chat_templates_apply(tmpls.get(), conversation_with_tools).prompt, std::string("<|im_system|>tool_declare<|im_middle|>[{\"type\": \"function\", \"function\": {\"name\": \"special_function\", \"description\": \"I'm special\", \"parameters\": {\"type\": \"object\", \"properties\": {\"arg1\": {\"type\": \"integer\", \"description\": \"The arg.\"}}, \"required\": [\"arg1\"]}}}]<|im_end|><|im_system|>system<|im_middle|>You are Kimi, an AI assistant created by Moonshot AI.<|im_end|><|im_user|>user<|im_middle|>Hey there!<|im_end|><|im_assistant|>assistant<|im_middle|><think>Think first</think>Let's do it<|tool_calls_section_begin|><|tool_call_begin|>functions.complex_function:0<|tool_call_argument_begin|>{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}<|tool_call_end|><|tool_calls_section_end|><|im_end|><|im_system|>complex_function<|im_middle|>## Return of functions.complex_function:0\nTool response 1<|im_end|><|im_assistant|>assistant<|im_middle|><think>Think next</think>Continue<|tool_calls_section_begin|><|tool_call_begin|>functions.web_search:1<|tool_call_argument_begin|>{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}<|tool_call_end|><|tool_calls_section_end|><|im_end|><|im_system|>web_search<|im_middle|>## Return of functions.web_search:1\nTool response 2<|im_end|><|im_assistant|>assistant<|im_middle|><think>Think last</think>CC<|tool_calls_section_begin|><|tool_call_begin|>functions.read_file:2<|tool_call_argument_begin|>{\"args\": [{\"path\": \"src/providers/ThemeProvider.tsx\"}, {\"path\": \"src/components/Header.tsx\"}, {\"path\": \"src/components/ThemeToggle.tsx\"}, {\"path\": \"src/app/globals.css\"}, {\"path\": \"src/app/layout.tsx\"}]}<|tool_call_end|><|tool_calls_section_end|><|im_end|><|im_system|>read_file<|im_middle|>## Return of functions.read_file:2\nTool response 3<|im_end|><|im_assistant|>assistant<|im_middle|>"));
  2736. // Test template generation for regular content
  2737. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  2738. "<think></think>Hello, world!\nWhat's up?",
  2739. /* expect_grammar_triggered= */ false);
  2740. // Test template generation for tool calls
  2741. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  2742. "<think></think><|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>",
  2743. /* expect_grammar_triggered= */ true,
  2744. /* test_grammar_if_triggered= */ true,
  2745. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2746. /* ignore_whitespace_differences= */ true
  2747. );
  2748. // Test template generation for tools with optional parameters
  2749. test_templates(tmpls.get(), end_tokens, message_assist_call_noopt, tools,
  2750. "<think></think><|tool_calls_section_begin|><|tool_call_begin|>functions.special_function_with_opt:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>",
  2751. /* expect_grammar_triggered= */ true,
  2752. /* test_grammar_if_triggered= */ true,
  2753. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2754. /* ignore_whitespace_differences= */ true
  2755. );
  2756. test_templates(tmpls.get(), end_tokens, message_assist_call_withopt, tools,
  2757. "<think></think><|tool_calls_section_begin|><|tool_call_begin|>functions.special_function_with_opt:0<|tool_call_argument_begin|>{\"arg1\": 1, \"arg2\": 2}<|tool_call_end|><|tool_calls_section_end|>",
  2758. /* expect_grammar_triggered= */ true,
  2759. /* test_grammar_if_triggered= */ true,
  2760. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2761. /* ignore_whitespace_differences= */ true
  2762. );
  2763. }
  2764. // Test Qwen3-Coder XML format
  2765. {
  2766. // Basic XML tool call parsing
  2767. assert_msg_equals(
  2768. message_assist_call,
  2769. common_chat_parse(
  2770. "<tool_call>\n"
  2771. " <function=special_function>\n"
  2772. " <parameter=arg1>\n"
  2773. " 1\n"
  2774. " </parameter>\n"
  2775. " </function>\n"
  2776. "</tool_call>",
  2777. /* is_partial= */ false,
  2778. {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}));
  2779. // Multiple parameters with different types
  2780. common_chat_msg expected_multi_param;
  2781. expected_multi_param.role = "assistant";
  2782. expected_multi_param.tool_calls = {
  2783. { "complex_function", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}", "" }
  2784. };
  2785. test_parser_with_streaming(expected_multi_param,
  2786. "<tool_call>\n"
  2787. " <function=complex_function>\n"
  2788. " <parameter=name>\n"
  2789. " John Doe\n"
  2790. " </parameter>\n"
  2791. " <parameter=age>\n"
  2792. " 30\n"
  2793. " </parameter>\n"
  2794. " <parameter=active>\n"
  2795. " true\n"
  2796. " </parameter>\n"
  2797. " <parameter=score>\n"
  2798. " 95.5\n"
  2799. " </parameter>\n"
  2800. " </function>\n"
  2801. "</tool_call>",
  2802. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2803. // Special characters and Unicode
  2804. common_chat_msg expected_special_chars;
  2805. expected_special_chars.role = "assistant";
  2806. expected_special_chars.tool_calls = {
  2807. { "unicode_function", "{\"message\":\"Hello 世界! 🌍 Special chars: @#$%^&*()\"}", "" }
  2808. };
  2809. test_parser_with_streaming(expected_special_chars,
  2810. "<tool_call>\n"
  2811. " <function=unicode_function>\n"
  2812. " <parameter=message>\n"
  2813. " Hello 世界! 🌍 Special chars: @#$%^&*()\n"
  2814. " </parameter>\n"
  2815. " </function>\n"
  2816. "</tool_call>",
  2817. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2818. // Multiline content with newlines and indentation
  2819. common_chat_msg expected_multiline;
  2820. expected_multiline.role = "assistant";
  2821. expected_multiline.tool_calls = {
  2822. { "code_function", "{\"code\":\"def hello():\\n print(\\\"Hello, World!\\\")\\n return True\"}", "" }
  2823. };
  2824. test_parser_with_streaming(expected_multiline,
  2825. "<tool_call>\n"
  2826. " <function=code_function>\n"
  2827. " <parameter=code>\n"
  2828. "def hello():\n"
  2829. " print(\"Hello, World!\")\n"
  2830. " return True\n"
  2831. " </parameter>\n"
  2832. " </function>\n"
  2833. "</tool_call>",
  2834. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2835. // JSON object as parameter value
  2836. common_chat_msg expected_json_param;
  2837. expected_json_param.role = "assistant";
  2838. expected_json_param.tool_calls = {
  2839. { "json_function", "{\"config\":{\"host\":\"localhost\",\"port\":8080,\"ssl\":false}}", "" }
  2840. };
  2841. test_parser_with_streaming(
  2842. expected_json_param,
  2843. "<tool_call>\n"
  2844. " <function=json_function>\n"
  2845. " <parameter=config>\n"
  2846. " {\"host\": \"localhost\", \"port\": 8080, \"ssl\": false}\n"
  2847. " </parameter>\n"
  2848. " </function>\n"
  2849. "</tool_call>",
  2850. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2851. // Array as parameter value
  2852. common_chat_msg expected_array_param;
  2853. expected_array_param.role = "assistant";
  2854. expected_array_param.tool_calls = {
  2855. { "array_function", "{\"items\":[\"apple\",\"banana\",\"cherry\"]}", "" }
  2856. };
  2857. test_parser_with_streaming(
  2858. expected_array_param,
  2859. "<tool_call>\n"
  2860. " <function=array_function>\n"
  2861. " <parameter=items>\n"
  2862. " [\"apple\", \"banana\", \"cherry\"]\n"
  2863. " </parameter>\n"
  2864. " </function>\n"
  2865. "</tool_call>",
  2866. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2867. // Empty parameter
  2868. common_chat_msg expected_empty_param;
  2869. expected_empty_param.role = "assistant";
  2870. expected_empty_param.tool_calls = {
  2871. { "empty_function", "{\"empty_param\":\"\"}", "" }
  2872. };
  2873. test_parser_with_streaming(
  2874. expected_empty_param,
  2875. "<tool_call>\n"
  2876. " <function=empty_function>\n"
  2877. " <parameter=empty_param>\n"
  2878. " </parameter>\n"
  2879. " </function>\n"
  2880. "</tool_call>",
  2881. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2882. // Boolean values (true/false)
  2883. common_chat_msg expected_boolean;
  2884. expected_boolean.role = "assistant";
  2885. expected_boolean.tool_calls = {
  2886. { "boolean_function", "{\"enabled\":true,\"debug\":false}", "" }
  2887. };
  2888. test_parser_with_streaming(
  2889. expected_boolean,
  2890. "<tool_call>\n"
  2891. " <function=boolean_function>\n"
  2892. " <parameter=enabled>\n"
  2893. " true\n"
  2894. " </parameter>\n"
  2895. " <parameter=debug>\n"
  2896. " false\n"
  2897. " </parameter>\n"
  2898. " </function>\n"
  2899. "</tool_call>",
  2900. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2901. // Null value
  2902. common_chat_msg expected_null;
  2903. expected_null.role = "assistant";
  2904. expected_null.tool_calls = {
  2905. { "null_function", "{\"optional_param\":null}", "" }
  2906. };
  2907. test_parser_with_streaming(
  2908. expected_null,
  2909. "<tool_call>\n"
  2910. " <function=null_function>\n"
  2911. " <parameter=optional_param>\n"
  2912. " null\n"
  2913. " </parameter>\n"
  2914. " </function>\n"
  2915. "</tool_call>",
  2916. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2917. // Negative numbers and scientific notation
  2918. common_chat_msg expected_numbers;
  2919. expected_numbers.role = "assistant";
  2920. expected_numbers.tool_calls = {
  2921. { "math_function", "{\"negative\":-42,\"decimal\":-3.14,\"scientific\":1.23e-4}", "" }
  2922. };
  2923. test_parser_with_streaming(
  2924. expected_numbers,
  2925. "<tool_call>\n"
  2926. " <function=math_function>\n"
  2927. " <parameter=negative>\n"
  2928. " -42\n"
  2929. " </parameter>\n"
  2930. " <parameter=decimal>\n"
  2931. " -3.14\n"
  2932. " </parameter>\n"
  2933. " <parameter=scientific>\n"
  2934. " 1.23e-4\n"
  2935. " </parameter>\n"
  2936. " </function>\n"
  2937. "</tool_call>",
  2938. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2939. // XML-like content in parameters (should be escaped)
  2940. common_chat_msg expected_xml_content;
  2941. expected_xml_content.role = "assistant";
  2942. expected_xml_content.tool_calls = {
  2943. { "xml_function", "{\"xml_content\":\"<root><item>value</item></root>\"}", "" }
  2944. };
  2945. test_parser_with_streaming(
  2946. expected_xml_content,
  2947. "<tool_call>\n"
  2948. " <function=xml_function>\n"
  2949. " <parameter=xml_content>\n"
  2950. " <root><item>value</item></root>\n"
  2951. " </parameter>\n"
  2952. " </function>\n"
  2953. "</tool_call>",
  2954. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2955. // Quotes and escape characters
  2956. common_chat_msg expected_quotes;
  2957. expected_quotes.role = "assistant";
  2958. expected_quotes.tool_calls = {
  2959. { "quote_function", "{\"message\":\"She said \\\"Hello!\\\" and left.\"}", "" }
  2960. };
  2961. test_parser_with_streaming(
  2962. expected_quotes,
  2963. "<tool_call>\n"
  2964. " <function=quote_function>\n"
  2965. " <parameter=message>\n"
  2966. " She said \"Hello!\" and left.\n"
  2967. " </parameter>\n"
  2968. " </function>\n"
  2969. "</tool_call>",
  2970. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2971. // Long parameter value (simplified)
  2972. std::string long_text = "This is a long text parameter that should test the parser's ability to handle larger amounts of text data.";
  2973. common_chat_msg expected_long_text;
  2974. expected_long_text.role = "assistant";
  2975. expected_long_text.tool_calls = {
  2976. { "long_function", "{\"long_text\":\"" + long_text + "\"}", "" }
  2977. };
  2978. test_parser_with_streaming(
  2979. expected_long_text,
  2980. "<tool_call>\n"
  2981. " <function=long_function>\n"
  2982. " <parameter=long_text>\n"
  2983. " " + long_text + "\n"
  2984. " </parameter>\n"
  2985. " </function>\n"
  2986. "</tool_call>",
  2987. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2988. // Mixed content with text before and after tool call
  2989. common_chat_msg expected_mixed_content;
  2990. expected_mixed_content.role = "assistant";
  2991. expected_mixed_content.content = "I'll help you search for products. ";
  2992. expected_mixed_content.tool_calls = {
  2993. { "search_function", "{\"query\":\"laptops\"}", "" }
  2994. };
  2995. test_parser_with_streaming(
  2996. expected_mixed_content,
  2997. "I'll help you search for products. <tool_call>\n"
  2998. " <function=search_function>\n"
  2999. " <parameter=query>\n"
  3000. " laptops\n"
  3001. " </parameter>\n"
  3002. " </function>\n"
  3003. "</tool_call>",
  3004. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3005. // Compact format (no extra whitespace)
  3006. common_chat_msg expected_compact;
  3007. expected_compact.role = "assistant";
  3008. expected_compact.tool_calls = {
  3009. { "compact_function", "{\"param\":\"value\"}", "" }
  3010. };
  3011. test_parser_with_streaming(
  3012. expected_compact,
  3013. "<tool_call><function=compact_function><parameter=param>value</parameter></function></tool_call>",
  3014. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3015. // Function name with underscores and numbers
  3016. common_chat_msg expected_complex_name;
  3017. expected_complex_name.role = "assistant";
  3018. expected_complex_name.tool_calls = {
  3019. { "get_user_data_v2", "{\"user_id\":12345}", "" }
  3020. };
  3021. test_parser_with_streaming(
  3022. expected_complex_name,
  3023. "<tool_call>\n"
  3024. " <function=get_user_data_v2>\n"
  3025. " <parameter=user_id>\n"
  3026. " 12345\n"
  3027. " </parameter>\n"
  3028. " </function>\n"
  3029. "</tool_call>",
  3030. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3031. // Parameter names with underscores and numbers
  3032. common_chat_msg expected_complex_params;
  3033. expected_complex_params.role = "assistant";
  3034. expected_complex_params.tool_calls = {
  3035. { "test_function", "{\"param_1\":\"value1\",\"param_2_name\":\"value2\",\"param3\":123}", "" }
  3036. };
  3037. test_parser_with_streaming(
  3038. expected_complex_params,
  3039. "<tool_call>\n"
  3040. " <function=test_function>\n"
  3041. " <parameter=param_1>\n"
  3042. " value1\n"
  3043. " </parameter>\n"
  3044. " <parameter=param_2_name>\n"
  3045. " value2\n"
  3046. " </parameter>\n"
  3047. " <parameter=param3>\n"
  3048. " 123\n"
  3049. " </parameter>\n"
  3050. " </function>\n"
  3051. "</tool_call>",
  3052. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3053. // Very deeply nested XML content in parameter
  3054. common_chat_msg expected_deep_xml;
  3055. expected_deep_xml.role = "assistant";
  3056. expected_deep_xml.tool_calls = {
  3057. { "xml_parser", "{\"xml\":\"<root><level1><level2><level3>deep content</level3></level2></level1></root>\"}", "" }
  3058. };
  3059. test_parser_with_streaming(
  3060. expected_deep_xml,
  3061. "<tool_call>\n"
  3062. " <function=xml_parser>\n"
  3063. " <parameter=xml>\n"
  3064. " <root><level1><level2><level3>deep content</level3></level2></level1></root>\n"
  3065. " </parameter>\n"
  3066. " </function>\n"
  3067. "</tool_call>",
  3068. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3069. // Parameter with only whitespace
  3070. common_chat_msg expected_whitespace_param;
  3071. expected_whitespace_param.role = "assistant";
  3072. expected_whitespace_param.tool_calls = {
  3073. { "whitespace_function", "{\"spaces\":\"\"}", "" }
  3074. };
  3075. test_parser_with_streaming(
  3076. expected_whitespace_param,
  3077. "<tool_call>\n"
  3078. " <function=whitespace_function>\n"
  3079. " <parameter=spaces>\n"
  3080. " \n"
  3081. " </parameter>\n"
  3082. " </function>\n"
  3083. "</tool_call>",
  3084. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3085. // Parameter with tabs and mixed whitespace
  3086. common_chat_msg expected_mixed_whitespace;
  3087. expected_mixed_whitespace.role = "assistant";
  3088. expected_mixed_whitespace.tool_calls = {
  3089. { "tab_function", "{\"content\":\"line1\\n\\tindented line\\n spaces\"}", "" }
  3090. };
  3091. test_parser_with_streaming(
  3092. expected_mixed_whitespace,
  3093. "<tool_call>\n"
  3094. " <function=tab_function>\n"
  3095. " <parameter=content>\n"
  3096. "line1\n"
  3097. "\tindented line\n"
  3098. " spaces\n"
  3099. " </parameter>\n"
  3100. " </function>\n"
  3101. "</tool_call>",
  3102. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3103. // Control characters and special Unicode
  3104. common_chat_msg expected_control_chars;
  3105. expected_control_chars.role = "assistant";
  3106. expected_control_chars.tool_calls = {
  3107. { "control_function", "{\"text\":\"Line1\\nLine2\\tTabbed\\rCarriage return\"}", "" }
  3108. };
  3109. test_parser_with_streaming(
  3110. expected_control_chars,
  3111. "<tool_call>\n"
  3112. " <function=control_function>\n"
  3113. " <parameter=text>\n"
  3114. "Line1\nLine2\tTabbed\rCarriage return\n"
  3115. " </parameter>\n"
  3116. " </function>\n"
  3117. "</tool_call>",
  3118. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3119. // Emoji and extended Unicode characters
  3120. common_chat_msg expected_emoji;
  3121. expected_emoji.role = "assistant";
  3122. expected_emoji.tool_calls = {
  3123. { "emoji_function", "{\"message\":\"Hello! 👋 🌟 🚀 Testing emojis: 😀😃😄😁 and symbols: ∑∏∆∇\"}", "" }
  3124. };
  3125. test_parser_with_streaming(
  3126. expected_emoji,
  3127. "<tool_call>\n"
  3128. " <function=emoji_function>\n"
  3129. " <parameter=message>\n"
  3130. " Hello! 👋 🌟 🚀 Testing emojis: 😀😃😄😁 and symbols: ∑∏∆∇\n"
  3131. " </parameter>\n"
  3132. " </function>\n"
  3133. "</tool_call>",
  3134. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3135. // Mathematical expressions and formulas
  3136. common_chat_msg expected_math;
  3137. expected_math.role = "assistant";
  3138. expected_math.tool_calls = {
  3139. { "math_function", "{\"formula\":\"E = mc² and ∫f(x)dx = F(x) + C\"}", "" }
  3140. };
  3141. test_parser_with_streaming(
  3142. expected_math,
  3143. "<tool_call>\n"
  3144. " <function=math_function>\n"
  3145. " <parameter=formula>\n"
  3146. " E = mc² and ∫f(x)dx = F(x) + C\n"
  3147. " </parameter>\n"
  3148. " </function>\n"
  3149. "</tool_call>",
  3150. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3151. // SQL injection-like content (should be safely escaped)
  3152. common_chat_msg expected_sql;
  3153. expected_sql.role = "assistant";
  3154. expected_sql.tool_calls = {
  3155. { "sql_function", "{\"query\":\"SELECT * FROM users WHERE id = 1; DROP TABLE users; --\"}", "" }
  3156. };
  3157. test_parser_with_streaming(
  3158. expected_sql,
  3159. "<tool_call>\n"
  3160. " <function=sql_function>\n"
  3161. " <parameter=query>\n"
  3162. " SELECT * FROM users WHERE id = 1; DROP TABLE users; --\n"
  3163. " </parameter>\n"
  3164. " </function>\n"
  3165. "</tool_call>",
  3166. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3167. // HTML/XML injection content
  3168. common_chat_msg expected_html;
  3169. expected_html.role = "assistant";
  3170. expected_html.tool_calls = {
  3171. { "html_function", "{\"content\":\"<script>alert('xss')</script><img src=x onerror=alert(1)>\"}", "" }
  3172. };
  3173. test_parser_with_streaming(
  3174. expected_html,
  3175. "<tool_call>\n"
  3176. " <function=html_function>\n"
  3177. " <parameter=content>\n"
  3178. " <script>alert('xss')</script><img src=x onerror=alert(1)>\n"
  3179. " </parameter>\n"
  3180. " </function>\n"
  3181. "</tool_call>",
  3182. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3183. // Binary-like content (base64)
  3184. common_chat_msg expected_binary;
  3185. expected_binary.role = "assistant";
  3186. expected_binary.tool_calls = {
  3187. { "binary_function", "{\"data\":\"SGVsbG8gV29ybGQhIFRoaXMgaXMgYmFzZTY0IGVuY29kZWQgdGV4dC4=\"}", "" }
  3188. };
  3189. test_parser_with_streaming(
  3190. expected_binary,
  3191. "<tool_call>\n"
  3192. " <function=binary_function>\n"
  3193. " <parameter=data>\n"
  3194. " SGVsbG8gV29ybGQhIFRoaXMgaXMgYmFzZTY0IGVuY29kZWQgdGV4dC4=\n"
  3195. " </parameter>\n"
  3196. " </function>\n"
  3197. "</tool_call>",
  3198. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3199. // Very large numbers (should be parsed as scientific notation)
  3200. common_chat_msg expected_large_numbers;
  3201. expected_large_numbers.role = "assistant";
  3202. expected_large_numbers.tool_calls = {
  3203. { "number_function", "{\"big_int\":1e+60}", "" } // Large number becomes scientific notation
  3204. };
  3205. test_parser_with_streaming(
  3206. expected_large_numbers,
  3207. "<tool_call>\n"
  3208. " <function=number_function>\n"
  3209. " <parameter=big_int>\n"
  3210. " 999999999999999999999999999999999999999999999999999999999999\n"
  3211. " </parameter>\n"
  3212. " </function>\n"
  3213. "</tool_call>",
  3214. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3215. }
  3216. {
  3217. // Qwen3-Coder template
  3218. auto tmpls = read_templates("models/templates/Qwen3-Coder.jinja");
  3219. common_chat_templates_inputs inputs;
  3220. inputs.messages = { message_user };
  3221. common_chat_tool qwen_union_tool {
  3222. /* .name = */ "qwen_union",
  3223. /* .description = */ "Test tool for union/anyOf handling",
  3224. /* .parameters = */ R"({
  3225. "type": "object",
  3226. "properties": {
  3227. "priority": { "type": ["number", "null"] },
  3228. "maybe_text": { "anyOf": [ { "type": "string" } ] },
  3229. "config": { "anyOf": [ { "type": "object" }, { "type": "null" } ] }
  3230. },
  3231. "required": []
  3232. })",
  3233. };
  3234. inputs.tools = { qwen_union_tool };
  3235. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  3236. assert_equals(COMMON_CHAT_FORMAT_QWEN3_CODER_XML, params.format);
  3237. assert_equals(false, params.grammar.empty());
  3238. // Grammar should compile successfully
  3239. auto grammar = build_grammar(params.grammar);
  3240. GGML_ASSERT(grammar && "Failed to build Qwen3-Coder grammar with union types");
  3241. }
  3242. }
  3243. static void test_template_output_peg_parsers() {
  3244. printf("[%s]\n", __func__);
  3245. // JSON schemas
  3246. const char * invoice_schema = R"({
  3247. "type": "object",
  3248. "properties": {
  3249. "amount": {"type": "number"},
  3250. "date": {"type": "string"}
  3251. }
  3252. })";
  3253. {
  3254. // Ministral-3-14B-Reasoning-2512
  3255. auto tmpls = read_templates("models/templates/mistralai-Ministral-3-14B-Reasoning-2512.jinja");
  3256. // Test basic message
  3257. test_peg_parser(tmpls.get(), [&](auto & t) {
  3258. t.input = "Hello, world!\nWhat's up?";
  3259. t.expect = message_assist;
  3260. });
  3261. // Test basic message and reasoning with reasoning_format = none
  3262. test_peg_parser(tmpls.get(), [&](auto & t) {
  3263. t.input = "[THINK]I'm\nthinking[/THINK]Hello, world!\nWhat's up?";
  3264. t.expect.content = "[THINK]I'm\nthinking[/THINK]Hello, world!\nWhat's up?";
  3265. });
  3266. // Test basic message and reasoning with reasoning_format = auto
  3267. test_peg_parser(tmpls.get(), [&](auto & t) {
  3268. t.input = "[THINK]I'm\nthinking[/THINK]Hello, world!\nWhat's up?";
  3269. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3270. t.expect = message_assist_thoughts;
  3271. });
  3272. // Test tool call
  3273. test_peg_parser(tmpls.get(), [&](auto & t) {
  3274. t.input = R"([TOOL_CALLS]special_function[ARGS]{"arg1":1})";
  3275. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3276. t.params.tools = {special_function_tool};
  3277. t.expect = message_assist_call;
  3278. });
  3279. // Test tool call with reasoning
  3280. test_peg_parser(tmpls.get(), [&](auto & t) {
  3281. t.input = "[THINK]I'm\nthinking[/THINK]"
  3282. R"([TOOL_CALLS]special_function[ARGS]{"arg1":1})";
  3283. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3284. t.params.tools = {special_function_tool};
  3285. t.expect = message_assist_call_thoughts;
  3286. });
  3287. // Test parallel tool calls
  3288. test_peg_parser(tmpls.get(), [&](auto & t) {
  3289. t.input = R"([TOOL_CALLS]special_function[ARGS]{"arg1": 1})"
  3290. R"([TOOL_CALLS]special_function_with_opt[ARGS]{"arg1": 1, "arg2": 2})";
  3291. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3292. t.params.parallel_tool_calls = true;
  3293. t.params.tools = {special_function_tool, special_function_tool_with_optional_param};
  3294. t.expect.tool_calls = {{
  3295. /* .name = */ "special_function",
  3296. /* .arguments = */ R"({"arg1": 1})",
  3297. /* .id = */ {},
  3298. }, {
  3299. /* .name = */ "special_function_with_opt",
  3300. /* .arguments = */ R"({"arg1": 1, "arg2": 2})",
  3301. /* .id = */ {},
  3302. }};
  3303. });
  3304. // Test response format
  3305. test_peg_parser(tmpls.get(), [&](auto & t) {
  3306. t.input = "[THINK]I need to output the invoice details in JSON[/THINK]"
  3307. "```json\n"
  3308. R"({"amount": 123.45, "date": "2025-12-03"})"
  3309. "\n```";
  3310. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3311. t.params.json_schema = invoice_schema;
  3312. t.expect.reasoning_content = "I need to output the invoice details in JSON";
  3313. t.expect.content =R"({"amount": 123.45, "date": "2025-12-03"})";
  3314. });
  3315. }
  3316. }
  3317. static void test_msg_diffs_compute() {
  3318. printf("[%s]\n", __func__);
  3319. {
  3320. common_chat_msg msg1;
  3321. common_chat_msg msg2;
  3322. msg2.content = "Hello, world!";
  3323. common_chat_msg_diff diff;
  3324. diff.content_delta = "Hello, world!";
  3325. assert_equals(
  3326. {diff},
  3327. common_chat_msg_diff::compute_diffs(msg1, msg2));
  3328. }
  3329. {
  3330. common_chat_msg msg1;
  3331. msg1.content = "Hello,";
  3332. common_chat_msg msg2;
  3333. msg2.content = "Hello, world!";
  3334. common_chat_msg_diff diff;
  3335. diff.content_delta = " world!";
  3336. assert_equals(
  3337. {diff},
  3338. common_chat_msg_diff::compute_diffs(msg1, msg2));
  3339. }
  3340. {
  3341. common_chat_msg msg0;
  3342. common_chat_msg msg1;
  3343. msg1.tool_calls = { { "special_function", "{\"ar", /* .id = */ "123" } };
  3344. common_chat_msg msg2;
  3345. msg2.tool_calls = { { "special_function", "{\"arg1\": 1}", /* .id = */ "123" } };
  3346. common_chat_msg_diff diff01;
  3347. diff01.tool_call_index = 0;
  3348. diff01.tool_call_delta.name = "special_function";
  3349. diff01.tool_call_delta.id = "123";
  3350. diff01.tool_call_delta.arguments = "{\"ar";
  3351. assert_equals(
  3352. {diff01},
  3353. common_chat_msg_diff::compute_diffs(msg0, msg1));
  3354. common_chat_msg_diff diff12;
  3355. diff12.tool_call_index = 0;
  3356. // Note: neither id nor name change here.
  3357. diff12.tool_call_delta.arguments = "g1\": 1}";
  3358. assert_equals(
  3359. {diff12},
  3360. common_chat_msg_diff::compute_diffs(msg1, msg2));
  3361. }
  3362. {
  3363. common_chat_msg msg0;
  3364. common_chat_msg msg2;
  3365. msg2.tool_calls = {
  3366. { "f1", "{\"arg1\": 1}", /* .id = */ "123" },
  3367. { "f2", "{\"arg2\": 2}", /* .id = */ "222" },
  3368. };
  3369. common_chat_msg_diff diff1;
  3370. diff1.tool_call_index = 0;
  3371. diff1.tool_call_delta.name = "f1";
  3372. diff1.tool_call_delta.id = "123";
  3373. diff1.tool_call_delta.arguments = "{\"arg1\": 1}";
  3374. common_chat_msg_diff diff2;
  3375. diff2.tool_call_index = 1;
  3376. diff2.tool_call_delta.name = "f2";
  3377. diff2.tool_call_delta.id = "222";
  3378. diff2.tool_call_delta.arguments = "{\"arg2\": 2}";
  3379. assert_equals(
  3380. {diff1, diff2},
  3381. common_chat_msg_diff::compute_diffs(msg0, msg2));
  3382. }
  3383. }
  3384. int main(int argc, char ** argv) {
  3385. common_log_set_verbosity_thold(999);
  3386. // try {
  3387. #ifndef _WIN32
  3388. if (argc > 1) {
  3389. common_chat_templates_inputs inputs;
  3390. common_chat_msg msg;
  3391. msg.role = "user";
  3392. msg.content = "Hey";
  3393. inputs.messages = {msg};
  3394. inputs.tools = { special_function_tool };
  3395. std::cout << "| Template | Format |\n";
  3396. std::cout << "|----------|--------|\n";
  3397. for (int i = 1; i < argc; i++) {
  3398. try {
  3399. std::string path = argv[i];
  3400. if (path.rfind(".jinja") != path.size() - 6) {
  3401. std::cerr << "Skipping non-jinja file: " << path << '\n';
  3402. continue;
  3403. }
  3404. auto tmpls = read_templates(path);
  3405. auto parts = string_split(path, "/");
  3406. auto name = parts[parts.size() - 1];
  3407. auto format = common_chat_format_name(common_chat_templates_apply(tmpls.get(), inputs).format);
  3408. std::cout << "| " << name << " | " << format << " |\n";
  3409. } catch (const std::exception & e) {
  3410. std::cerr << "Failed to process " << argv[i] << ": " << e.what() << '\n';
  3411. }
  3412. }
  3413. } else
  3414. #endif
  3415. {
  3416. test_msg_diffs_compute();
  3417. test_msgs_oaicompat_json_conversion();
  3418. test_tools_oaicompat_json_conversion();
  3419. test_template_output_parsers();
  3420. test_template_output_peg_parsers();
  3421. std::cout << "\n[chat] All tests passed!" << '\n';
  3422. }
  3423. return 0;
  3424. // } catch (const std::exception & e) {
  3425. // std::cerr << "Error: " << e.what() << '\n';
  3426. // return 1;
  3427. // }
  3428. }