test-chat.cpp 186 KB

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