test-chat.cpp 187 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913
  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:```\n" << expected << "\n```" << std::endl;
  77. std::cerr << "Actual:```\n" << actual << "\n```" << 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\": \"\",\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. auto tools_no_params = common_chat_tools_parse_oaicompat(json::parse(
  671. R"([{"type": "function", "function": {"name": "test_func", "description": "A test"}}])"));
  672. assert_equals((size_t) 1, tools_no_params.size());
  673. assert_equals(std::string("test_func"), tools_no_params[0].name);
  674. assert_equals(std::string("A test"), tools_no_params[0].description);
  675. assert_equals(std::string("{}"), tools_no_params[0].parameters);
  676. }
  677. {
  678. auto tools_no_desc = common_chat_tools_parse_oaicompat(json::parse(
  679. R"([{"type": "function", "function": {"name": "test_func", "parameters": {"type": "object"}}}])"));
  680. assert_equals((size_t) 1, tools_no_desc.size());
  681. assert_equals(std::string("test_func"), tools_no_desc[0].name);
  682. assert_equals(std::string(""), tools_no_desc[0].description);
  683. }
  684. {
  685. auto tools_minimal = common_chat_tools_parse_oaicompat(json::parse(
  686. R"([{"type": "function", "function": {"name": "test_func"}}])"));
  687. assert_equals((size_t) 1, tools_minimal.size());
  688. assert_equals(std::string("test_func"), tools_minimal[0].name);
  689. assert_equals(std::string(""), tools_minimal[0].description);
  690. assert_equals(std::string("{}"), tools_minimal[0].parameters);
  691. }
  692. }
  693. static void test_template_output_parsers() {
  694. printf("[%s]\n", __func__);
  695. common_chat_templates_inputs inputs_no_tools;
  696. inputs_no_tools.messages = {message_user};
  697. common_chat_templates_inputs inputs_tools;
  698. inputs_tools.messages = {message_user};
  699. inputs_tools.tools = {special_function_tool};
  700. common_chat_templates_inputs inputs_tools_builtin;
  701. inputs_tools_builtin.messages = {message_user};
  702. inputs_tools_builtin.tools = {python_tool};
  703. {
  704. // Not supported yet
  705. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r-plus-tool_use.jinja");
  706. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  707. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  708. }
  709. {
  710. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r7b-12-2024-tool_use.jinja");
  711. std::vector<std::string> end_tokens{ "<|END_OF_TURN_TOKEN|>" };
  712. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  713. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  714. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B, params.format);
  715. assert_equals(false, params.thinking_forced_open);
  716. }
  717. assert_msg_equals(message_assist,
  718. common_chat_parse(
  719. "Hello, world!\nWhat's up?",
  720. /* is_partial= */ false,
  721. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  722. assert_msg_equals(message_assist,
  723. common_chat_parse(
  724. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  725. /* is_partial= */ false,
  726. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  727. assert_msg_equals(message_assist_thoughts,
  728. common_chat_parse(
  729. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  730. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  731. /* is_partial= */ false,
  732. {
  733. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  734. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  735. }));
  736. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  737. common_chat_parse(
  738. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  739. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  740. /* is_partial= */ false,
  741. {
  742. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  743. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  744. /* .reasoning_in_content = */ true,
  745. /* .thinking_forced_open = */ false,
  746. }));
  747. assert_msg_equals(message_assist_thoughts_unparsed_r7b,
  748. common_chat_parse(
  749. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  750. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  751. /* is_partial= */ false,
  752. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  753. assert_msg_equals(message_assist_thoughts,
  754. common_chat_parse(
  755. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  756. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  757. /* is_partial= */ false,
  758. {
  759. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  760. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  761. }));
  762. assert_msg_equals(message_assist_thoughts_call_idx,
  763. common_chat_parse(
  764. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  765. "<|START_ACTION|>[\n"
  766. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  767. "]<|END_ACTION|>",
  768. /* is_partial= */ false,
  769. {
  770. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  771. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  772. }));
  773. assert_msg_equals(message_assist_thoughts_no_content,
  774. common_chat_parse(
  775. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  776. "<|START_ACTION|>[\n"
  777. " {\"tool_call_id\": \"0\", \"tool_name\": \"special",
  778. /* is_partial= */ true,
  779. {
  780. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  781. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  782. }));
  783. test_templates(tmpls.get(), end_tokens, message_assist_call_idx, tools,
  784. "<|START_THINKING|><|END_THINKING|>"
  785. "<|START_ACTION|>[\n"
  786. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  787. "]<|END_ACTION|>",
  788. /* expect_grammar_triggered= */ true,
  789. /* test_grammar_if_triggered= */ true,
  790. COMMON_REASONING_FORMAT_DEEPSEEK);
  791. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  792. "<|START_RESPONSE|>Hello, world!\n"
  793. "What's up?<|END_RESPONSE|>",
  794. /* expect_grammar_triggered= */ false);
  795. }
  796. // TODO @ngxson : generic tool calls is too costly to maintain, consider removing it in the future
  797. {
  798. auto tmpls = read_templates("models/templates/google-gemma-2-2b-it.jinja");
  799. std::vector<std::string> end_tokens{ "<end_of_turn>" };
  800. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  801. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  802. assert_equals(COMMON_CHAT_FORMAT_GENERIC,
  803. common_chat_templates_apply(
  804. read_templates("models/templates/microsoft-Phi-3.5-mini-instruct.jinja").get(),
  805. inputs_tools)
  806. .format);
  807. // Generic tool calls doesn't generate / parse content-only messages symmetrically.
  808. assert_equals(
  809. simple_assist_msg("{ \"tool_call\" : { \"name\" : \"t"),
  810. common_chat_parse(
  811. "{ \"tool_call\" : { \"name\" : \"t",
  812. /* is_partial= */ true,
  813. {
  814. /* .format = */ COMMON_CHAT_FORMAT_GENERIC,
  815. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  816. /* .reasoning_in_content = */ false,
  817. /* .thinking_forced_open = */ true,
  818. /* .parse_tool_calls = */ false,
  819. }));
  820. assert_equals(
  821. message_assist_empty,
  822. common_chat_parse(
  823. "{ \"tool_call\" : { \"name\" : \"t",
  824. /* is_partial= */ true,
  825. {COMMON_CHAT_FORMAT_GENERIC}));
  826. assert_equals(
  827. simple_assist_msg("", "", "puppeteer_screenshot", "{\"name\":\"servethehome_homepage\","),
  828. common_chat_parse(
  829. R"({"tool_call": {"name": "puppeteer_screenshot", "arguments": {"name": "servethehome_homepage",)",
  830. /* is_partial= */ true,
  831. {COMMON_CHAT_FORMAT_GENERIC}));
  832. assert_equals(
  833. message_assist_call_empty_args,
  834. common_chat_parse(
  835. "{ \"tool_call\" : { \"name\" : \"special_function\"",
  836. /* is_partial= */ true,
  837. {COMMON_CHAT_FORMAT_GENERIC}));
  838. assert_equals(
  839. message_assist_call_cutoff_args,
  840. common_chat_parse(
  841. "{ \"tool_call\" : { \"name\" : \"special_function\", \"arguments\" : { \"arg",
  842. /* is_partial= */ true,
  843. {COMMON_CHAT_FORMAT_GENERIC}));
  844. assert_msg_equals(message_assist,
  845. common_chat_parse(
  846. "{\n"
  847. " \"response\": \"Hello, world!\\nWhat's up?\"\n"
  848. "}",
  849. /* is_partial= */ false,
  850. {COMMON_CHAT_FORMAT_GENERIC}));
  851. #if 0
  852. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  853. "{\n"
  854. " \"tool_calls\": [\n"
  855. " {\n"
  856. " \"name\": \"special_function\",\n"
  857. " \"arguments\": {\n"
  858. " \"arg1\": 1\n"
  859. " },\n"
  860. " \"id\": \"123456789\"\n"
  861. " }\n"
  862. " ],\n"
  863. " \"content\": \"\"\n"
  864. "}");
  865. #endif
  866. }
  867. {
  868. auto tmpls = read_templates("models/templates/mistralai-Mistral-Nemo-Instruct-2407.jinja");
  869. std::vector<std::string> end_tokens{ "</s>" };
  870. assert_equals(COMMON_CHAT_FORMAT_MISTRAL_NEMO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  871. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  872. test_templates(
  873. tmpls.get(), end_tokens, message_assist_call_id, tools,
  874. "[TOOL_CALLS][{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, \"id\": \"123456789\"}]");
  875. }
  876. {
  877. assert_msg_equals(
  878. simple_assist_msg("Réponse", "raisonnement"),
  879. common_chat_parse(
  880. message_assist_thoughts_unparsed_magistral.content,
  881. /* is_partial= */ false,
  882. {
  883. /* .format = */ COMMON_CHAT_FORMAT_MAGISTRAL,
  884. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  885. }));
  886. }
  887. {
  888. auto tmpls = read_templates("models/templates/Qwen-QwQ-32B.jinja");
  889. std::vector<std::string> end_tokens{ "<|im_end|>" };
  890. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  891. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  892. }
  893. {
  894. auto tmpls = read_templates("models/templates/NousResearch-Hermes-2-Pro-Llama-3-8B-tool_use.jinja");
  895. std::vector<std::string> end_tokens{ "<|im_end|>" };
  896. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  897. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  898. assert_equals(
  899. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  900. common_chat_templates_apply(
  901. read_templates("models/templates/NousResearch-Hermes-3-Llama-3.1-8B-tool_use.jinja").get(),
  902. inputs_tools)
  903. .format);
  904. assert_equals(
  905. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  906. common_chat_templates_apply(
  907. read_templates("models/templates/Qwen-Qwen2.5-7B-Instruct.jinja").get(),
  908. inputs_tools)
  909. .format);
  910. // Test parsing
  911. assert_msg_equals(
  912. simple_assist_msg("", "", "python", ""),
  913. common_chat_parse(
  914. "```json\n"
  915. "<function_call> { \"name\" : \"python\"",
  916. /* is_partial= */ true,
  917. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  918. assert_msg_equals(
  919. simple_assist_msg("Let's call something\n"),
  920. common_chat_parse(
  921. "Let's call something\n"
  922. "<tool_call>{\"name\"",
  923. /* is_partial= */ true,
  924. {
  925. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  926. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  927. }));
  928. assert_msg_equals(
  929. simple_assist_msg("Let's call something\n"),
  930. common_chat_parse(
  931. "Let's call something\n"
  932. "<tool_call>{\"name",
  933. /* is_partial= */ true,
  934. {
  935. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  936. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  937. }));
  938. assert_msg_equals(message_assist_call_thoughts,
  939. common_chat_parse(
  940. // QwQ-32B's template adds a trailing <think> if add_generation_prompt
  941. "I'm\nthinking</think>\n"
  942. "<tool_call>{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}</tool_call>",
  943. /* is_partial= */ false,
  944. {
  945. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  946. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  947. /* .reasoning_in_content = */ false,
  948. /* .thinking_forced_open = */ true,
  949. }));
  950. assert_msg_equals(
  951. message_assist_call,
  952. common_chat_parse(
  953. "<tool_call>\n"
  954. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  955. "</tool_call>",
  956. /* is_partial= */ false,
  957. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  958. assert_msg_equals(message_assist_call_content,
  959. common_chat_parse(
  960. "Hello, world!\nWhat's up?<tool_call>\n"
  961. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  962. "</tool_call>",
  963. /* is_partial= */ false,
  964. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  965. assert_msg_equals(
  966. message_assist_call,
  967. common_chat_parse(
  968. "<function=special_function>{\"arg1\": 1}</function>",
  969. /* is_partial= */ false,
  970. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  971. assert_msg_equals(
  972. message_assist_call,
  973. common_chat_parse(
  974. "<function name=\"special_function\">\n"
  975. "{\"arg1\": 1}\n"
  976. "</function>",
  977. /* is_partial= */ false,
  978. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  979. assert_msg_equals(
  980. message_assist_call,
  981. common_chat_parse(
  982. "<tool>\n"
  983. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  984. "</tool>",
  985. /* is_partial= */ false,
  986. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  987. assert_msg_equals(
  988. message_assist_call,
  989. common_chat_parse(
  990. "<tools>\n"
  991. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  992. "</tools>",
  993. /* is_partial= */ false,
  994. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  995. assert_msg_equals(
  996. message_assist_call,
  997. common_chat_parse(
  998. "<response>\n"
  999. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1000. "</response>",
  1001. /* is_partial= */ false,
  1002. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1003. assert_msg_equals(
  1004. message_assist_call,
  1005. common_chat_parse(
  1006. "```xml\n"
  1007. "<response>\n"
  1008. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1009. "</response>\n"
  1010. "```",
  1011. /* is_partial= */ false,
  1012. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1013. assert_msg_equals(
  1014. message_assist_call,
  1015. common_chat_parse(
  1016. "```xml\n"
  1017. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1018. "```",
  1019. /* is_partial= */ false,
  1020. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1021. assert_msg_equals(
  1022. message_assist_call,
  1023. common_chat_parse(
  1024. "```\n"
  1025. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1026. "```",
  1027. /* is_partial= */ false,
  1028. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1029. assert_msg_equals(
  1030. message_assist_call,
  1031. common_chat_parse(
  1032. "```\n"
  1033. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1034. "```",
  1035. /* is_partial= */ false,
  1036. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1037. assert_msg_equals(
  1038. message_assist_call,
  1039. common_chat_parse(
  1040. "```json\n"
  1041. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1042. "```",
  1043. /* is_partial= */ false,
  1044. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1045. assert_msg_equals(
  1046. message_assist_call,
  1047. common_chat_parse(
  1048. "```json\n"
  1049. "\n"
  1050. " <function_call> {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}} \n"
  1051. " </function_call> \n"
  1052. "``` ",
  1053. /* is_partial= */ false,
  1054. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1055. assert_msg_equals(
  1056. message_assist_call,
  1057. common_chat_parse(
  1058. "<json>\n"
  1059. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1060. "</json>",
  1061. /* is_partial= */ false,
  1062. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1063. assert_msg_equals(
  1064. message_assist_call,
  1065. common_chat_parse(
  1066. "<xml>\n"
  1067. " {\n"
  1068. " \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}\n"
  1069. " }\n"
  1070. "</xml>",
  1071. /* is_partial= */ false,
  1072. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1073. assert_msg_equals(
  1074. message_assist_call,
  1075. common_chat_parse(
  1076. "<JSON>\n"
  1077. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1078. "</JSON>",
  1079. /* is_partial= */ false,
  1080. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1081. assert_msg_equals(
  1082. message_assist_call,
  1083. common_chat_parse(
  1084. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  1085. /* is_partial= */ false,
  1086. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1087. assert_msg_equals(
  1088. message_assist_call,
  1089. common_chat_parse(
  1090. "{\n \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  1091. /* is_partial= */ false,
  1092. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1093. // Test multiple tool calls
  1094. common_chat_msg message_assist_multiple_calls;
  1095. message_assist_multiple_calls.role = "assistant";
  1096. message_assist_multiple_calls.content = "";
  1097. message_assist_multiple_calls.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  1098. message_assist_multiple_calls.tool_calls.push_back({"python", "{\"code\":\"print('hello')\"}", ""});
  1099. assert_msg_equals(
  1100. message_assist_multiple_calls,
  1101. common_chat_parse(
  1102. "<tool_call>\n"
  1103. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1104. "</tool_call>\n"
  1105. "<tool_call>\n"
  1106. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('hello')\"}}\n"
  1107. "</tool_call>",
  1108. /* is_partial= */ false,
  1109. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1110. assert_msg_equals(
  1111. message_assist_multiple_calls,
  1112. common_chat_parse(
  1113. "<function=special_function>{\"arg1\": 1}</function>\n"
  1114. "<function=python>{\"code\":\"print('hello')\"}</function>",
  1115. /* is_partial= */ false,
  1116. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1117. assert_msg_equals(
  1118. simple_assist_msg(
  1119. "This is not a tool call:",
  1120. "",
  1121. "special_function",
  1122. "{\"arg1\": 1}"),
  1123. common_chat_parse(
  1124. "This is not a tool call:\n"
  1125. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  1126. /* is_partial= */ false,
  1127. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1128. assert_msg_equals(message_assist,
  1129. common_chat_parse(
  1130. "Hello, world!\nWhat's up?",
  1131. /* is_partial= */ false,
  1132. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1133. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1134. common_chat_parse(
  1135. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1136. /* is_partial= */ false,
  1137. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  1138. // assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1139. // common_chat_parse(
  1140. // "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1141. // COMMON_CHAT_FORMAT_HERMES_2_PRO));
  1142. assert_msg_equals(message_assist_thoughts,
  1143. common_chat_parse(
  1144. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1145. /* is_partial= */ false,
  1146. {
  1147. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1148. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1149. }));
  1150. assert_msg_equals(message_assist_thoughts,
  1151. common_chat_parse(
  1152. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1153. /* is_partial= */ true,
  1154. {
  1155. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1156. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1157. }));
  1158. assert_msg_equals(message_assist_thoughts_unparsed_md,
  1159. common_chat_parse(
  1160. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  1161. /* is_partial= */ false,
  1162. {
  1163. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1164. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1165. /* .reasoning_in_content = */ true,
  1166. /* .thinking_forced_open = */ false,
  1167. /* .parse_tool_calls = */ false,
  1168. }));
  1169. assert_msg_equals(message_assist_thoughts_unparsed_md_partial,
  1170. common_chat_parse(
  1171. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  1172. /* is_partial= */ true,
  1173. {
  1174. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1175. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1176. /* .reasoning_in_content = */ true,
  1177. /* .thinking_forced_open = */ false,
  1178. }));
  1179. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  1180. common_chat_parse(
  1181. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1182. /* is_partial= */ false,
  1183. {
  1184. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1185. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1186. }));
  1187. assert_msg_equals(message_assist_thoughts,
  1188. common_chat_parse(
  1189. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1190. /* is_partial= */ false,
  1191. {
  1192. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1193. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1194. /* .reasoning_in_content = */ false,
  1195. /* .thinking_forced_open = */ true,
  1196. }));
  1197. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1198. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1199. "<tool_call>\n"
  1200. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1201. "</tool_call>");
  1202. // Test multiple tool calls with template
  1203. common_chat_msg message_assist_multiple_calls_template;
  1204. message_assist_multiple_calls_template.role = "assistant";
  1205. message_assist_multiple_calls_template.content = "";
  1206. message_assist_multiple_calls_template.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  1207. message_assist_multiple_calls_template.tool_calls.push_back({"python", "{\"code\":\"print('test')\"}", ""});
  1208. test_templates(tmpls.get(), end_tokens, message_assist_multiple_calls_template, tools,
  1209. "<tool_call>\n"
  1210. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1211. "</tool_call>\n"
  1212. "<tool_call>\n"
  1213. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('test')\"}}\n"
  1214. "</tool_call>");
  1215. test_templates(tmpls.get(), end_tokens, message_assist_call_python_lines, tools,
  1216. "<tool_call>\n"
  1217. "{\"name\": \"python\", \"arguments\": {\"code\":\"# This is a program:\\nprint('hey')\"}}\n"
  1218. "</tool_call>");
  1219. assert_msg_equals(
  1220. simple_assist_msg("", /* reasoning_content= */ "<tool_call>nah uhg</tool_call>"),
  1221. common_chat_parse(
  1222. "<think><tool_call>nah uhg</tool_call>",
  1223. /* is_partial= */ false,
  1224. {
  1225. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1226. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1227. }));
  1228. }
  1229. {
  1230. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.1-8B-Instruct.jinja");
  1231. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1232. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1233. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1234. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1235. common_chat_templates_apply(tmpls.get(), inputs_tools_builtin).format);
  1236. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1237. common_chat_templates_apply(
  1238. read_templates("models/templates/meta-llama-Llama-3.3-70B-Instruct.jinja").get(),
  1239. inputs_tools_builtin)
  1240. .format);
  1241. assert_equals(
  1242. message_assist_call,
  1243. common_chat_parse(
  1244. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}",
  1245. /* is_partial= */ false,
  1246. {COMMON_CHAT_FORMAT_LLAMA_3_X}));
  1247. // test_templates(tmpls.get(), end_tokens, message_assist, tools, R"(?)", /* expect_grammar_triggered= */ false);
  1248. test_templates(tmpls.get(), end_tokens, message_assist_call_code_interpreter, llama_3_1_tools,
  1249. "<|python_tag|>code_interpreter.call(code=\"print('hey')\")");
  1250. test_templates(tmpls.get(), end_tokens, message_assist_call_python, tools,
  1251. "<|python_tag|>python.call(code=\"print('hey')\")");
  1252. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1253. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1254. }
  1255. {
  1256. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.2-3B-Instruct.jinja");
  1257. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1258. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1259. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  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. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1263. }
  1264. {
  1265. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.1.jinja");
  1266. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1267. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1268. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1269. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1,
  1270. common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1271. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1272. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1273. for (auto is_partial : { false, true }) {
  1274. assert_equals(
  1275. message_assist_call,
  1276. common_chat_parse(
  1277. "<function=special_function>{\"arg1\": 1}</function>",
  1278. is_partial,
  1279. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1280. }
  1281. assert_equals(
  1282. message_assist_call,
  1283. common_chat_parse(
  1284. "<function=special_function>{\"arg1\": 1}<",
  1285. /* is_partial= */ true,
  1286. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1287. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1288. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1289. "<function=special_function>{\"arg1\": 1}</function>");
  1290. }
  1291. {
  1292. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.2.jinja");
  1293. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1294. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1295. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1296. assert_msg_equals(
  1297. simple_assist_msg(
  1298. "Hello, world!\nnono\nWhat's up?",
  1299. "",
  1300. "special_function",
  1301. "{\"arg1\": 1}"),
  1302. common_chat_parse(
  1303. "all\n"
  1304. "Hello, world!\n"
  1305. "nono\n"
  1306. "What's up?>>>special_function\n"
  1307. "{\"arg1\": 1}\n",
  1308. /* is_partial= */ false,
  1309. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1310. assert_msg_equals(message_assist_call_python_lines,
  1311. common_chat_parse(
  1312. "python\n"
  1313. "# This is a program:\n"
  1314. "print('hey')",
  1315. /* is_partial= */ false,
  1316. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1317. assert_msg_equals(message_assist_call_python_lines_unclosed,
  1318. common_chat_parse(
  1319. "python\n"
  1320. "# This is a program:\n"
  1321. "print('hey')",
  1322. /* is_partial= */ true,
  1323. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1324. assert_msg_equals(message_assist_call,
  1325. common_chat_parse(
  1326. "special_function\n"
  1327. "{\"arg1\": 1} \n ",
  1328. /* is_partial= */ false,
  1329. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1330. assert_msg_equals(message_assist,
  1331. common_chat_parse(
  1332. "all\n"
  1333. "Hello, world!\nWhat's up?",
  1334. /* is_partial= */ false,
  1335. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1336. test_templates(tmpls.get(), end_tokens, message_assist, {},
  1337. "all\n"
  1338. "Hello, world!\n"
  1339. "What's up?",
  1340. /* expect_grammar_triggered= */ false);
  1341. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1342. "special_function\n"
  1343. "{\"arg1\": 1}");
  1344. }
  1345. {
  1346. auto tmpls = read_templates("models/templates/fireworks-ai-llama-3-firefunction-v2.jinja");
  1347. std::vector<std::string> end_tokens{ "<|eot_id|>" };
  1348. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1349. assert_equals(COMMON_CHAT_FORMAT_FIREFUNCTION_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1350. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1351. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1352. " functools[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]");
  1353. }
  1354. {
  1355. // Original DeepSeek R1 template. Leaves <|tool▁calls▁begin|> and others unclosed. Our logic fixes the prompt.
  1356. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-R1-Distill-Llama-8B.jinja");
  1357. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1358. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  1359. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  1360. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, params.format);
  1361. assert_equals(true, params.thinking_forced_open);
  1362. }
  1363. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1364. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1365. assert_msg_equals(
  1366. simple_assist_msg("Hello, world!\nWhat's up?", "<think>I'm\nthinking"),
  1367. common_chat_parse(
  1368. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1369. /* is_partial= */ false,
  1370. {
  1371. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1372. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1373. /* .reasoning_in_content = */ false,
  1374. /* .thinking_forced_open = */ true,
  1375. }));
  1376. assert_msg_equals(
  1377. simple_assist_msg("", "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with"),
  1378. common_chat_parse(
  1379. "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with",
  1380. /* is_partial= */ true,
  1381. {
  1382. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1383. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1384. /* .reasoning_in_content = */ false,
  1385. /* .thinking_forced_open = */ true,
  1386. }));
  1387. assert_msg_equals(message_assist_thoughts,
  1388. common_chat_parse(
  1389. "<think>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. }));
  1395. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  1396. common_chat_parse(
  1397. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1398. /* is_partial= */ false,
  1399. {
  1400. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1401. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1402. }));
  1403. assert_msg_equals(message_assist_thoughts,
  1404. common_chat_parse(
  1405. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1406. /* is_partial= */ false,
  1407. {
  1408. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1409. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1410. /* .reasoning_in_content = */ false,
  1411. /* .thinking_forced_open = */ true,
  1412. }));
  1413. assert_msg_equals(message_assist_thoughts,
  1414. // Latest template update (ast of 20250209) adds a trailing <think>\n if add_generation_prompt is true.
  1415. common_chat_parse(
  1416. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1417. /* is_partial= */ false,
  1418. {
  1419. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1420. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1421. /* .reasoning_in_content = */ false,
  1422. /* .thinking_forced_open = */ true,
  1423. }));
  1424. // test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1425. // "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1426. // "```json\n"
  1427. // "{\"arg1\": 1}\n"
  1428. // // 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)
  1429. // "```<|tool▁call▁end|>",
  1430. // /* expect_grammar_triggered= */ true,
  1431. // /* test_grammar_if_triggered= */ false);
  1432. }
  1433. {
  1434. // Replacement DeepSeek R1 template. Makes the Distill Qwen 7B/32B models happy to call tools and all.
  1435. auto tmpls = read_templates("models/templates/llama-cpp-deepseek-r1.jinja");
  1436. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1437. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1438. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1439. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1440. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1441. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1442. common_chat_parse(
  1443. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1444. /* is_partial= */ false,
  1445. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1446. assert_msg_equals(message_assist_thoughts,
  1447. common_chat_parse(
  1448. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1449. /* is_partial= */ false,
  1450. {
  1451. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1452. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1453. }));
  1454. assert_msg_equals(message_assist_thoughts,
  1455. common_chat_parse(
  1456. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1457. /* is_partial= */ false,
  1458. {
  1459. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1460. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1461. /* .reasoning_in_content = */ false,
  1462. /* .thinking_forced_open = */ true,
  1463. }));
  1464. assert_msg_equals(message_assist_call_thoughts_unparsed,
  1465. common_chat_parse(
  1466. "<think>I'm\nthinking</think>\n\n"
  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. /* is_partial= */ false,
  1472. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1473. assert_msg_equals(message_assist_call,
  1474. common_chat_parse(
  1475. "<|tool▁calls|>function<|tool▁sep|>special_function\n"
  1476. "```json\n"
  1477. "{\"arg1\": 1}\n"
  1478. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1479. /* is_partial= */ false,
  1480. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1481. assert_msg_equals(message_assist_call_thoughts,
  1482. common_chat_parse(
  1483. "<think>I'm\nthinking</think>\n\n"
  1484. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1485. "```json\n"
  1486. "{\"arg1\": 1}\n"
  1487. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1488. /* is_partial= */ false,
  1489. {
  1490. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1491. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1492. }));
  1493. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1494. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1495. "```json\n"
  1496. "{\"arg1\": 1}\n"
  1497. "```<|tool▁call▁end|><|tool▁calls▁end|>");
  1498. }
  1499. {
  1500. auto tmpls = read_templates("models/templates/ibm-granite-granite-3.3-2B-Instruct.jinja");
  1501. std::vector<std::string> end_tokens{ "<|end_of_text|>" };
  1502. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1503. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1504. // Test parsing regular content
  1505. assert_msg_equals(message_assist,
  1506. common_chat_parse(
  1507. "Hello, world!\nWhat's up?",
  1508. /* is_partial= */ false,
  1509. {COMMON_CHAT_FORMAT_GRANITE}));
  1510. assert_msg_equals(
  1511. message_assist,
  1512. common_chat_parse(
  1513. "Hello, world!\nWhat's up?",
  1514. /* is_partial= */ true,
  1515. {COMMON_CHAT_FORMAT_GRANITE}));
  1516. // Test parsing content with thinking
  1517. assert_msg_equals(message_assist_thoughts,
  1518. common_chat_parse(
  1519. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1520. /* is_partial= */ false,
  1521. {
  1522. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1523. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1524. }));
  1525. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1526. common_chat_parse(
  1527. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1528. /* is_partial= */ false,
  1529. {COMMON_CHAT_FORMAT_GRANITE}));
  1530. assert_msg_equals(message_assist_thoughts,
  1531. common_chat_parse(
  1532. "<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?",
  1533. /* is_partial= */ true,
  1534. {
  1535. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1536. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1537. }));
  1538. assert_msg_equals(message_assist_thoughts,
  1539. common_chat_parse(
  1540. "<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?</response>",
  1541. /* is_partial= */ false,
  1542. {
  1543. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1544. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1545. }));
  1546. assert_msg_equals(simple_assist_msg("<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?</response>"),
  1547. common_chat_parse(
  1548. "<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?</response>",
  1549. /* is_partial= */ false,
  1550. {COMMON_CHAT_FORMAT_GRANITE}));
  1551. assert_msg_equals(message_assist_empty,
  1552. common_chat_parse(
  1553. "<think",
  1554. /* is_partial= */ true,
  1555. {
  1556. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1557. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1558. }));
  1559. assert_msg_equals(message_assist_empty,
  1560. common_chat_parse(
  1561. "<think",
  1562. /* is_partial= */ true,
  1563. {COMMON_CHAT_FORMAT_GRANITE}));
  1564. assert_msg_equals(message_assist_thoughts_no_content,
  1565. common_chat_parse(
  1566. "<think>I'm\nthinking",
  1567. /* is_partial= */ true,
  1568. {
  1569. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1570. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1571. }));
  1572. assert_msg_equals(
  1573. message_assist_empty,
  1574. common_chat_parse(
  1575. "<think>I'm\nthinking</think><response",
  1576. /* is_partial= */ true,
  1577. {COMMON_CHAT_FORMAT_GRANITE}));
  1578. // Test parsing tool calls
  1579. assert_msg_equals(message_assist_call,
  1580. common_chat_parse(
  1581. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]",
  1582. /* is_partial= */ false,
  1583. {COMMON_CHAT_FORMAT_GRANITE}));
  1584. assert_msg_equals(
  1585. message_assist_call_empty_args,
  1586. common_chat_parse(
  1587. "<|tool_call|>[{\"name\": \"special_function\"",
  1588. /* is_partial= */ true,
  1589. {COMMON_CHAT_FORMAT_GRANITE}));
  1590. assert_msg_equals(
  1591. message_assist_call_cutoff_args,
  1592. common_chat_parse(
  1593. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg",
  1594. /* is_partial= */ true,
  1595. {COMMON_CHAT_FORMAT_GRANITE}));
  1596. assert_msg_equals(
  1597. message_assist_call_cutoff_args,
  1598. common_chat_parse(
  1599. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg",
  1600. /* is_partial= */ true,
  1601. {
  1602. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1603. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1604. }));
  1605. // Test parsing tool calls with thinking
  1606. assert_msg_equals(
  1607. message_assist_call_thoughts,
  1608. common_chat_parse(
  1609. "<think>I'm\nthinking</think><|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, {",
  1610. /* is_partial= */ true,
  1611. {
  1612. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1613. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1614. }));
  1615. // Test template generation for regular content
  1616. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1617. "Hello, world!\nWhat's up?",
  1618. /* expect_grammar_triggered= */ false);
  1619. // TODO @ngxson : generic tool call should be removed in the future
  1620. #if 0
  1621. // Test template generation for tool calls
  1622. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  1623. "{\n"
  1624. " \"tool_calls\": [\n"
  1625. " {\n"
  1626. " \"name\": \"special_function\",\n"
  1627. " \"arguments\": {\n"
  1628. " \"arg1\": 1\n"
  1629. " },\n"
  1630. " \"id\": \"123456789\"\n"
  1631. " }\n"
  1632. " ],\n"
  1633. " \"content\": \"\"\n"
  1634. "}",
  1635. /* expect_grammar_triggered= */ false
  1636. );
  1637. #endif
  1638. }
  1639. {
  1640. auto tmpls = read_templates("models/templates/openai-gpt-oss-120b.jinja");
  1641. std::vector<std::string> end_tokens{ "<|return|>", "<|call|>" };
  1642. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1643. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1644. assert_msg_equals(simple_assist_msg("", "I'm\nthink"),
  1645. common_chat_parse(
  1646. "<|channel|>analysis<|message|>I'm\nthink",
  1647. /* is_partial= */ true,
  1648. {
  1649. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1650. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1651. }));
  1652. assert_msg_equals(simple_assist_msg("", "I'm\nthinking"),
  1653. common_chat_parse(
  1654. "<|channel|>analysis<|message|>I'm\nthinking<|end|>",
  1655. /* is_partial= */ true,
  1656. {
  1657. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1658. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1659. }));
  1660. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1661. common_chat_parse(
  1662. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1663. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1664. /* is_partial= */ false,
  1665. {
  1666. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1667. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1668. }));
  1669. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1670. common_chat_parse(
  1671. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1672. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1",
  1673. /* is_partial= */ true,
  1674. {
  1675. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1676. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1677. }));
  1678. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1679. common_chat_parse(
  1680. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1681. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1682. /* is_partial= */ true,
  1683. {
  1684. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1685. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1686. }));
  1687. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1688. common_chat_parse(
  1689. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1690. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1691. /* is_partial= */ false,
  1692. {
  1693. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1694. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1695. }));
  1696. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1697. common_chat_parse(
  1698. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1699. "<|start|>assistant<|channel|>analysis to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1700. /* is_partial= */ false,
  1701. {
  1702. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1703. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1704. }));
  1705. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1706. common_chat_parse(
  1707. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1708. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?",
  1709. /* is_partial= */ true,
  1710. {
  1711. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1712. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1713. }));
  1714. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1715. common_chat_parse(
  1716. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1717. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?<|end|>"
  1718. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1719. /* is_partial= */ true,
  1720. {
  1721. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1722. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1723. }));
  1724. // Test parse_tool_calls == false
  1725. assert_msg_equals(
  1726. simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1727. common_chat_parse(
  1728. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1729. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1730. /* is_partial= */ true,
  1731. {
  1732. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1733. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1734. /* .reasoning_in_content = */ false,
  1735. /* .thinking_forced_open = */ false,
  1736. /* .parse_tool_calls = */ false,
  1737. }));
  1738. assert_msg_equals(
  1739. simple_assist_msg("", "I'm\nthinking"),
  1740. common_chat_parse(
  1741. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1742. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1743. /* is_partial= */ true,
  1744. {
  1745. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1746. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1747. /* .reasoning_in_content = */ false,
  1748. /* .thinking_forced_open = */ false,
  1749. /* .parse_tool_calls = */ false,
  1750. }));
  1751. assert_msg_equals(
  1752. simple_assist_msg("", "I'm\nthinking"),
  1753. common_chat_parse(
  1754. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1755. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1756. /* is_partial= */ false,
  1757. {
  1758. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1759. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1760. /* .reasoning_in_content = */ false,
  1761. /* .thinking_forced_open = */ false,
  1762. /* .parse_tool_calls = */ false,
  1763. }));
  1764. // Test reasoning formats
  1765. assert_msg_equals(
  1766. simple_assist_msg(
  1767. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1768. common_chat_parse(
  1769. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1770. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1771. /* is_partial= */ false,
  1772. {
  1773. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1774. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  1775. }));
  1776. assert_msg_equals(
  1777. simple_assist_msg(
  1778. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1779. common_chat_parse(
  1780. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1781. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1782. /* is_partial= */ false,
  1783. {
  1784. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1785. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1786. /* .reasoning_in_content = */ true,
  1787. }));
  1788. // Test tool calling in role header
  1789. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1790. common_chat_parse(
  1791. " to=functions.special_function<|channel|>commentary <|constrain|>json<|message|>{\"arg1\": 1}",
  1792. /* is_partial= */ false,
  1793. {
  1794. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1795. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1796. }));
  1797. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1798. common_chat_parse(
  1799. " to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1800. /* is_partial= */ false,
  1801. {
  1802. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1803. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1804. }));
  1805. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1806. common_chat_parse(
  1807. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1808. "<|start|>assistant to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1809. /* is_partial= */ false,
  1810. {
  1811. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1812. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1813. }));
  1814. }
  1815. {
  1816. // Seed-OSS format tests
  1817. auto tmpls = read_templates("models/templates/ByteDance-Seed-OSS.jinja");
  1818. std::vector<std::string> end_tokens{ "<seed:eos>" };
  1819. assert_equals(COMMON_CHAT_FORMAT_SEED_OSS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1820. assert_equals(COMMON_CHAT_FORMAT_SEED_OSS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1821. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1822. // Test simple reasoning content
  1823. assert_msg_equals(
  1824. simple_assist_msg("Hello, world!", "I'm thinking about the answer"),
  1825. common_chat_parse(
  1826. "<seed:think>I'm thinking about the answer</seed:think>Hello, world!",
  1827. /* is_partial= */ false,
  1828. {
  1829. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1830. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1831. }));
  1832. // Test budget reflection tags
  1833. common_chat_msg msg_budget_reflect;
  1834. msg_budget_reflect.role = "assistant";
  1835. 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.";
  1836. msg_budget_reflect.reasoning_content = "Token usage: 45/1000\nI should continue thinking to find the best solution.";
  1837. assert_msg_equals(
  1838. msg_budget_reflect,
  1839. common_chat_parse(
  1840. "<seed:think>Token usage: 45/1000\nI should continue thinking to find the best solution.</seed:think>"
  1841. "<seed:cot_budget_reflect>Token usage: 45/1000\nI should continue thinking to find the best solution.</seed:cot_budget_reflect>"
  1842. "I need to calculate this step by step.",
  1843. /* is_partial= */ false,
  1844. {
  1845. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1846. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1847. }));
  1848. // Test tool calls with Seed-OSS format
  1849. common_chat_msg msg_tool_call;
  1850. msg_tool_call.role = "assistant";
  1851. msg_tool_call.tool_calls.push_back({"calculate_sum", "{\"numbers\": [1, 2, 3]}", ""});
  1852. assert_msg_equals(
  1853. msg_tool_call,
  1854. common_chat_parse(
  1855. "<seed:tool_call>\n"
  1856. "<function=calculate_sum>\n"
  1857. "<parameter=numbers>[1, 2, 3]</parameter>\n"
  1858. "</function>\n"
  1859. "</seed:tool_call>",
  1860. /* is_partial= */ false,
  1861. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1862. // Test reasoning + tool call combination
  1863. common_chat_msg msg_reasoning_tool;
  1864. msg_reasoning_tool.role = "assistant";
  1865. msg_reasoning_tool.content = "";
  1866. msg_reasoning_tool.reasoning_content = "I need to calculate the sum of these numbers";
  1867. msg_reasoning_tool.tool_calls.push_back({"calculate_sum", "{\"numbers\": [1, 2, 3]}", ""});
  1868. assert_msg_equals(
  1869. msg_reasoning_tool,
  1870. common_chat_parse(
  1871. "<seed:think>I need to calculate the sum of these numbers</seed:think>"
  1872. "<seed:tool_call>\n"
  1873. "<function=calculate_sum>\n"
  1874. "<parameter=numbers>[1, 2, 3]</parameter>\n"
  1875. "</function>\n"
  1876. "</seed:tool_call>",
  1877. /* is_partial= */ false,
  1878. {
  1879. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1880. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1881. }));
  1882. // Test deltas: the number of tool calls in partial parses should never decrease
  1883. std::string tool_msg = "<seed:tool_call>\n"
  1884. "<function=fun>\n"
  1885. "<parameter=smth>[1, 2, 3]</parameter>\n"
  1886. "</function>";
  1887. std::size_t previousToolCalls = 0;
  1888. for (std::size_t i = std::string("<seed:tool_call>").length(); i < tool_msg.length() - 1; i++) {
  1889. auto partial = tool_msg.substr(0, i);
  1890. auto partial_res = common_chat_parse(partial, true, { COMMON_CHAT_FORMAT_SEED_OSS, COMMON_REASONING_FORMAT_DEEPSEEK });
  1891. if (partial_res.tool_calls.size() < previousToolCalls) {
  1892. 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()));
  1893. }
  1894. previousToolCalls = partial_res.tool_calls.size();
  1895. }
  1896. // Test multiple parameters in tool call
  1897. common_chat_msg msg_multi_param;
  1898. msg_multi_param.role = "assistant";
  1899. msg_multi_param.tool_calls.push_back({"process_data", "{\"input\": \"test\", \"format\": \"json\"}", ""});
  1900. assert_msg_equals(
  1901. msg_multi_param,
  1902. common_chat_parse(
  1903. "<seed:tool_call>\n"
  1904. "<function=process_data>\n"
  1905. "<parameter=input>test</parameter>\n"
  1906. "<parameter=format>json</parameter>\n"
  1907. "</function>\n"
  1908. "</seed:tool_call>",
  1909. /* is_partial= */ false,
  1910. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1911. // Test partial parsing for incomplete tool call - don't actually add the call until parsing parameters is done
  1912. assert_msg_equals(
  1913. simple_assist_msg("", "", "calculate_sum", "{\"numbers\":"),
  1914. common_chat_parse(
  1915. "<seed:tool_call>\n"
  1916. "<function=calculate_sum>\n"
  1917. "<parameter=numbers>[1,\n",
  1918. /* is_partial= */ true,
  1919. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1920. // Test incomplete reasoning tag
  1921. assert_msg_equals(
  1922. simple_assist_msg("", "I was thinking"),
  1923. common_chat_parse(
  1924. "<seed:think>I was thinking",
  1925. /* is_partial= */ true,
  1926. {
  1927. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1928. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1929. }));
  1930. // Test content without reasoning
  1931. assert_msg_equals(
  1932. simple_assist_msg("This is a simple response without reasoning."),
  1933. common_chat_parse(
  1934. "This is a simple response without reasoning.",
  1935. /* is_partial= */ false,
  1936. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1937. }
  1938. {
  1939. auto tmpls = read_templates("models/templates/NVIDIA-Nemotron-Nano-v2.jinja");
  1940. std::vector<std::string> end_tokens{ "<SPECIAL_12>" };
  1941. assert_equals(COMMON_CHAT_FORMAT_NEMOTRON_V2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1942. assert_equals(COMMON_CHAT_FORMAT_NEMOTRON_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1943. // Test parsing regular content
  1944. assert_msg_equals(message_assist,
  1945. common_chat_parse(
  1946. "Hello, world!\nWhat's up?",
  1947. /* is_partial= */ false,
  1948. {COMMON_CHAT_FORMAT_NEMOTRON_V2}));
  1949. // Test parsing content with thinking
  1950. assert_msg_equals(message_assist_thoughts,
  1951. common_chat_parse(
  1952. "<think>I'm\nthinking</think>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 parsing tool calls
  1959. assert_msg_equals(message_assist_call,
  1960. common_chat_parse(
  1961. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1962. /* is_partial= */ false,
  1963. {COMMON_CHAT_FORMAT_NEMOTRON_V2}));
  1964. // Test parsing tool calls with thinking
  1965. assert_msg_equals(message_assist_call_thoughts,
  1966. common_chat_parse(
  1967. "<think>I'm\nthinking</think><TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1968. /* is_partial= */ false,
  1969. {
  1970. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1971. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1972. }));
  1973. // Test tool calls with extra content
  1974. assert_msg_equals(message_assist_call_content,
  1975. common_chat_parse(
  1976. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>Hello, world!\nWhat's up?",
  1977. /* is_partial= */ false,
  1978. {COMMON_CHAT_FORMAT_NEMOTRON_V2}
  1979. ));
  1980. // Test tool calls with extra content AND thinking
  1981. assert_msg_equals(message_assist_call_thoughts_content,
  1982. common_chat_parse(
  1983. "<think>I'm\nthinking</think><TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>Hello, world!\nWhat's up?",
  1984. /* is_partial= */ false,
  1985. {
  1986. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1987. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1988. }));
  1989. // Test template generation for regular content
  1990. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1991. "Hello, world!\nWhat's up?\n",
  1992. /* expect_grammar_triggered= */ false);
  1993. // Test template generation for tool calls
  1994. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1995. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1996. /* expect_grammar_triggered= */ true
  1997. );
  1998. }
  1999. {
  2000. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-V3.1.jinja");
  2001. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  2002. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  2003. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  2004. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_V3_1, params.format);
  2005. assert_equals(true, params.thinking_forced_open);
  2006. }
  2007. test_templates(tmpls.get(), end_tokens, message_assist, tools, "</think>Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  2008. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "</think>Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  2009. assert_msg_equals(
  2010. simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  2011. common_chat_parse(
  2012. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  2013. /* is_partial= */ false,
  2014. {
  2015. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2016. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2017. /* .reasoning_in_content = */ false,
  2018. /* .thinking_forced_open = */ true,
  2019. }));
  2020. // variant: thinking forced open, reasoning_format none
  2021. assert_msg_equals(
  2022. simple_assist_msg("REASONING</think>ok", ""),
  2023. common_chat_parse(
  2024. "REASONING</think>ok",
  2025. /* is_partial= */ false,
  2026. {
  2027. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2028. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  2029. /* .reasoning_in_content = */ false,
  2030. /* .thinking_forced_open = */ true,
  2031. /* .parse_tool_calls = */ true,
  2032. }));
  2033. // variant: happy path for when it works as the model card says it should
  2034. assert_msg_equals(
  2035. simple_assist_msg("", "", "get_time", "{\"city\":\"Tokyo\"}"),
  2036. common_chat_parse(
  2037. "<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|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: simple + thinking open
  2047. assert_msg_equals(
  2048. simple_assist_msg("", "REASONING", "get_time", "{\"city\":\"Tokyo\"}"),
  2049. common_chat_parse(
  2050. "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: simple + multiple tool calls
  2060. common_chat_msg message_assist_multiple_calls;
  2061. message_assist_multiple_calls.role = "assistant";
  2062. message_assist_multiple_calls.content = "CONTENT";
  2063. message_assist_multiple_calls.tool_calls.push_back({"get_time", "{\"city\":\"Paris\"}", ""});
  2064. message_assist_multiple_calls.tool_calls.push_back({"get_weather", "{\"city\":\"Paris\"}", ""});
  2065. assert_msg_equals(
  2066. message_assist_multiple_calls,
  2067. common_chat_parse(
  2068. "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|>",
  2069. /* is_partial= */ false,
  2070. {
  2071. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2072. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2073. /* .reasoning_in_content = */ false,
  2074. /* .thinking_forced_open = */ false,
  2075. /* .parse_tool_calls = */ true,
  2076. }));
  2077. // variant: thinking forced open + tool call in reasoning content
  2078. assert_msg_equals(
  2079. 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\"}"),
  2080. common_chat_parse(
  2081. "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|>",
  2082. /* is_partial= */ false,
  2083. {
  2084. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2085. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2086. /* .reasoning_in_content = */ false,
  2087. /* .thinking_forced_open = */ true,
  2088. /* .parse_tool_calls = */ true,
  2089. }));
  2090. // variant: thinking forced open + tool call in reasoning content + no closing think + not partial
  2091. // This is a bit of a fine tuning issue on the model's part IMO. It really should not be attempting
  2092. // to make tool calls in reasoning content according to the model card, but it does sometimes, so
  2093. // add the reasoning content as regular content and parse the tool calls.
  2094. assert_msg_equals(
  2095. simple_assist_msg("REASONING", "", "get_time", "{\"city\":\"Tokyo\"}"),
  2096. common_chat_parse(
  2097. "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  2098. /* is_partial= */ false,
  2099. {
  2100. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2101. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2102. /* .reasoning_in_content = */ false,
  2103. /* .thinking_forced_open = */ true,
  2104. /* .parse_tool_calls = */ true,
  2105. }));
  2106. // variant: thinking forced open + tool call in reasoning content + no closing think + partial
  2107. assert_msg_equals(
  2108. simple_assist_msg("", "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>", "", ""),
  2109. common_chat_parse(
  2110. "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  2111. /* is_partial= */ true,
  2112. {
  2113. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2114. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2115. /* .reasoning_in_content = */ false,
  2116. /* .thinking_forced_open = */ true,
  2117. /* .parse_tool_calls = */ true,
  2118. }));
  2119. // variant: thinking not forced open + missing reasoning + no tool calls
  2120. assert_msg_equals(
  2121. simple_assist_msg("CONTENT", ""),
  2122. common_chat_parse(
  2123. "CONTENT",
  2124. /* is_partial= */ false,
  2125. {
  2126. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  2127. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2128. /* .reasoning_in_content = */ false,
  2129. /* .thinking_forced_open = */ false,
  2130. /* .parse_tool_calls = */ true,
  2131. }));
  2132. }
  2133. {
  2134. auto tmpls = read_templates("models/templates/Apertus-8B-Instruct.jinja");
  2135. std::vector<std::string> end_tokens{ "<|assistant_end|>" };
  2136. assert_equals(COMMON_CHAT_FORMAT_APERTUS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  2137. assert_equals(COMMON_CHAT_FORMAT_APERTUS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  2138. // Test parsing regular content
  2139. assert_msg_equals(message_assist,
  2140. common_chat_parse(
  2141. "Hello, world!\nWhat's up?",
  2142. /* is_partial= */ false,
  2143. {COMMON_CHAT_FORMAT_APERTUS}));
  2144. // Test parsing content with thinking
  2145. assert_msg_equals(message_assist_thoughts,
  2146. common_chat_parse(
  2147. "<|inner_prefix|>I'm\nthinking<|inner_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 parsing tool calls
  2154. assert_msg_equals(message_assist_call,
  2155. common_chat_parse(
  2156. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  2157. /* is_partial= */ false,
  2158. {COMMON_CHAT_FORMAT_APERTUS}));
  2159. // Test parsing tool calls with thinking
  2160. assert_msg_equals(message_assist_call_thoughts,
  2161. common_chat_parse(
  2162. "<|inner_prefix|>I'm\nthinking<|inner_suffix|><|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  2163. /* is_partial= */ false,
  2164. {
  2165. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  2166. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2167. }));
  2168. // Test tool calls with extra content
  2169. assert_msg_equals(message_assist_call_content,
  2170. common_chat_parse(
  2171. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>Hello, world!\nWhat's up?",
  2172. /* is_partial= */ false,
  2173. {COMMON_CHAT_FORMAT_APERTUS}
  2174. ));
  2175. // Test tool calls with extra content AND thinking
  2176. assert_msg_equals(message_assist_call_thoughts_content,
  2177. common_chat_parse(
  2178. "<|inner_prefix|>I'm\nthinking<|inner_suffix|><|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>Hello, world!\nWhat's up?",
  2179. /* is_partial= */ false,
  2180. {
  2181. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  2182. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2183. }));
  2184. // Test template generation for regular content
  2185. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  2186. "Hello, world!\nWhat's up?",
  2187. /* expect_grammar_triggered= */ false);
  2188. // Test template generation for tool calls
  2189. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  2190. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  2191. /* expect_grammar_triggered= */ true
  2192. );
  2193. // TODO @ngxson : not sure why this fails, but not very important for now
  2194. // assert_equals(true, common_chat_templates_support_enable_thinking(tmpls.get()));
  2195. }
  2196. {
  2197. // LFM2 format tests
  2198. auto tmpls = read_templates("models/templates/llama-cpp-lfm2.jinja");
  2199. std::vector<std::string> end_tokens{ "<|im_end|>" };
  2200. auto inputs_tools_forced_json_schema = std::invoke([&]() -> common_chat_templates_inputs {
  2201. common_chat_templates_inputs inputs;
  2202. inputs.messages = {
  2203. std::invoke([&]() -> common_chat_msg {
  2204. common_chat_msg msg;
  2205. msg.role = "system";
  2206. msg.content = "force json schema.\n";
  2207. return msg;
  2208. }),
  2209. message_user,
  2210. };
  2211. inputs.tools = {special_function_tool};
  2212. return inputs;
  2213. });
  2214. {
  2215. auto params = common_chat_templates_apply(tmpls.get(), inputs_no_tools);
  2216. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, params.format);
  2217. assert_equals(false, params.grammar_lazy);
  2218. assert_equals(std::string(R"(<|im_start|>user
  2219. Hey there!<|im_end|>
  2220. <|im_start|>assistant
  2221. )"), params.prompt);
  2222. }
  2223. {
  2224. auto params = common_chat_templates_apply(tmpls.get(), inputs_tools);
  2225. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, params.format);
  2226. assert_equals(false, params.grammar_lazy);
  2227. assert_equals(std::string(R"(<|im_start|>system
  2228. 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|>
  2229. <|im_start|>user
  2230. Hey there!<|im_end|>
  2231. <|im_start|>assistant
  2232. )"), params.prompt);
  2233. assert_equals(true, params.grammar.empty());
  2234. }
  2235. {
  2236. auto params = common_chat_templates_apply(tmpls.get(), inputs_tools_forced_json_schema);
  2237. assert_equals(COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS, params.format);
  2238. assert_equals(true, params.grammar_lazy);
  2239. assert_equals(std::string(R"(<|im_start|>system
  2240. 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|>
  2241. <|im_start|>user
  2242. Hey there!<|im_end|>
  2243. <|im_start|>assistant
  2244. )"), params.prompt);
  2245. assert_equals(false, params.grammar.empty());
  2246. }
  2247. // Test parsing regular content
  2248. assert_msg_equals(message_assist,
  2249. common_chat_parse(
  2250. "Hello, world!\nWhat's up?",
  2251. /* is_partial= */ false,
  2252. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2253. // Test single tool call with JSON format
  2254. common_chat_msg msg_single_tool_call;
  2255. msg_single_tool_call.role = "assistant";
  2256. msg_single_tool_call.tool_calls.push_back({"special_function", "{\"arg1\":1}", ""});
  2257. assert_msg_equals(
  2258. msg_single_tool_call,
  2259. common_chat_parse(
  2260. "<|tool_call_start|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]<|tool_call_end|>",
  2261. /* is_partial= */ false,
  2262. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2263. // Test tool call with string argument
  2264. common_chat_msg msg_tool_call_string;
  2265. msg_tool_call_string.role = "assistant";
  2266. msg_tool_call_string.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2267. assert_msg_equals(
  2268. msg_tool_call_string,
  2269. common_chat_parse(
  2270. "<|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 multiple arguments
  2274. common_chat_msg msg_multi_args;
  2275. msg_multi_args.role = "assistant";
  2276. msg_multi_args.tool_calls.push_back({"calculate", "{\"x\":10,\"y\":20,\"operation\":\"add\"}", ""});
  2277. assert_msg_equals(
  2278. msg_multi_args,
  2279. common_chat_parse(
  2280. "<|tool_call_start|>[{\"name\": \"calculate\", \"arguments\": {\"x\": 10, \"y\": 20, \"operation\": \"add\"}}]<|tool_call_end|>",
  2281. /* is_partial= */ false,
  2282. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2283. // Test multiple tool calls in single array
  2284. common_chat_msg msg_multiple_tools;
  2285. msg_multiple_tools.role = "assistant";
  2286. msg_multiple_tools.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2287. msg_multiple_tools.tool_calls.push_back({"get_time", "{\"timezone\":\"UTC\"}", ""});
  2288. assert_msg_equals(
  2289. msg_multiple_tools,
  2290. common_chat_parse(
  2291. "<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}, {\"name\": \"get_time\", \"arguments\": {\"timezone\": \"UTC\"}}]<|tool_call_end|>",
  2292. /* is_partial= */ false,
  2293. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2294. // Test tool call with content before
  2295. common_chat_msg msg_content_before_tool;
  2296. msg_content_before_tool.role = "assistant";
  2297. msg_content_before_tool.content = "Let me check the weather for you.";
  2298. msg_content_before_tool.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2299. assert_msg_equals(
  2300. msg_content_before_tool,
  2301. common_chat_parse(
  2302. "Let me check the weather for you.<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}]<|tool_call_end|>",
  2303. /* is_partial= */ false,
  2304. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2305. // Test tool call with content after
  2306. common_chat_msg msg_content_after_tool;
  2307. msg_content_after_tool.role = "assistant";
  2308. msg_content_after_tool.content = "Here's the result.";
  2309. msg_content_after_tool.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2310. assert_msg_equals(
  2311. msg_content_after_tool,
  2312. common_chat_parse(
  2313. "<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}]<|tool_call_end|>Here's the result.",
  2314. /* is_partial= */ false,
  2315. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2316. // Test tool call with newlines (common in LLM output)
  2317. common_chat_msg msg_tool_call_newlines;
  2318. msg_tool_call_newlines.role = "assistant";
  2319. msg_tool_call_newlines.tool_calls.push_back({"get_current_time", "{\"location\":\"Paris\"}", ""});
  2320. assert_msg_equals(
  2321. msg_tool_call_newlines,
  2322. common_chat_parse(
  2323. "<|tool_call_start|>[{\n \"name\": \"get_current_time\",\n \"arguments\": {\n \"location\": \"Paris\"\n }\n}]<|tool_call_end|>",
  2324. /* is_partial= */ false,
  2325. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2326. // Note: LFM2 uses JSON format for tool calls: [{"name": "...", "arguments": {...}}]
  2327. // Unlike other formats, LFM2 template does not render tool calls in conversation history,
  2328. // so we don't use test_templates() for tool call generation. Instead, the parsing tests
  2329. // above verify edge cases and format variations for the tool call output format.
  2330. }
  2331. {
  2332. auto tmpls = read_templates("models/templates/MiniMax-M2.jinja");
  2333. std::vector<std::string> end_tokens{ "[e~[" };
  2334. assert_equals(COMMON_CHAT_FORMAT_MINIMAX_M2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  2335. assert_equals(COMMON_CHAT_FORMAT_MINIMAX_M2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  2336. // Test parsing regular content
  2337. assert_msg_equals(message_assist,
  2338. common_chat_parse(
  2339. "Hello, world!\nWhat's up?",
  2340. /* is_partial= */ false,
  2341. {COMMON_CHAT_FORMAT_MINIMAX_M2}));
  2342. // Test parsing content with thinking
  2343. assert_msg_equals(message_assist_thoughts,
  2344. common_chat_parse(
  2345. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  2346. /* is_partial= */ false,
  2347. {
  2348. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2349. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2350. }));
  2351. // Test parsing tool calls
  2352. assert_msg_equals(message_assist_call,
  2353. common_chat_parse(
  2354. "<minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>",
  2355. /* is_partial= */ false,
  2356. {COMMON_CHAT_FORMAT_MINIMAX_M2}));
  2357. // Test parsing tool calls with thinking
  2358. assert_msg_equals(message_assist_call_thoughts,
  2359. common_chat_parse(
  2360. "<think>I'm\nthinking</think><minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>",
  2361. /* is_partial= */ false,
  2362. {
  2363. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2364. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2365. }));
  2366. // Test tool calls with extra content
  2367. assert_msg_equals(message_assist_call_content,
  2368. common_chat_parse(
  2369. "<minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>Hello, world!\nWhat's up?",
  2370. /* is_partial= */ false,
  2371. {COMMON_CHAT_FORMAT_MINIMAX_M2}
  2372. ));
  2373. // Test tool calls with extra content AND thinking
  2374. assert_msg_equals(message_assist_call_thoughts_content,
  2375. common_chat_parse(
  2376. "<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?",
  2377. /* is_partial= */ false,
  2378. {
  2379. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2380. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2381. }));
  2382. // Test streaming
  2383. test_parser_with_streaming(message_assist_call_thoughts_content,
  2384. "<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>",
  2385. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2386. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2387. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2388. }); });
  2389. test_parser_with_streaming(message_assist_call_thoughts_unparsed,
  2390. "<think>I'm\nthinking</think>\n\n<minimax:tool_call><invoke name=\"special_function\"><parameter name=\"arg1\">1</parameter></invoke></minimax:tool_call>",
  2391. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2392. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2393. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2394. }); });
  2395. test_parser_with_streaming(message_assist_call_thoughts_content,
  2396. "<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",
  2397. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2398. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2399. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2400. }); });
  2401. test_parser_with_streaming(message_assist_call_withopt,
  2402. "<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>",
  2403. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2404. /* .format = */ COMMON_CHAT_FORMAT_MINIMAX_M2,
  2405. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2406. }); });
  2407. // Test template generation for regular content
  2408. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  2409. "Hello, world!\nWhat's up?",
  2410. /* expect_grammar_triggered= */ false);
  2411. // Test template generation for tool calls
  2412. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  2413. "<minimax:tool_call>\n<invoke name=\"special_function\">\n<parameter name=\"arg1\">1</parameter>\n</invoke>\n</minimax:tool_call>",
  2414. /* expect_grammar_triggered= */ true,
  2415. /* test_grammar_if_triggered= */ true,
  2416. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_NONE,
  2417. /* ignore_whitespace_differences= */ true
  2418. );
  2419. // Test template generation for tools with optional parameters
  2420. test_templates(tmpls.get(), end_tokens, message_assist_call_noopt, tools,
  2421. "<minimax:tool_call>\n<invoke name=\"special_function_with_opt\">\n<parameter name=\"arg1\">1</parameter>\n</invoke>\n</minimax:tool_call>",
  2422. /* expect_grammar_triggered= */ true,
  2423. /* test_grammar_if_triggered= */ true,
  2424. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_NONE,
  2425. /* ignore_whitespace_differences= */ true
  2426. );
  2427. test_templates(tmpls.get(), end_tokens, message_assist_call_withopt, tools,
  2428. "<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>",
  2429. /* expect_grammar_triggered= */ true,
  2430. /* test_grammar_if_triggered= */ true,
  2431. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_NONE,
  2432. /* ignore_whitespace_differences= */ true
  2433. );
  2434. }
  2435. {
  2436. auto tmpls = read_templates("models/templates/GLM-4.6.jinja");
  2437. std::vector<std::string> end_tokens{ "<|assistant|>", "<|observation|>" };
  2438. assert_equals(COMMON_CHAT_FORMAT_GLM_4_5, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  2439. assert_equals(COMMON_CHAT_FORMAT_GLM_4_5, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  2440. // Test parsing regular content
  2441. assert_msg_equals(message_assist,
  2442. common_chat_parse(
  2443. "Hello, world!\nWhat's up?",
  2444. /* is_partial= */ false,
  2445. {COMMON_CHAT_FORMAT_GLM_4_5}));
  2446. // Test parsing content with thinking
  2447. assert_msg_equals(message_assist_thoughts,
  2448. common_chat_parse(
  2449. "\n<think>I'm\nthinking</think>\nHello, world!\nWhat's up?",
  2450. /* is_partial= */ false,
  2451. {
  2452. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2453. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2454. }), true);
  2455. // Test parsing tool calls
  2456. assert_msg_equals(message_assist_call,
  2457. common_chat_parse(
  2458. "\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>",
  2459. /* is_partial= */ false,
  2460. {COMMON_CHAT_FORMAT_GLM_4_5}), true);
  2461. // Test parsing tool calls with thinking
  2462. assert_msg_equals(message_assist_call_thoughts,
  2463. common_chat_parse(
  2464. "\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>",
  2465. /* is_partial= */ false,
  2466. {
  2467. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2468. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2469. }), true);
  2470. // Test tool calls with extra content
  2471. assert_msg_equals(message_assist_call_content,
  2472. common_chat_parse(
  2473. "\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?",
  2474. /* is_partial= */ false,
  2475. {COMMON_CHAT_FORMAT_GLM_4_5}
  2476. ), true);
  2477. // Test tool calls with extra content AND thinking
  2478. assert_msg_equals(message_assist_call_thoughts_content,
  2479. common_chat_parse(
  2480. "\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>",
  2481. /* is_partial= */ false,
  2482. {
  2483. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2484. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2485. }), true);
  2486. // Test streaming
  2487. test_parser_with_streaming(message_assist_call_thoughts_content,
  2488. "\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>",
  2489. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2490. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2491. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2492. }); });
  2493. test_parser_with_streaming(message_assist_call_thoughts_unparsed,
  2494. "\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>",
  2495. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2496. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2497. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2498. }); });
  2499. test_parser_with_streaming(message_assist_call_withopt,
  2500. "\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",
  2501. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2502. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2503. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2504. }); });
  2505. test_parser_with_streaming(
  2506. simple_assist_msg("", "", "complex_function", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}"),
  2507. "<tool_call>complex_function\n"
  2508. "<arg_key>name</arg_key>\n"
  2509. "<arg_value>John Doe</arg_value>\n"
  2510. "<arg_key>age</arg_key>\n"
  2511. "<arg_value>30</arg_value>\n"
  2512. "<arg_key>active</arg_key>\n"
  2513. "<arg_value>true</arg_value>\n"
  2514. "<arg_key>score</arg_key>\n"
  2515. "<arg_value>95.5</arg_value>\n"
  2516. "</tool_call>",
  2517. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_GLM_4_5}); });
  2518. test_parser_with_streaming(
  2519. simple_assist_msg("", "", "web_search", "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}"),
  2520. "<tool_call>web_search\n"
  2521. "<arg_key>query</arg_key>\n"
  2522. "<arg_value>\"From Zero\" Linkin Park album tracklist complete songs</arg_value>\n"
  2523. "<arg_key>limit</arg_key>\n"
  2524. "<arg_value>3</arg_value>\n"
  2525. "<arg_key>type</arg_key>\n"
  2526. "<arg_value>text</arg_value>\n"
  2527. "</tool_call>",
  2528. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_GLM_4_5}); });
  2529. // Test interleaved thinking
  2530. test_parser_with_streaming(simple_assist_msg("Hello, world!\n\nWhat's up?", "I'm\nthinkingThinking2", "special_function", "{\"arg1\": 1}"),
  2531. "\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>",
  2532. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2533. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2534. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2535. }); });
  2536. 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}"),
  2537. "\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>",
  2538. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2539. /* .format = */ COMMON_CHAT_FORMAT_GLM_4_5,
  2540. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2541. }); });
  2542. // Test template generation for regular content
  2543. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  2544. "\n<think></think>\nHello, world!\nWhat's up?",
  2545. /* expect_grammar_triggered= */ false);
  2546. // Test template generation for tool calls
  2547. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  2548. "\n<think></think>\n<tool_call>special_function\n<arg_key>arg1</arg_key>\n<arg_value>1</arg_value>\n</tool_call>\n",
  2549. /* expect_grammar_triggered= */ true,
  2550. /* test_grammar_if_triggered= */ false,
  2551. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2552. /* ignore_whitespace_differences= */ true
  2553. );
  2554. // Test template generation for tools with optional parameters
  2555. test_templates(tmpls.get(), end_tokens, message_assist_call_noopt, tools,
  2556. "\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",
  2557. /* expect_grammar_triggered= */ true,
  2558. /* test_grammar_if_triggered= */ false,
  2559. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2560. /* ignore_whitespace_differences= */ true
  2561. );
  2562. test_templates(tmpls.get(), end_tokens, message_assist_call_withopt, tools,
  2563. "\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",
  2564. /* expect_grammar_triggered= */ true,
  2565. /* test_grammar_if_triggered= */ false,
  2566. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2567. /* ignore_whitespace_differences= */ true
  2568. );
  2569. }
  2570. {
  2571. auto tmpls = read_templates("models/templates/Kimi-K2-Thinking.jinja");
  2572. std::vector<std::string> end_tokens{ "<|im_end|>" };
  2573. assert_equals(COMMON_CHAT_FORMAT_KIMI_K2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  2574. assert_equals(COMMON_CHAT_FORMAT_KIMI_K2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  2575. // Test parsing regular content
  2576. assert_msg_equals(message_assist,
  2577. common_chat_parse(
  2578. "Hello, world!\nWhat's up?",
  2579. /* is_partial= */ false,
  2580. {COMMON_CHAT_FORMAT_KIMI_K2}));
  2581. // Test parsing content with thinking
  2582. assert_msg_equals(message_assist_thoughts,
  2583. common_chat_parse(
  2584. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  2585. /* is_partial= */ false,
  2586. {
  2587. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2588. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2589. }));
  2590. // Test parsing tool calls
  2591. assert_msg_equals(message_assist_call,
  2592. common_chat_parse(
  2593. "<|tool_calls_section_begin|><|tool_call_begin|>functions.special_function:0<|tool_call_argument_begin|>{\"arg1\": 1}<|tool_call_end|><|tool_calls_section_end|>",
  2594. /* is_partial= */ false,
  2595. {COMMON_CHAT_FORMAT_KIMI_K2}));
  2596. // Test parsing tool calls with thinking
  2597. assert_msg_equals(message_assist_call_thoughts,
  2598. common_chat_parse(
  2599. "<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|>",
  2600. /* is_partial= */ false,
  2601. {
  2602. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2603. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2604. }));
  2605. // Test tool calls with extra content
  2606. assert_msg_equals(message_assist_call_content,
  2607. common_chat_parse(
  2608. "<|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?",
  2609. /* is_partial= */ false,
  2610. {COMMON_CHAT_FORMAT_KIMI_K2}
  2611. ));
  2612. // Test tool calls with extra content AND thinking
  2613. assert_msg_equals(message_assist_call_thoughts_content,
  2614. common_chat_parse(
  2615. "<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?",
  2616. /* is_partial= */ false,
  2617. {
  2618. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2619. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2620. }));
  2621. // Test streaming
  2622. test_parser_with_streaming(message_assist_call_thoughts_content,
  2623. "<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|>",
  2624. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2625. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2626. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2627. }); });
  2628. test_parser_with_streaming(message_assist_call_thoughts_unparsed,
  2629. "<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|>",
  2630. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2631. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2632. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2633. }); });
  2634. test_parser_with_streaming(message_assist_call_thoughts_content,
  2635. "<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",
  2636. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2637. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2638. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2639. }); });
  2640. test_parser_with_streaming(message_assist_call_withopt,
  2641. "<|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|>",
  2642. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2643. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2644. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE
  2645. }); });
  2646. test_parser_with_streaming(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": \"123456\"}"),
  2647. "<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|>",
  2648. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2649. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2650. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2651. }); });
  2652. test_parser_with_streaming(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": [1, 2, \"345\", 6]}"),
  2653. "<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|>",
  2654. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2655. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2656. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2657. }); });
  2658. 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\"}}"),
  2659. "<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|>",
  2660. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2661. /* .format = */ COMMON_CHAT_FORMAT_KIMI_K2,
  2662. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  2663. }); });
  2664. test_parser_with_streaming(
  2665. simple_assist_msg("", "", "complex_function", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}"),
  2666. "<|tool_calls_section_begin|><|tool_call_begin|>functions.complex_function:0<|tool_call_argument_begin|>"
  2667. "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}"
  2668. "<|tool_call_end|><|tool_calls_section_end|>",
  2669. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_KIMI_K2}); });
  2670. test_parser_with_streaming(
  2671. simple_assist_msg("", "", "web_search", "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}"),
  2672. "<|tool_calls_section_begin|><|tool_call_begin|>functions.web_search:0<|tool_call_argument_begin|>"
  2673. "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}"
  2674. "<|tool_call_end|><|tool_calls_section_end|>",
  2675. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_KIMI_K2}); });
  2676. test_parser_with_streaming(
  2677. 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\"}]}"),
  2678. "<|tool_calls_section_begin|><|tool_call_begin|>functions.read_file:0<|tool_call_argument_begin|>"
  2679. "{\"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\"}]}"
  2680. "<|tool_call_end|><|tool_calls_section_end|>",
  2681. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_KIMI_K2}); });
  2682. test_parser_with_streaming(
  2683. simple_assist_msg(
  2684. "Let me start by examining the relevant files to understand the current implementation.", "",
  2685. "read_file",
  2686. "{\"files\": [{\"path\": \"src/app/Partners.tsx\", \"line_ranges\": [\"1-100\"]}]}"),
  2687. "Let me start by examining the relevant files to understand the current implementation."
  2688. "<|tool_calls_section_begin|><|tool_call_begin|>functions.read_file:0<|tool_call_argument_begin|>"
  2689. "{\"files\":[{\"path\":\"src/app/Partners.tsx\",\"line_ranges\":[\"1-100\"]}]}"
  2690. "<|tool_call_end|><|tool_calls_section_end|>",
  2691. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_KIMI_K2}); });
  2692. auto multi_tool_msg = simple_assist_msg("Let me call multiple tools.", "I'm thinking.");
  2693. multi_tool_msg.tool_calls.push_back({ "read_file", "{\"files\": [{\"path\": \"src/app/Partners.tsx\", \"line_ranges\": [\"1-100\"]}]}", "" });
  2694. multi_tool_msg.tool_calls.push_back({ "web_search", "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}", "" });
  2695. multi_tool_msg.tool_calls.push_back({ "complex_function", "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}", "" });
  2696. multi_tool_msg.tool_calls.push_back({ "emoji_function", "{\"message\":\"Hello! 👋 🌟 🚀 Testing emojis: 😀😃😄😁 and symbols: ∑∏∆∇\"}", "" });
  2697. test_parser_with_streaming(multi_tool_msg,
  2698. "<think>I'm thinking.</think>Let me call multiple tools."
  2699. "<|tool_calls_section_begin|>"
  2700. "<|tool_call_begin|>functions.read_file:0<|tool_call_argument_begin|>"
  2701. "{\"files\":[{\"path\":\"src/app/Partners.tsx\",\"line_ranges\":[\"1-100\"]}]}"
  2702. "<|tool_call_end|>"
  2703. "<|tool_call_begin|>functions.web_search:1<|tool_call_argument_begin|>"
  2704. "{\"query\":\"\\\"From Zero\\\" Linkin Park album tracklist complete songs\",\"limit\":3,\"type\":\"text\"}"
  2705. "<|tool_call_end|>"
  2706. "<|tool_call_begin|>functions.complex_function:2<|tool_call_argument_begin|>"
  2707. "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}"
  2708. "<|tool_call_end|>"
  2709. "<|tool_call_begin|>functions.emoji_function:3<|tool_call_argument_begin|>"
  2710. "{\"message\":\"Hello! 👋 🌟 🚀 Testing emojis: 😀😃😄😁 and symbols: ∑∏∆∇\"}"
  2711. "<|tool_call_end|>"
  2712. "<|tool_calls_section_end|>",
  2713. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2714. COMMON_CHAT_FORMAT_KIMI_K2,
  2715. COMMON_REASONING_FORMAT_DEEPSEEK
  2716. }); });
  2717. test_parser_with_streaming(
  2718. simple_assist_msg("", "I'm thinking", "complex_function_in_think", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}"),
  2719. "<think>I'm thinking<|tool_calls_section_begin|><|tool_call_begin|>functions.complex_function_in_think:0<|tool_call_argument_begin|>"
  2720. "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}"
  2721. "<|tool_call_end|><|tool_calls_section_end|>",
  2722. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2723. COMMON_CHAT_FORMAT_KIMI_K2,
  2724. COMMON_REASONING_FORMAT_DEEPSEEK
  2725. }); });
  2726. test_parser_with_streaming(
  2727. simple_assist_msg("Hello", "I'm thinkingI'm still thinking", "complex_function_in_think", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}"),
  2728. "<think>I'm thinking<|tool_calls_section_begin|><|tool_call_begin|>functions.complex_function_in_think:0<|tool_call_argument_begin|>"
  2729. "{\"name\": \"John Doe\", \"age\": 30, \"active\": true, \"score\": 95.5}"
  2730. "<|tool_call_end|><|tool_calls_section_end|>I'm still thinking</think>Hello",
  2731. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {
  2732. COMMON_CHAT_FORMAT_KIMI_K2,
  2733. COMMON_REASONING_FORMAT_DEEPSEEK
  2734. }); });
  2735. // Test template rendering
  2736. common_chat_templates_inputs conversation_with_tools = inputs_tools;
  2737. 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}"));
  2738. conversation_with_tools.messages.push_back({
  2739. "tool",
  2740. "Tool response 1",
  2741. /* .content_parts = */ {},
  2742. /* .tool_calls = */ {},
  2743. /* .reasoning_content = */ "",
  2744. /* .tool_name = */ "complex_function",
  2745. /* .tool_call_id = */ "",
  2746. });
  2747. 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\"}"));
  2748. conversation_with_tools.messages.push_back({
  2749. "tool",
  2750. "Tool response 2",
  2751. /* .content_parts = */ {},
  2752. /* .tool_calls = */ {},
  2753. /* .reasoning_content = */ "",
  2754. /* .tool_name = */ "web_search",
  2755. /* .tool_call_id = */ "",
  2756. });
  2757. 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\"}]}"));
  2758. conversation_with_tools.messages.push_back({
  2759. "tool",
  2760. "Tool response 3",
  2761. /* .content_parts = */ {},
  2762. /* .tool_calls = */ {},
  2763. /* .reasoning_content = */ "",
  2764. /* .tool_name = */ "read_file",
  2765. /* .tool_call_id = */ "",
  2766. });
  2767. 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|>"));
  2768. // Test template generation for regular content
  2769. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  2770. "<think></think>Hello, world!\nWhat's up?",
  2771. /* expect_grammar_triggered= */ false);
  2772. // Test template generation for tool calls
  2773. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  2774. "<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|>",
  2775. /* expect_grammar_triggered= */ true,
  2776. /* test_grammar_if_triggered= */ true,
  2777. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2778. /* ignore_whitespace_differences= */ true
  2779. );
  2780. // Test template generation for tools with optional parameters
  2781. test_templates(tmpls.get(), end_tokens, message_assist_call_noopt, tools,
  2782. "<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|>",
  2783. /* expect_grammar_triggered= */ true,
  2784. /* test_grammar_if_triggered= */ true,
  2785. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2786. /* ignore_whitespace_differences= */ true
  2787. );
  2788. test_templates(tmpls.get(), end_tokens, message_assist_call_withopt, tools,
  2789. "<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|>",
  2790. /* expect_grammar_triggered= */ true,
  2791. /* test_grammar_if_triggered= */ true,
  2792. /* common_reasoning_format= */ COMMON_REASONING_FORMAT_DEEPSEEK,
  2793. /* ignore_whitespace_differences= */ true
  2794. );
  2795. }
  2796. // Test Qwen3-Coder XML format
  2797. {
  2798. // Basic XML tool call parsing
  2799. assert_msg_equals(
  2800. message_assist_call,
  2801. common_chat_parse(
  2802. "<tool_call>\n"
  2803. " <function=special_function>\n"
  2804. " <parameter=arg1>\n"
  2805. " 1\n"
  2806. " </parameter>\n"
  2807. " </function>\n"
  2808. "</tool_call>",
  2809. /* is_partial= */ false,
  2810. {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}));
  2811. // Multiple parameters with different types
  2812. common_chat_msg expected_multi_param;
  2813. expected_multi_param.role = "assistant";
  2814. expected_multi_param.tool_calls = {
  2815. { "complex_function", "{\"name\":\"John Doe\",\"age\":30,\"active\":true,\"score\":95.5}", "" }
  2816. };
  2817. test_parser_with_streaming(expected_multi_param,
  2818. "<tool_call>\n"
  2819. " <function=complex_function>\n"
  2820. " <parameter=name>\n"
  2821. " John Doe\n"
  2822. " </parameter>\n"
  2823. " <parameter=age>\n"
  2824. " 30\n"
  2825. " </parameter>\n"
  2826. " <parameter=active>\n"
  2827. " true\n"
  2828. " </parameter>\n"
  2829. " <parameter=score>\n"
  2830. " 95.5\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. // Special characters and Unicode
  2836. common_chat_msg expected_special_chars;
  2837. expected_special_chars.role = "assistant";
  2838. expected_special_chars.tool_calls = {
  2839. { "unicode_function", "{\"message\":\"Hello 世界! 🌍 Special chars: @#$%^&*()\"}", "" }
  2840. };
  2841. test_parser_with_streaming(expected_special_chars,
  2842. "<tool_call>\n"
  2843. " <function=unicode_function>\n"
  2844. " <parameter=message>\n"
  2845. " Hello 世界! 🌍 Special chars: @#$%^&*()\n"
  2846. " </parameter>\n"
  2847. " </function>\n"
  2848. "</tool_call>",
  2849. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2850. // Multiline content with newlines and indentation
  2851. common_chat_msg expected_multiline;
  2852. expected_multiline.role = "assistant";
  2853. expected_multiline.tool_calls = {
  2854. { "code_function", "{\"code\":\"def hello():\\n print(\\\"Hello, World!\\\")\\n return True\"}", "" }
  2855. };
  2856. test_parser_with_streaming(expected_multiline,
  2857. "<tool_call>\n"
  2858. " <function=code_function>\n"
  2859. " <parameter=code>\n"
  2860. "def hello():\n"
  2861. " print(\"Hello, World!\")\n"
  2862. " return True\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. // JSON object as parameter value
  2868. common_chat_msg expected_json_param;
  2869. expected_json_param.role = "assistant";
  2870. expected_json_param.tool_calls = {
  2871. { "json_function", "{\"config\":{\"host\":\"localhost\",\"port\":8080,\"ssl\":false}}", "" }
  2872. };
  2873. test_parser_with_streaming(
  2874. expected_json_param,
  2875. "<tool_call>\n"
  2876. " <function=json_function>\n"
  2877. " <parameter=config>\n"
  2878. " {\"host\": \"localhost\", \"port\": 8080, \"ssl\": false}\n"
  2879. " </parameter>\n"
  2880. " </function>\n"
  2881. "</tool_call>",
  2882. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2883. // Array as parameter value
  2884. common_chat_msg expected_array_param;
  2885. expected_array_param.role = "assistant";
  2886. expected_array_param.tool_calls = {
  2887. { "array_function", "{\"items\":[\"apple\",\"banana\",\"cherry\"]}", "" }
  2888. };
  2889. test_parser_with_streaming(
  2890. expected_array_param,
  2891. "<tool_call>\n"
  2892. " <function=array_function>\n"
  2893. " <parameter=items>\n"
  2894. " [\"apple\", \"banana\", \"cherry\"]\n"
  2895. " </parameter>\n"
  2896. " </function>\n"
  2897. "</tool_call>",
  2898. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2899. // Empty parameter
  2900. common_chat_msg expected_empty_param;
  2901. expected_empty_param.role = "assistant";
  2902. expected_empty_param.tool_calls = {
  2903. { "empty_function", "{\"empty_param\":\"\"}", "" }
  2904. };
  2905. test_parser_with_streaming(
  2906. expected_empty_param,
  2907. "<tool_call>\n"
  2908. " <function=empty_function>\n"
  2909. " <parameter=empty_param>\n"
  2910. " </parameter>\n"
  2911. " </function>\n"
  2912. "</tool_call>",
  2913. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2914. // Boolean values (true/false)
  2915. common_chat_msg expected_boolean;
  2916. expected_boolean.role = "assistant";
  2917. expected_boolean.tool_calls = {
  2918. { "boolean_function", "{\"enabled\":true,\"debug\":false}", "" }
  2919. };
  2920. test_parser_with_streaming(
  2921. expected_boolean,
  2922. "<tool_call>\n"
  2923. " <function=boolean_function>\n"
  2924. " <parameter=enabled>\n"
  2925. " true\n"
  2926. " </parameter>\n"
  2927. " <parameter=debug>\n"
  2928. " false\n"
  2929. " </parameter>\n"
  2930. " </function>\n"
  2931. "</tool_call>",
  2932. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2933. // Null value
  2934. common_chat_msg expected_null;
  2935. expected_null.role = "assistant";
  2936. expected_null.tool_calls = {
  2937. { "null_function", "{\"optional_param\":null}", "" }
  2938. };
  2939. test_parser_with_streaming(
  2940. expected_null,
  2941. "<tool_call>\n"
  2942. " <function=null_function>\n"
  2943. " <parameter=optional_param>\n"
  2944. " null\n"
  2945. " </parameter>\n"
  2946. " </function>\n"
  2947. "</tool_call>",
  2948. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2949. // Negative numbers and scientific notation
  2950. common_chat_msg expected_numbers;
  2951. expected_numbers.role = "assistant";
  2952. expected_numbers.tool_calls = {
  2953. { "math_function", "{\"negative\":-42,\"decimal\":-3.14,\"scientific\":1.23e-4}", "" }
  2954. };
  2955. test_parser_with_streaming(
  2956. expected_numbers,
  2957. "<tool_call>\n"
  2958. " <function=math_function>\n"
  2959. " <parameter=negative>\n"
  2960. " -42\n"
  2961. " </parameter>\n"
  2962. " <parameter=decimal>\n"
  2963. " -3.14\n"
  2964. " </parameter>\n"
  2965. " <parameter=scientific>\n"
  2966. " 1.23e-4\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. // XML-like content in parameters (should be escaped)
  2972. common_chat_msg expected_xml_content;
  2973. expected_xml_content.role = "assistant";
  2974. expected_xml_content.tool_calls = {
  2975. { "xml_function", "{\"xml_content\":\"<root><item>value</item></root>\"}", "" }
  2976. };
  2977. test_parser_with_streaming(
  2978. expected_xml_content,
  2979. "<tool_call>\n"
  2980. " <function=xml_function>\n"
  2981. " <parameter=xml_content>\n"
  2982. " <root><item>value</item></root>\n"
  2983. " </parameter>\n"
  2984. " </function>\n"
  2985. "</tool_call>",
  2986. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  2987. // Quotes and escape characters
  2988. common_chat_msg expected_quotes;
  2989. expected_quotes.role = "assistant";
  2990. expected_quotes.tool_calls = {
  2991. { "quote_function", "{\"message\":\"She said \\\"Hello!\\\" and left.\"}", "" }
  2992. };
  2993. test_parser_with_streaming(
  2994. expected_quotes,
  2995. "<tool_call>\n"
  2996. " <function=quote_function>\n"
  2997. " <parameter=message>\n"
  2998. " She said \"Hello!\" and left.\n"
  2999. " </parameter>\n"
  3000. " </function>\n"
  3001. "</tool_call>",
  3002. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3003. // Long parameter value (simplified)
  3004. std::string long_text = "This is a long text parameter that should test the parser's ability to handle larger amounts of text data.";
  3005. common_chat_msg expected_long_text;
  3006. expected_long_text.role = "assistant";
  3007. expected_long_text.tool_calls = {
  3008. { "long_function", "{\"long_text\":\"" + long_text + "\"}", "" }
  3009. };
  3010. test_parser_with_streaming(
  3011. expected_long_text,
  3012. "<tool_call>\n"
  3013. " <function=long_function>\n"
  3014. " <parameter=long_text>\n"
  3015. " " + long_text + "\n"
  3016. " </parameter>\n"
  3017. " </function>\n"
  3018. "</tool_call>",
  3019. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3020. // Mixed content with text before and after tool call
  3021. common_chat_msg expected_mixed_content;
  3022. expected_mixed_content.role = "assistant";
  3023. expected_mixed_content.content = "I'll help you search for products. ";
  3024. expected_mixed_content.tool_calls = {
  3025. { "search_function", "{\"query\":\"laptops\"}", "" }
  3026. };
  3027. test_parser_with_streaming(
  3028. expected_mixed_content,
  3029. "I'll help you search for products. <tool_call>\n"
  3030. " <function=search_function>\n"
  3031. " <parameter=query>\n"
  3032. " laptops\n"
  3033. " </parameter>\n"
  3034. " </function>\n"
  3035. "</tool_call>",
  3036. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3037. // Compact format (no extra whitespace)
  3038. common_chat_msg expected_compact;
  3039. expected_compact.role = "assistant";
  3040. expected_compact.tool_calls = {
  3041. { "compact_function", "{\"param\":\"value\"}", "" }
  3042. };
  3043. test_parser_with_streaming(
  3044. expected_compact,
  3045. "<tool_call><function=compact_function><parameter=param>value</parameter></function></tool_call>",
  3046. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3047. // Function name with underscores and numbers
  3048. common_chat_msg expected_complex_name;
  3049. expected_complex_name.role = "assistant";
  3050. expected_complex_name.tool_calls = {
  3051. { "get_user_data_v2", "{\"user_id\":12345}", "" }
  3052. };
  3053. test_parser_with_streaming(
  3054. expected_complex_name,
  3055. "<tool_call>\n"
  3056. " <function=get_user_data_v2>\n"
  3057. " <parameter=user_id>\n"
  3058. " 12345\n"
  3059. " </parameter>\n"
  3060. " </function>\n"
  3061. "</tool_call>",
  3062. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3063. // Parameter names with underscores and numbers
  3064. common_chat_msg expected_complex_params;
  3065. expected_complex_params.role = "assistant";
  3066. expected_complex_params.tool_calls = {
  3067. { "test_function", "{\"param_1\":\"value1\",\"param_2_name\":\"value2\",\"param3\":123}", "" }
  3068. };
  3069. test_parser_with_streaming(
  3070. expected_complex_params,
  3071. "<tool_call>\n"
  3072. " <function=test_function>\n"
  3073. " <parameter=param_1>\n"
  3074. " value1\n"
  3075. " </parameter>\n"
  3076. " <parameter=param_2_name>\n"
  3077. " value2\n"
  3078. " </parameter>\n"
  3079. " <parameter=param3>\n"
  3080. " 123\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. // Very deeply nested XML content in parameter
  3086. common_chat_msg expected_deep_xml;
  3087. expected_deep_xml.role = "assistant";
  3088. expected_deep_xml.tool_calls = {
  3089. { "xml_parser", "{\"xml\":\"<root><level1><level2><level3>deep content</level3></level2></level1></root>\"}", "" }
  3090. };
  3091. test_parser_with_streaming(
  3092. expected_deep_xml,
  3093. "<tool_call>\n"
  3094. " <function=xml_parser>\n"
  3095. " <parameter=xml>\n"
  3096. " <root><level1><level2><level3>deep content</level3></level2></level1></root>\n"
  3097. " </parameter>\n"
  3098. " </function>\n"
  3099. "</tool_call>",
  3100. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3101. // Parameter with only whitespace
  3102. common_chat_msg expected_whitespace_param;
  3103. expected_whitespace_param.role = "assistant";
  3104. expected_whitespace_param.tool_calls = {
  3105. { "whitespace_function", "{\"spaces\":\"\"}", "" }
  3106. };
  3107. test_parser_with_streaming(
  3108. expected_whitespace_param,
  3109. "<tool_call>\n"
  3110. " <function=whitespace_function>\n"
  3111. " <parameter=spaces>\n"
  3112. " \n"
  3113. " </parameter>\n"
  3114. " </function>\n"
  3115. "</tool_call>",
  3116. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3117. // Parameter with tabs and mixed whitespace
  3118. common_chat_msg expected_mixed_whitespace;
  3119. expected_mixed_whitespace.role = "assistant";
  3120. expected_mixed_whitespace.tool_calls = {
  3121. { "tab_function", "{\"content\":\"line1\\n\\tindented line\\n spaces\"}", "" }
  3122. };
  3123. test_parser_with_streaming(
  3124. expected_mixed_whitespace,
  3125. "<tool_call>\n"
  3126. " <function=tab_function>\n"
  3127. " <parameter=content>\n"
  3128. "line1\n"
  3129. "\tindented line\n"
  3130. " spaces\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. // Control characters and special Unicode
  3136. common_chat_msg expected_control_chars;
  3137. expected_control_chars.role = "assistant";
  3138. expected_control_chars.tool_calls = {
  3139. { "control_function", "{\"text\":\"Line1\\nLine2\\tTabbed\\rCarriage return\"}", "" }
  3140. };
  3141. test_parser_with_streaming(
  3142. expected_control_chars,
  3143. "<tool_call>\n"
  3144. " <function=control_function>\n"
  3145. " <parameter=text>\n"
  3146. "Line1\nLine2\tTabbed\rCarriage return\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. // Emoji and extended Unicode characters
  3152. common_chat_msg expected_emoji;
  3153. expected_emoji.role = "assistant";
  3154. expected_emoji.tool_calls = {
  3155. { "emoji_function", "{\"message\":\"Hello! 👋 🌟 🚀 Testing emojis: 😀😃😄😁 and symbols: ∑∏∆∇\"}", "" }
  3156. };
  3157. test_parser_with_streaming(
  3158. expected_emoji,
  3159. "<tool_call>\n"
  3160. " <function=emoji_function>\n"
  3161. " <parameter=message>\n"
  3162. " Hello! 👋 🌟 🚀 Testing emojis: 😀😃😄😁 and symbols: ∑∏∆∇\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. // Mathematical expressions and formulas
  3168. common_chat_msg expected_math;
  3169. expected_math.role = "assistant";
  3170. expected_math.tool_calls = {
  3171. { "math_function", "{\"formula\":\"E = mc² and ∫f(x)dx = F(x) + C\"}", "" }
  3172. };
  3173. test_parser_with_streaming(
  3174. expected_math,
  3175. "<tool_call>\n"
  3176. " <function=math_function>\n"
  3177. " <parameter=formula>\n"
  3178. " E = mc² and ∫f(x)dx = F(x) + C\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. // SQL injection-like content (should be safely escaped)
  3184. common_chat_msg expected_sql;
  3185. expected_sql.role = "assistant";
  3186. expected_sql.tool_calls = {
  3187. { "sql_function", "{\"query\":\"SELECT * FROM users WHERE id = 1; DROP TABLE users; --\"}", "" }
  3188. };
  3189. test_parser_with_streaming(
  3190. expected_sql,
  3191. "<tool_call>\n"
  3192. " <function=sql_function>\n"
  3193. " <parameter=query>\n"
  3194. " SELECT * FROM users WHERE id = 1; DROP TABLE users; --\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. // HTML/XML injection content
  3200. common_chat_msg expected_html;
  3201. expected_html.role = "assistant";
  3202. expected_html.tool_calls = {
  3203. { "html_function", "{\"content\":\"<script>alert('xss')</script><img src=x onerror=alert(1)>\"}", "" }
  3204. };
  3205. test_parser_with_streaming(
  3206. expected_html,
  3207. "<tool_call>\n"
  3208. " <function=html_function>\n"
  3209. " <parameter=content>\n"
  3210. " <script>alert('xss')</script><img src=x onerror=alert(1)>\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. // Binary-like content (base64)
  3216. common_chat_msg expected_binary;
  3217. expected_binary.role = "assistant";
  3218. expected_binary.tool_calls = {
  3219. { "binary_function", "{\"data\":\"SGVsbG8gV29ybGQhIFRoaXMgaXMgYmFzZTY0IGVuY29kZWQgdGV4dC4=\"}", "" }
  3220. };
  3221. test_parser_with_streaming(
  3222. expected_binary,
  3223. "<tool_call>\n"
  3224. " <function=binary_function>\n"
  3225. " <parameter=data>\n"
  3226. " SGVsbG8gV29ybGQhIFRoaXMgaXMgYmFzZTY0IGVuY29kZWQgdGV4dC4=\n"
  3227. " </parameter>\n"
  3228. " </function>\n"
  3229. "</tool_call>",
  3230. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3231. // Very large numbers (should be parsed as scientific notation)
  3232. common_chat_msg expected_large_numbers;
  3233. expected_large_numbers.role = "assistant";
  3234. expected_large_numbers.tool_calls = {
  3235. { "number_function", "{\"big_int\":1e+60}", "" } // Large number becomes scientific notation
  3236. };
  3237. test_parser_with_streaming(
  3238. expected_large_numbers,
  3239. "<tool_call>\n"
  3240. " <function=number_function>\n"
  3241. " <parameter=big_int>\n"
  3242. " 999999999999999999999999999999999999999999999999999999999999\n"
  3243. " </parameter>\n"
  3244. " </function>\n"
  3245. "</tool_call>",
  3246. [&](const std::string &msg) { return common_chat_parse(msg, /* is_partial= */ true, {COMMON_CHAT_FORMAT_QWEN3_CODER_XML}); });
  3247. }
  3248. {
  3249. // Qwen3-Coder template
  3250. auto tmpls = read_templates("models/templates/Qwen3-Coder.jinja");
  3251. common_chat_templates_inputs inputs;
  3252. inputs.messages = { message_user };
  3253. common_chat_tool qwen_union_tool {
  3254. /* .name = */ "qwen_union",
  3255. /* .description = */ "Test tool for union/anyOf handling",
  3256. /* .parameters = */ R"({
  3257. "type": "object",
  3258. "properties": {
  3259. "priority": { "type": ["number", "null"] },
  3260. "maybe_text": { "anyOf": [ { "type": "string" } ] },
  3261. "config": { "anyOf": [ { "type": "object" }, { "type": "null" } ] }
  3262. },
  3263. "required": []
  3264. })",
  3265. };
  3266. inputs.tools = { qwen_union_tool };
  3267. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  3268. assert_equals(COMMON_CHAT_FORMAT_QWEN3_CODER_XML, params.format);
  3269. assert_equals(false, params.grammar.empty());
  3270. // Grammar should compile successfully
  3271. auto grammar = build_grammar(params.grammar);
  3272. GGML_ASSERT(grammar && "Failed to build Qwen3-Coder grammar with union types");
  3273. }
  3274. }
  3275. static void test_template_output_peg_parsers() {
  3276. printf("[%s]\n", __func__);
  3277. // JSON schemas
  3278. const char * invoice_schema = R"({
  3279. "type": "object",
  3280. "properties": {
  3281. "amount": {"type": "number"},
  3282. "date": {"type": "string"}
  3283. }
  3284. })";
  3285. {
  3286. // Ministral-3-14B-Reasoning-2512
  3287. auto tmpls = read_templates("models/templates/mistralai-Ministral-3-14B-Reasoning-2512.jinja");
  3288. // Test basic message
  3289. test_peg_parser(tmpls.get(), [&](auto & t) {
  3290. t.input = "Hello, world!\nWhat's up?";
  3291. t.expect = message_assist;
  3292. });
  3293. // Test basic message and reasoning with reasoning_format = none
  3294. test_peg_parser(tmpls.get(), [&](auto & t) {
  3295. t.input = "[THINK]I'm\nthinking[/THINK]Hello, world!\nWhat's up?";
  3296. t.expect.content = "[THINK]I'm\nthinking[/THINK]Hello, world!\nWhat's up?";
  3297. });
  3298. // Test basic message and reasoning with reasoning_format = auto
  3299. test_peg_parser(tmpls.get(), [&](auto & t) {
  3300. t.input = "[THINK]I'm\nthinking[/THINK]Hello, world!\nWhat's up?";
  3301. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3302. t.expect = message_assist_thoughts;
  3303. });
  3304. // Test tool call
  3305. test_peg_parser(tmpls.get(), [&](auto & t) {
  3306. t.input = R"([TOOL_CALLS]special_function[ARGS]{"arg1":1})";
  3307. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3308. t.params.tools = {special_function_tool};
  3309. t.expect = message_assist_call;
  3310. });
  3311. // Test tool call with reasoning
  3312. test_peg_parser(tmpls.get(), [&](auto & t) {
  3313. t.input = "[THINK]I'm\nthinking[/THINK]"
  3314. R"([TOOL_CALLS]special_function[ARGS]{"arg1":1})";
  3315. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3316. t.params.tools = {special_function_tool};
  3317. t.expect = message_assist_call_thoughts;
  3318. });
  3319. // Test parallel tool calls
  3320. test_peg_parser(tmpls.get(), [&](auto & t) {
  3321. t.input = R"([TOOL_CALLS]special_function[ARGS]{"arg1": 1})"
  3322. R"([TOOL_CALLS]special_function_with_opt[ARGS]{"arg1": 1, "arg2": 2})";
  3323. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3324. t.params.parallel_tool_calls = true;
  3325. t.params.tools = {special_function_tool, special_function_tool_with_optional_param};
  3326. t.expect.tool_calls = {{
  3327. /* .name = */ "special_function",
  3328. /* .arguments = */ R"({"arg1": 1})",
  3329. /* .id = */ {},
  3330. }, {
  3331. /* .name = */ "special_function_with_opt",
  3332. /* .arguments = */ R"({"arg1": 1, "arg2": 2})",
  3333. /* .id = */ {},
  3334. }};
  3335. });
  3336. // Test response format
  3337. test_peg_parser(tmpls.get(), [&](auto & t) {
  3338. t.input = "[THINK]I need to output the invoice details in JSON[/THINK]"
  3339. "```json\n"
  3340. R"({"amount": 123.45, "date": "2025-12-03"})"
  3341. "\n```";
  3342. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3343. t.params.json_schema = invoice_schema;
  3344. t.expect.reasoning_content = "I need to output the invoice details in JSON";
  3345. t.expect.content =R"({"amount": 123.45, "date": "2025-12-03"})";
  3346. });
  3347. }
  3348. {
  3349. // NVIDIA Nemotron-3 Nano
  3350. auto tmpls = read_templates("models/templates/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16.jinja");
  3351. // Test basic message
  3352. test_peg_parser(tmpls.get(), [&](auto & t) {
  3353. t.input = "Hello, world!\nWhat's up?";
  3354. t.expect = message_assist;
  3355. });
  3356. // Test basic message and reasoning with reasoning_format = none
  3357. test_peg_parser(tmpls.get(), [&](auto & t) {
  3358. t.input = "I'm\nthinking\n</think>\nHello, world!\nWhat's up?";
  3359. t.expect.content = "I'm\nthinking\n</think>\nHello, world!\nWhat's up?";
  3360. });
  3361. // Test basic message and reasoning with reasoning_format = auto
  3362. test_peg_parser(tmpls.get(), [&](auto & t) {
  3363. t.input = "I'm\nthinking\n</think>\nHello, world!\nWhat's up?";
  3364. t.params.enable_thinking = true;
  3365. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3366. t.expect = message_assist_thoughts;
  3367. });
  3368. // Test tool call
  3369. test_peg_parser(tmpls.get(), [&](auto & t) {
  3370. t.input =
  3371. "<tool_call>\n"
  3372. "<function=special_function>\n"
  3373. "<parameter=arg1>\n"
  3374. "1\n"
  3375. "</parameter>\n"
  3376. "</function>\n"
  3377. "</tool_call>";
  3378. t.params.enable_thinking = false;
  3379. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3380. t.params.tools = {special_function_tool};
  3381. t.expect = message_assist_call;
  3382. });
  3383. // Test tool call with reasoning
  3384. test_peg_parser(tmpls.get(), [&](auto & t) {
  3385. t.input =
  3386. "I'm\nthinking\n</think>\n"
  3387. "<tool_call>\n"
  3388. "<function=special_function>\n"
  3389. "<parameter=arg1>\n"
  3390. "1\n"
  3391. "</parameter>\n"
  3392. "</function>\n"
  3393. "</tool_call>";
  3394. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3395. t.params.tools = {special_function_tool};
  3396. t.expect = message_assist_call_thoughts;
  3397. });
  3398. // Test parallel tool calls
  3399. test_peg_parser(tmpls.get(), [&](auto & t) {
  3400. t.input =
  3401. "<tool_call>\n"
  3402. "<function=special_function>\n"
  3403. "<parameter=arg1>\n"
  3404. "1\n"
  3405. "</parameter>\n"
  3406. "</function>\n"
  3407. "</tool_call>\n"
  3408. "<tool_call>\n"
  3409. "<function=special_function_with_opt>\n"
  3410. "<parameter=arg1>\n"
  3411. "1\n"
  3412. "</parameter>\n"
  3413. "<parameter=arg2>\n"
  3414. "2\n"
  3415. "</parameter>\n"
  3416. "</function>\n"
  3417. "</tool_call>";
  3418. t.params.enable_thinking = false;
  3419. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3420. t.params.parallel_tool_calls = true;
  3421. t.params.tools = {special_function_tool, special_function_tool_with_optional_param};
  3422. t.expect.tool_calls = {{
  3423. /* .name = */ "special_function",
  3424. /* .arguments = */ R"({"arg1": 1})",
  3425. /* .id = */ {},
  3426. }, {
  3427. /* .name = */ "special_function_with_opt",
  3428. /* .arguments = */ R"({"arg1": 1, "arg2": 2})",
  3429. /* .id = */ {},
  3430. }};
  3431. });
  3432. // Test tool call with string parameter
  3433. test_peg_parser(tmpls.get(), [&](auto & t) {
  3434. t.input =
  3435. "<tool_call>\n"
  3436. "<function=python>\n"
  3437. "<parameter=code>\n"
  3438. "def hello():\n"
  3439. " print(\"Hello, world!\")\n"
  3440. "\n"
  3441. "hello()\n"
  3442. "</parameter>\n"
  3443. "</function>\n"
  3444. "</tool_call>";
  3445. t.params.enable_thinking = false;
  3446. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3447. t.params.tools = {python_tool};
  3448. t.expect.tool_calls = {{
  3449. /* .name = */ "python",
  3450. /* .arguments = */ "{\"code\": \"def hello():\\n print(\\\"Hello, world!\\\")\\n\\nhello()\"}",
  3451. /* .id = */ {},
  3452. }};
  3453. });
  3454. // Test tool call with string parameter and no closing </parameter> tag
  3455. test_peg_parser(tmpls.get(), [&](auto & t) {
  3456. t.input =
  3457. "<tool_call>\n"
  3458. "<function=python>\n"
  3459. "<parameter=code>\n"
  3460. "def hello():\n"
  3461. " print(\"Hello, world!\")\n"
  3462. "\n"
  3463. "hello()\n"
  3464. "</function>\n"
  3465. "</tool_call>";
  3466. t.params.enable_thinking = false;
  3467. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3468. t.params.tools = {python_tool};
  3469. t.expect.tool_calls = {{
  3470. /* .name = */ "python",
  3471. /* .arguments = */ "{\"code\": \"def hello():\\n print(\\\"Hello, world!\\\")\\n\\nhello()\"}",
  3472. /* .id = */ {},
  3473. }};
  3474. });
  3475. // Test response format
  3476. test_peg_parser(tmpls.get(), [&](auto & t) {
  3477. t.input =
  3478. "I need to output the invoice details in JSON\n"
  3479. "</think>\n"
  3480. R"({"amount": 123.45, "date": "2025-12-03"})";
  3481. t.params.reasoning_format = COMMON_REASONING_FORMAT_AUTO;
  3482. t.params.json_schema = invoice_schema;
  3483. t.expect.reasoning_content = "I need to output the invoice details in JSON";
  3484. t.expect.content = R"({"amount": 123.45, "date": "2025-12-03"})";
  3485. });
  3486. }
  3487. }
  3488. static void test_msg_diffs_compute() {
  3489. printf("[%s]\n", __func__);
  3490. {
  3491. common_chat_msg msg1;
  3492. common_chat_msg msg2;
  3493. msg2.content = "Hello, world!";
  3494. common_chat_msg_diff diff;
  3495. diff.content_delta = "Hello, world!";
  3496. assert_equals(
  3497. {diff},
  3498. common_chat_msg_diff::compute_diffs(msg1, msg2));
  3499. }
  3500. {
  3501. common_chat_msg msg1;
  3502. msg1.content = "Hello,";
  3503. common_chat_msg msg2;
  3504. msg2.content = "Hello, world!";
  3505. common_chat_msg_diff diff;
  3506. diff.content_delta = " world!";
  3507. assert_equals(
  3508. {diff},
  3509. common_chat_msg_diff::compute_diffs(msg1, msg2));
  3510. }
  3511. {
  3512. common_chat_msg msg0;
  3513. common_chat_msg msg1;
  3514. msg1.tool_calls = { { "special_function", "{\"ar", /* .id = */ "123" } };
  3515. common_chat_msg msg2;
  3516. msg2.tool_calls = { { "special_function", "{\"arg1\": 1}", /* .id = */ "123" } };
  3517. common_chat_msg_diff diff01;
  3518. diff01.tool_call_index = 0;
  3519. diff01.tool_call_delta.name = "special_function";
  3520. diff01.tool_call_delta.id = "123";
  3521. diff01.tool_call_delta.arguments = "{\"ar";
  3522. assert_equals(
  3523. {diff01},
  3524. common_chat_msg_diff::compute_diffs(msg0, msg1));
  3525. common_chat_msg_diff diff12;
  3526. diff12.tool_call_index = 0;
  3527. // Note: neither id nor name change here.
  3528. diff12.tool_call_delta.arguments = "g1\": 1}";
  3529. assert_equals(
  3530. {diff12},
  3531. common_chat_msg_diff::compute_diffs(msg1, msg2));
  3532. }
  3533. {
  3534. common_chat_msg msg0;
  3535. common_chat_msg msg2;
  3536. msg2.tool_calls = {
  3537. { "f1", "{\"arg1\": 1}", /* .id = */ "123" },
  3538. { "f2", "{\"arg2\": 2}", /* .id = */ "222" },
  3539. };
  3540. common_chat_msg_diff diff1;
  3541. diff1.tool_call_index = 0;
  3542. diff1.tool_call_delta.name = "f1";
  3543. diff1.tool_call_delta.id = "123";
  3544. diff1.tool_call_delta.arguments = "{\"arg1\": 1}";
  3545. common_chat_msg_diff diff2;
  3546. diff2.tool_call_index = 1;
  3547. diff2.tool_call_delta.name = "f2";
  3548. diff2.tool_call_delta.id = "222";
  3549. diff2.tool_call_delta.arguments = "{\"arg2\": 2}";
  3550. assert_equals(
  3551. {diff1, diff2},
  3552. common_chat_msg_diff::compute_diffs(msg0, msg2));
  3553. }
  3554. }
  3555. int main(int argc, char ** argv) {
  3556. common_log_set_verbosity_thold(999);
  3557. // try {
  3558. #ifndef _WIN32
  3559. if (argc > 1) {
  3560. common_chat_templates_inputs inputs;
  3561. common_chat_msg msg;
  3562. msg.role = "user";
  3563. msg.content = "Hey";
  3564. inputs.messages = {msg};
  3565. inputs.tools = { special_function_tool };
  3566. std::cout << "| Template | Format |\n";
  3567. std::cout << "|----------|--------|\n";
  3568. for (int i = 1; i < argc; i++) {
  3569. try {
  3570. std::string path = argv[i];
  3571. if (path.rfind(".jinja") != path.size() - 6) {
  3572. std::cerr << "Skipping non-jinja file: " << path << '\n';
  3573. continue;
  3574. }
  3575. auto tmpls = read_templates(path);
  3576. auto parts = string_split(path, "/");
  3577. auto name = parts[parts.size() - 1];
  3578. auto format = common_chat_format_name(common_chat_templates_apply(tmpls.get(), inputs).format);
  3579. std::cout << "| " << name << " | " << format << " |\n";
  3580. } catch (const std::exception & e) {
  3581. std::cerr << "Failed to process " << argv[i] << ": " << e.what() << '\n';
  3582. }
  3583. }
  3584. } else
  3585. #endif
  3586. {
  3587. test_msg_diffs_compute();
  3588. test_msgs_oaicompat_json_conversion();
  3589. test_tools_oaicompat_json_conversion();
  3590. test_template_output_parsers();
  3591. test_template_output_peg_parsers();
  3592. std::cout << "\n[chat] All tests passed!" << '\n';
  3593. }
  3594. return 0;
  3595. // } catch (const std::exception & e) {
  3596. // std::cerr << "Error: " << e.what() << '\n';
  3597. // return 1;
  3598. // }
  3599. }