test-chat.cpp 188 KB

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