1
0

test-chat.cpp 163 KB

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