test-chat.cpp 187 KB

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