test-chat.cpp 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423
  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) {
  133. assert_equals(expected.role, actual.role);
  134. assert_equals(expected.content, actual.content);
  135. assert_equals(expected.content_parts.size(), actual.content_parts.size());
  136. for (size_t i = 0; i < expected.content_parts.size(); i++) {
  137. const auto & expected_part = expected.content_parts[i];
  138. const auto & actual_part = actual.content_parts[i];
  139. assert_equals(expected_part.type, actual_part.type);
  140. assert_equals(expected_part.text, actual_part.text);
  141. }
  142. assert_equals(expected.reasoning_content, actual.reasoning_content);
  143. assert_equals(expected.tool_calls.size(), actual.tool_calls.size());
  144. for (size_t i = 0; i < expected.tool_calls.size(); i++) {
  145. const auto & expected_tool_call = expected.tool_calls[i];
  146. const auto & actual_tool_call = actual.tool_calls[i];
  147. assert_equals(expected_tool_call.name, actual_tool_call.name);
  148. assert_equals(renormalize_json(expected_tool_call.arguments), renormalize_json(actual_tool_call.arguments));
  149. assert_equals(expected_tool_call.id, actual_tool_call.id);
  150. }
  151. }
  152. common_chat_tool special_function_tool {
  153. /* .name = */ "special_function",
  154. /* .description = */ "I'm special",
  155. /* .parameters = */ R"({
  156. "type": "object",
  157. "properties": {
  158. "arg1": {
  159. "type": "integer",
  160. "description": "The arg."
  161. }
  162. },
  163. "required": ["arg1"]
  164. })",
  165. };
  166. common_chat_tool python_tool {
  167. /* .name = */ "python",
  168. /* .description = */ "an ipython interpreter",
  169. /* .parameters = */ R"({
  170. "type": "object",
  171. "properties": {
  172. "code": {
  173. "type": "string",
  174. "description": "Python code to execute."
  175. }
  176. },
  177. "required": ["code"]
  178. })",
  179. };
  180. common_chat_tool code_interpreter_tool {
  181. /* .name = */ "code_interpreter",
  182. /* .description = */ "an ipython interpreter",
  183. /* .parameters = */ R"({
  184. "type": "object",
  185. "properties": {
  186. "code": {
  187. "type": "string",
  188. "description": "Python code to execute."
  189. }
  190. },
  191. "required": ["code"]
  192. })",
  193. };
  194. std::vector<common_chat_tool> tools { special_function_tool, python_tool };
  195. std::vector<common_chat_tool> llama_3_1_tools { special_function_tool, code_interpreter_tool };
  196. struct delta_data {
  197. std::string delta;
  198. common_chat_params params;
  199. };
  200. static delta_data init_delta(const struct common_chat_templates * tmpls, const std::vector<std::string> & end_tokens,
  201. const common_chat_msg & user_message,
  202. const common_chat_msg & delta_message,
  203. const std::vector<common_chat_tool> & tools,
  204. const common_chat_tool_choice & tool_choice) {
  205. common_chat_templates_inputs inputs;
  206. inputs.parallel_tool_calls = true;
  207. inputs.messages.push_back(user_message);
  208. inputs.tools = tools;
  209. inputs.tool_choice = tool_choice;
  210. auto params_prefix = common_chat_templates_apply(tmpls, inputs);
  211. inputs.messages.push_back(delta_message);
  212. inputs.add_generation_prompt = false;
  213. auto params_full = common_chat_templates_apply(tmpls, inputs);
  214. std::string prefix = params_prefix.prompt;
  215. std::string full = params_full.prompt;
  216. if (full == prefix) {
  217. throw std::runtime_error("Full message is the same as the prefix");
  218. }
  219. size_t common_prefix_length = 0;
  220. for (size_t i = 0; i < prefix.size() && i < full.size(); ++i) {
  221. if (prefix[i] != full[i]) {
  222. break;
  223. }
  224. if (prefix[i] == '<') {
  225. // DeepSeek R1's template (as of 20250209) adds a trailing <think> if add_generation_prompt,
  226. // but it removes thinking tags for past messages.
  227. // The prefix and full strings diverge at <think> vs. <|tool▁calls▁begin|>, we avoid consuming the leading <.
  228. continue;
  229. }
  230. common_prefix_length = i + 1;
  231. }
  232. auto delta = full.substr(common_prefix_length);
  233. // Strip end tokens
  234. for (const auto & end_token : end_tokens) {
  235. // rfind to find the last occurrence
  236. auto pos = delta.rfind(end_token);
  237. if (pos != std::string::npos) {
  238. delta = delta.substr(0, pos);
  239. break;
  240. }
  241. }
  242. return { delta, params_full };
  243. }
  244. /*
  245. Applies the template to 1 user message w/ add_generation_prompt=true, then w/ the test message w/ add_generation_prompt=false,
  246. gets the diff, removes any end tokens and parses the result w/ the grammar, checking that
  247. the parsed message is the same as the test_message
  248. */
  249. static void test_templates(const struct common_chat_templates * tmpls, const std::vector<std::string> & end_tokens,
  250. const common_chat_msg & test_message,
  251. const std::vector<common_chat_tool> & tools = {},
  252. const std::string & expected_delta = "",
  253. bool expect_grammar_triggered = true,
  254. bool test_grammar_if_triggered = true,
  255. common_reasoning_format reasoning_format = COMMON_REASONING_FORMAT_NONE) {
  256. common_chat_msg user_message;
  257. user_message.role = "user";
  258. user_message.content = "Hello, world!";
  259. for (const auto & tool_choice : std::vector<common_chat_tool_choice> {COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED}) {
  260. auto data = init_delta(tmpls, end_tokens, user_message, test_message, tools, tool_choice);
  261. if (!expected_delta.empty()) {
  262. assert_equals(expected_delta, data.delta);
  263. }
  264. if (expect_grammar_triggered) {
  265. common_chat_syntax syntax;
  266. syntax.format = data.params.format;
  267. syntax.reasoning_format = reasoning_format;
  268. const auto msg = common_chat_parse(data.delta, /* is_partial= */ false, syntax);
  269. assert_msg_equals(test_message, msg);
  270. }
  271. if (!test_message.tool_calls.empty()) {
  272. GGML_ASSERT(!data.params.grammar.empty());
  273. }
  274. if (!data.params.grammar.empty()) {
  275. auto grammar = build_grammar(data.params.grammar);
  276. if (!grammar) {
  277. throw std::runtime_error("Failed to build grammar");
  278. }
  279. auto earliest_trigger_pos = std::string::npos;
  280. auto constrained = data.delta;
  281. for (const auto & trigger : data.params.grammar_triggers) {
  282. size_t pos = std::string::npos;
  283. std::smatch match;
  284. switch (trigger.type) {
  285. case COMMON_GRAMMAR_TRIGGER_TYPE_WORD:
  286. {
  287. const auto & word = trigger.value;
  288. pos = constrained.find(word);
  289. break;
  290. }
  291. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN:
  292. {
  293. const auto & pattern = trigger.value;
  294. if (std::regex_search(constrained, match, std::regex(pattern))) {
  295. pos = match.position(1);
  296. }
  297. break;
  298. }
  299. case COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL:
  300. {
  301. const auto & pattern = trigger.value;
  302. if (std::regex_match(constrained, match, std::regex(pattern))) {
  303. auto mpos = std::string::npos;
  304. for (size_t i = 1; i < match.size(); ++i) {
  305. if (match[i].length() > 0) {
  306. mpos = match.position(i);
  307. break;
  308. }
  309. }
  310. if (mpos == std::string::npos) {
  311. mpos = match.position(0);
  312. }
  313. pos = mpos;
  314. }
  315. break;
  316. }
  317. default:
  318. throw std::runtime_error("Unknown trigger type");
  319. }
  320. if (pos == std::string::npos) {
  321. continue;
  322. }
  323. if (earliest_trigger_pos == std::string::npos || pos < earliest_trigger_pos) {
  324. earliest_trigger_pos = pos;
  325. }
  326. }
  327. auto grammar_triggered = false;
  328. if (earliest_trigger_pos != std::string::npos) {
  329. constrained = constrained.substr(earliest_trigger_pos);
  330. grammar_triggered = true;
  331. }
  332. if (data.params.grammar_lazy) {
  333. assert_equals(expect_grammar_triggered, grammar_triggered);
  334. }
  335. if (grammar_triggered && test_grammar_if_triggered && !match_string(constrained, grammar.get())) {
  336. throw std::runtime_error("Failed to match delta against grammar:\n\n" + data.delta +
  337. "\n\nConstrained: " + constrained +
  338. "\n\nGrammar: " + data.params.grammar);
  339. }
  340. }
  341. }
  342. }
  343. const common_chat_msg message_user {
  344. "user",
  345. "Hey there!",
  346. /* .content_parts = */ {},
  347. /* .tool_calls = */ {},
  348. /* .reasoning_content = */ "",
  349. /* .tool_name = */ "",
  350. /* .tool_call_id = */ "",
  351. };
  352. const common_chat_msg message_user_parts {
  353. "user",
  354. /* .content = */ "",
  355. /* .content_parts = */ {
  356. { "text", "Hey" },
  357. { "text", "there" },
  358. },
  359. /* .tool_calls = */ {},
  360. /* .reasoning_content = */ "",
  361. /* .tool_name = */ "",
  362. /* .tool_call_id = */ "",
  363. };
  364. 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 = "") {
  365. common_chat_msg msg;
  366. msg.role = "assistant";
  367. msg.content = content;
  368. msg.reasoning_content = reasoning_content;
  369. if (!tool_name.empty()) {
  370. msg.tool_calls.push_back({ tool_name, arguments, id });
  371. }
  372. return msg;
  373. }
  374. const common_chat_msg message_assist = simple_assist_msg("Hello, world!\nWhat's up?");
  375. const common_chat_msg message_assist_empty = simple_assist_msg("");
  376. const common_chat_msg message_assist_thoughts_unparsed_deepseek = simple_assist_msg("<think>I'm\nthinking</think>Hello, world!\nWhat's up?");
  377. 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{}```");
  378. 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{}");
  379. const common_chat_msg message_assist_thoughts_unparsed_r7b = simple_assist_msg("<|START_THINKING|>I'm\nthinking<|END_THINKING|>Hello, world!\nWhat's up?");
  380. const common_chat_msg message_assist_thoughts_unparsed_magistral = simple_assist_msg("[THINK]raisonnement[/THINK]Réponse");
  381. const common_chat_msg message_assist_thoughts = simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking");
  382. const common_chat_msg message_assist_thoughts_unopened_unparsed = simple_assist_msg("I'm\nthinking</think>Hello, world!\nWhat's up?");
  383. const common_chat_msg message_assist_thoughts_no_content = simple_assist_msg("", "I'm\nthinking");
  384. const common_chat_msg message_assist_call = simple_assist_msg("", "", "special_function", "{\"arg1\": 1}");
  385. const common_chat_msg message_assist_call_content = simple_assist_msg("Hello, world!\nWhat's up?", "", "special_function", "{\"arg1\":1}");
  386. const common_chat_msg message_assist_call_empty_args = simple_assist_msg("", "", "special_function");
  387. const common_chat_msg message_assist_call_cutoff_args = simple_assist_msg("", "", "special_function", "{\"arg");
  388. const common_chat_msg message_assist_call_thoughts = simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\":1}");
  389. const common_chat_msg message_assist_call_thoughts_unparsed = simple_assist_msg("<think>I'm\nthinking</think>\n\n", "", "special_function", "{\"arg1\": 1}");
  390. const common_chat_msg message_assist_call_thoughts_content = simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": 1}");
  391. const common_chat_msg message_assist_call_id = simple_assist_msg("", "", "special_function", "{\"arg1\":1}", /* .id = */ "123456789");
  392. const common_chat_msg message_assist_call_idx = simple_assist_msg("", "", "special_function", "{\"arg1\":1}", /* .id = */ "0");
  393. const common_chat_msg message_assist_thoughts_call_idx = simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}", /* id = */ "0");
  394. const common_chat_msg message_assist_call_python = simple_assist_msg("", "", "python", "{\"code\":\"print('hey')\"}");
  395. const common_chat_msg message_assist_call_python_lines = simple_assist_msg("", "", "python", "{\"code\":\"# This is a program:\\nprint('hey')\"}");
  396. const common_chat_msg message_assist_call_python_lines_unclosed = simple_assist_msg("", "", "python", "{\"code\":\"# This is a program:\\nprint('hey')");
  397. const common_chat_msg message_assist_call_code_interpreter = simple_assist_msg("", "", "code_interpreter", "{\"code\":\"print('hey')\"}");
  398. static void test_msgs_oaicompat_json_conversion() {
  399. printf("[%s]\n", __func__);
  400. std::vector<common_chat_msg> msgs{
  401. message_user,
  402. message_user_parts,
  403. message_assist_call,
  404. message_assist_call_thoughts,
  405. message_assist_call_thoughts_unparsed,
  406. message_assist_call_thoughts_content,
  407. message_assist_call_id,
  408. message_assist_call_idx,
  409. message_assist_call_python,
  410. message_assist_call_code_interpreter,
  411. };
  412. for (const auto & msg : msgs) {
  413. auto oai_json = common_chat_msgs_to_json_oaicompat<json>({msg});
  414. auto msgs2 = common_chat_msgs_parse_oaicompat(oai_json);
  415. assert_equals((size_t) 1, msgs2.size());
  416. auto msg2 = msgs2[0];
  417. assert_msg_equals(msg, msg2);
  418. }
  419. assert_equals(
  420. std::string(
  421. "[\n"
  422. " {\n"
  423. " \"role\": \"user\",\n"
  424. " \"content\": [\n"
  425. " {\n"
  426. " \"type\": \"text\",\n"
  427. " \"text\": \"Hey\"\n"
  428. " },\n"
  429. " {\n"
  430. " \"type\": \"text\",\n"
  431. " \"text\": \"there\"\n"
  432. " }\n"
  433. " ]\n"
  434. " }\n"
  435. "]"
  436. ),
  437. common_chat_msgs_to_json_oaicompat<json>({message_user_parts}).dump(2));
  438. assert_equals(
  439. std::string(
  440. "[\n"
  441. " {\n"
  442. " \"role\": \"assistant\",\n"
  443. " \"content\": null,\n"
  444. " \"tool_calls\": [\n"
  445. " {\n"
  446. " \"type\": \"function\",\n"
  447. " \"function\": {\n"
  448. " \"name\": \"python\",\n"
  449. " \"arguments\": \"{\\\"code\\\":\\\"print('hey')\\\"}\"\n"
  450. " }\n"
  451. " }\n"
  452. " ]\n"
  453. " }\n"
  454. "]"
  455. ),
  456. common_chat_msgs_to_json_oaicompat<json>({message_assist_call_python}).dump(2));
  457. auto res = common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\", \"tool_calls\": []}]"));
  458. assert_equals<size_t>(1, res.size());
  459. assert_equals<std::string>(res[0].role, "assistant");
  460. assert_equals(true, res[0].content.empty());
  461. assert_equals(true, res[0].tool_calls.empty());
  462. try {
  463. common_chat_msgs_parse_oaicompat(json::parse("[{\"role\": \"assistant\"}]"));
  464. throw std::runtime_error("Expected exception");
  465. } catch (const std::exception & e) {
  466. if (std::string(e.what()).find("'content'") == std::string::npos) {
  467. throw std::runtime_error("Expected exception about missing 'content'");
  468. }
  469. }
  470. }
  471. static void test_tools_oaicompat_json_conversion() {
  472. printf("[%s]\n", __func__);
  473. std::vector<common_chat_tool> tools{
  474. special_function_tool,
  475. python_tool,
  476. code_interpreter_tool,
  477. };
  478. for (const auto & tool : tools) {
  479. auto oai_json = common_chat_tools_to_json_oaicompat<json>({tool});
  480. auto tools2 = common_chat_tools_parse_oaicompat(oai_json);
  481. assert_equals((size_t) 1, tools2.size());
  482. auto tool2 = tools2[0];
  483. assert_equals(tool.name, tool2.name);
  484. assert_equals(tool.description, tool2.description);
  485. assert_equals(json::parse(tool.parameters).dump(2), json::parse(tool2.parameters).dump(2));
  486. }
  487. assert_equals(
  488. std::string(
  489. "[\n"
  490. " {\n"
  491. " \"type\": \"function\",\n"
  492. " \"function\": {\n"
  493. " \"name\": \"special_function\",\n"
  494. " \"description\": \"I'm special\",\n"
  495. " \"parameters\": {\n"
  496. " \"type\": \"object\",\n"
  497. " \"properties\": {\n"
  498. " \"arg1\": {\n"
  499. " \"type\": \"integer\",\n"
  500. " \"description\": \"The arg.\"\n"
  501. " }\n"
  502. " },\n"
  503. " \"required\": [\n"
  504. " \"arg1\"\n"
  505. " ]\n"
  506. " }\n"
  507. " }\n"
  508. " }\n"
  509. "]"
  510. ),
  511. common_chat_tools_to_json_oaicompat<json>({special_function_tool}).dump(2));
  512. }
  513. static void test_template_output_parsers() {
  514. printf("[%s]\n", __func__);
  515. common_chat_templates_inputs inputs_no_tools;
  516. inputs_no_tools.messages = {message_user};
  517. common_chat_templates_inputs inputs_tools;
  518. inputs_tools.messages = {message_user};
  519. inputs_tools.tools = {special_function_tool};
  520. common_chat_templates_inputs inputs_tools_builtin;
  521. inputs_tools_builtin.messages = {message_user};
  522. inputs_tools_builtin.tools = {python_tool};
  523. {
  524. // Not supported yet
  525. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r-plus-tool_use.jinja");
  526. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  527. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  528. }
  529. {
  530. auto tmpls = read_templates("models/templates/CohereForAI-c4ai-command-r7b-12-2024-tool_use.jinja");
  531. std::vector<std::string> end_tokens{ "<|END_OF_TURN_TOKEN|>" };
  532. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  533. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  534. assert_equals(COMMON_CHAT_FORMAT_COMMAND_R7B, params.format);
  535. assert_equals(false, params.thinking_forced_open);
  536. }
  537. assert_msg_equals(message_assist,
  538. common_chat_parse(
  539. "Hello, world!\nWhat's up?",
  540. /* is_partial= */ false,
  541. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  542. assert_msg_equals(message_assist,
  543. common_chat_parse(
  544. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  545. /* is_partial= */ false,
  546. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  547. assert_msg_equals(message_assist_thoughts,
  548. common_chat_parse(
  549. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  550. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  551. /* is_partial= */ false,
  552. {
  553. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  554. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  555. }));
  556. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  557. common_chat_parse(
  558. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  559. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  560. /* is_partial= */ false,
  561. {
  562. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  563. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  564. /* .reasoning_in_content = */ true,
  565. /* .thinking_forced_open = */ false,
  566. }));
  567. assert_msg_equals(message_assist_thoughts_unparsed_r7b,
  568. common_chat_parse(
  569. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  570. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  571. /* is_partial= */ false,
  572. {COMMON_CHAT_FORMAT_COMMAND_R7B}));
  573. assert_msg_equals(message_assist_thoughts,
  574. common_chat_parse(
  575. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  576. "<|START_RESPONSE|>Hello, world!\nWhat's up?<|END_RESPONSE|>",
  577. /* is_partial= */ false,
  578. {
  579. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  580. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  581. }));
  582. assert_msg_equals(message_assist_thoughts_call_idx,
  583. common_chat_parse(
  584. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  585. "<|START_ACTION|>[\n"
  586. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  587. "]<|END_ACTION|>",
  588. /* is_partial= */ false,
  589. {
  590. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  591. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  592. }));
  593. assert_msg_equals(message_assist_thoughts_no_content,
  594. common_chat_parse(
  595. "<|START_THINKING|>I'm\nthinking<|END_THINKING|>"
  596. "<|START_ACTION|>[\n"
  597. " {\"tool_call_id\": \"0\", \"tool_name\": \"special",
  598. /* is_partial= */ true,
  599. {
  600. /* .format = */ COMMON_CHAT_FORMAT_COMMAND_R7B,
  601. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  602. }));
  603. test_templates(tmpls.get(), end_tokens, message_assist_call_idx, tools,
  604. "<|START_THINKING|><|END_THINKING|>"
  605. "<|START_ACTION|>[\n"
  606. " {\"tool_call_id\": \"0\", \"tool_name\": \"special_function\", \"parameters\": {\"arg1\": 1}}\n"
  607. "]<|END_ACTION|>",
  608. /* expect_grammar_triggered= */ true,
  609. /* test_grammar_if_triggered= */ true,
  610. COMMON_REASONING_FORMAT_DEEPSEEK);
  611. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  612. "<|START_RESPONSE|>Hello, world!\n"
  613. "What's up?<|END_RESPONSE|>",
  614. /* expect_grammar_triggered= */ false);
  615. }
  616. {
  617. auto tmpls = read_templates("models/templates/google-gemma-2-2b-it.jinja");
  618. std::vector<std::string> end_tokens{ "<end_of_turn>" };
  619. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  620. assert_equals(COMMON_CHAT_FORMAT_GENERIC, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  621. assert_equals(COMMON_CHAT_FORMAT_GENERIC,
  622. common_chat_templates_apply(
  623. read_templates("models/templates/microsoft-Phi-3.5-mini-instruct.jinja").get(),
  624. inputs_tools)
  625. .format);
  626. // Generic tool calls doesn't generate / parse content-only messages symmetrically.
  627. assert_equals(
  628. simple_assist_msg("{ \"tool_call\" : { \"name\" : \"t"),
  629. common_chat_parse(
  630. "{ \"tool_call\" : { \"name\" : \"t",
  631. /* is_partial= */ true,
  632. {
  633. /* .format = */ COMMON_CHAT_FORMAT_GENERIC,
  634. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  635. /* .reasoning_in_content = */ false,
  636. /* .thinking_forced_open = */ true,
  637. /* .parse_tool_calls = */ false,
  638. }));
  639. assert_equals(
  640. message_assist_empty,
  641. common_chat_parse(
  642. "{ \"tool_call\" : { \"name\" : \"t",
  643. /* is_partial= */ true,
  644. {COMMON_CHAT_FORMAT_GENERIC}));
  645. assert_equals(
  646. simple_assist_msg("", "", "puppeteer_screenshot", "{\"name\":\"servethehome_homepage\","),
  647. common_chat_parse(
  648. R"({"tool_call": {"name": "puppeteer_screenshot", "arguments": {"name": "servethehome_homepage",)",
  649. /* is_partial= */ true,
  650. {COMMON_CHAT_FORMAT_GENERIC}));
  651. assert_equals(
  652. message_assist_call_empty_args,
  653. common_chat_parse(
  654. "{ \"tool_call\" : { \"name\" : \"special_function\"",
  655. /* is_partial= */ true,
  656. {COMMON_CHAT_FORMAT_GENERIC}));
  657. assert_equals(
  658. message_assist_call_cutoff_args,
  659. common_chat_parse(
  660. "{ \"tool_call\" : { \"name\" : \"special_function\", \"arguments\" : { \"arg",
  661. /* is_partial= */ true,
  662. {COMMON_CHAT_FORMAT_GENERIC}));
  663. assert_msg_equals(message_assist,
  664. common_chat_parse(
  665. "{\n"
  666. " \"response\": \"Hello, world!\\nWhat's up?\"\n"
  667. "}",
  668. /* is_partial= */ false,
  669. {COMMON_CHAT_FORMAT_GENERIC}));
  670. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  671. "{\n"
  672. " \"tool_calls\": [\n"
  673. " {\n"
  674. " \"name\": \"special_function\",\n"
  675. " \"arguments\": {\n"
  676. " \"arg1\": 1\n"
  677. " },\n"
  678. " \"id\": \"123456789\"\n"
  679. " }\n"
  680. " ]\n"
  681. "}");
  682. }
  683. {
  684. auto tmpls = read_templates("models/templates/mistralai-Mistral-Nemo-Instruct-2407.jinja");
  685. std::vector<std::string> end_tokens{ "</s>" };
  686. assert_equals(COMMON_CHAT_FORMAT_MISTRAL_NEMO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  687. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  688. test_templates(
  689. tmpls.get(), end_tokens, message_assist_call_id, tools,
  690. "[TOOL_CALLS][{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, \"id\": \"123456789\"}]");
  691. }
  692. {
  693. assert_msg_equals(
  694. simple_assist_msg("Réponse", "raisonnement"),
  695. common_chat_parse(
  696. message_assist_thoughts_unparsed_magistral.content,
  697. /* is_partial= */ false,
  698. {
  699. /* .format = */ COMMON_CHAT_FORMAT_MAGISTRAL,
  700. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  701. }));
  702. }
  703. {
  704. auto tmpls = read_templates("models/templates/Qwen-QwQ-32B.jinja");
  705. std::vector<std::string> end_tokens{ "<|im_end|>" };
  706. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  707. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  708. }
  709. {
  710. auto tmpls = read_templates("models/templates/NousResearch-Hermes-2-Pro-Llama-3-8B-tool_use.jinja");
  711. std::vector<std::string> end_tokens{ "<|im_end|>" };
  712. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  713. assert_equals(COMMON_CHAT_FORMAT_HERMES_2_PRO, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  714. assert_equals(
  715. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  716. common_chat_templates_apply(
  717. read_templates("models/templates/NousResearch-Hermes-3-Llama-3.1-8B-tool_use.jinja").get(),
  718. inputs_tools)
  719. .format);
  720. assert_equals(
  721. COMMON_CHAT_FORMAT_HERMES_2_PRO,
  722. common_chat_templates_apply(
  723. read_templates("models/templates/Qwen-Qwen2.5-7B-Instruct.jinja").get(),
  724. inputs_tools)
  725. .format);
  726. // Test parsing
  727. assert_msg_equals(
  728. simple_assist_msg("", "", "python", ""),
  729. common_chat_parse(
  730. "```json\n"
  731. "<function_call> { \"name\" : \"python\"",
  732. /* is_partial= */ true,
  733. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  734. assert_msg_equals(
  735. simple_assist_msg("Let's call something\n"),
  736. common_chat_parse(
  737. "Let's call something\n"
  738. "<tool_call>{\"name\"",
  739. /* is_partial= */ true,
  740. {
  741. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  742. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  743. }));
  744. assert_msg_equals(
  745. simple_assist_msg("Let's call something\n"),
  746. common_chat_parse(
  747. "Let's call something\n"
  748. "<tool_call>{\"name",
  749. /* is_partial= */ true,
  750. {
  751. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  752. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  753. }));
  754. assert_msg_equals(message_assist_call_thoughts,
  755. common_chat_parse(
  756. // QwQ-32B's template adds a trailing <think> if add_generation_prompt
  757. "I'm\nthinking</think>\n"
  758. "<tool_call>{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}</tool_call>",
  759. /* is_partial= */ false,
  760. {
  761. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  762. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  763. /* .reasoning_in_content = */ false,
  764. /* .thinking_forced_open = */ true,
  765. }));
  766. assert_msg_equals(
  767. message_assist_call,
  768. common_chat_parse(
  769. "<tool_call>\n"
  770. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  771. "</tool_call>",
  772. /* is_partial= */ false,
  773. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  774. assert_msg_equals(message_assist_call_content,
  775. common_chat_parse(
  776. "Hello, world!\nWhat's up?<tool_call>\n"
  777. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  778. "</tool_call>",
  779. /* is_partial= */ false,
  780. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  781. assert_msg_equals(
  782. message_assist_call,
  783. common_chat_parse(
  784. "<function=special_function>{\"arg1\": 1}</function>",
  785. /* is_partial= */ false,
  786. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  787. assert_msg_equals(
  788. message_assist_call,
  789. common_chat_parse(
  790. "<function name=\"special_function\">\n"
  791. "{\"arg1\": 1}\n"
  792. "</function>",
  793. /* is_partial= */ false,
  794. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  795. assert_msg_equals(
  796. message_assist_call,
  797. common_chat_parse(
  798. "<tool>\n"
  799. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  800. "</tool>",
  801. /* is_partial= */ false,
  802. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  803. assert_msg_equals(
  804. message_assist_call,
  805. common_chat_parse(
  806. "<tools>\n"
  807. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  808. "</tools>",
  809. /* is_partial= */ false,
  810. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  811. assert_msg_equals(
  812. message_assist_call,
  813. common_chat_parse(
  814. "<response>\n"
  815. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  816. "</response>",
  817. /* is_partial= */ false,
  818. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  819. assert_msg_equals(
  820. message_assist_call,
  821. common_chat_parse(
  822. "```xml\n"
  823. "<response>\n"
  824. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  825. "</response>\n"
  826. "```",
  827. /* is_partial= */ false,
  828. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  829. assert_msg_equals(
  830. message_assist_call,
  831. common_chat_parse(
  832. "```xml\n"
  833. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  834. "```",
  835. /* is_partial= */ false,
  836. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  837. assert_msg_equals(
  838. message_assist_call,
  839. common_chat_parse(
  840. "```\n"
  841. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  842. "```",
  843. /* is_partial= */ false,
  844. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  845. assert_msg_equals(
  846. message_assist_call,
  847. common_chat_parse(
  848. "```\n"
  849. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  850. "```",
  851. /* is_partial= */ false,
  852. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  853. assert_msg_equals(
  854. message_assist_call,
  855. common_chat_parse(
  856. "```json\n"
  857. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  858. "```",
  859. /* is_partial= */ false,
  860. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  861. assert_msg_equals(
  862. message_assist_call,
  863. common_chat_parse(
  864. "```json\n"
  865. "\n"
  866. " <function_call> {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}} \n"
  867. " </function_call> \n"
  868. "``` ",
  869. /* is_partial= */ false,
  870. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  871. assert_msg_equals(
  872. message_assist_call,
  873. common_chat_parse(
  874. "<json>\n"
  875. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  876. "</json>",
  877. /* is_partial= */ false,
  878. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  879. assert_msg_equals(
  880. message_assist_call,
  881. common_chat_parse(
  882. "<xml>\n"
  883. " {\n"
  884. " \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}\n"
  885. " }\n"
  886. "</xml>",
  887. /* is_partial= */ false,
  888. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  889. assert_msg_equals(
  890. message_assist_call,
  891. common_chat_parse(
  892. "<JSON>\n"
  893. " {\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  894. "</JSON>",
  895. /* is_partial= */ false,
  896. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  897. assert_msg_equals(
  898. message_assist_call,
  899. common_chat_parse(
  900. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  901. /* is_partial= */ false,
  902. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  903. assert_msg_equals(
  904. message_assist_call,
  905. common_chat_parse(
  906. "{\n \"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  907. /* is_partial= */ false,
  908. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  909. // Test multiple tool calls
  910. common_chat_msg message_assist_multiple_calls;
  911. message_assist_multiple_calls.role = "assistant";
  912. message_assist_multiple_calls.content = "";
  913. message_assist_multiple_calls.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  914. message_assist_multiple_calls.tool_calls.push_back({"python", "{\"code\":\"print('hello')\"}", ""});
  915. assert_msg_equals(
  916. message_assist_multiple_calls,
  917. common_chat_parse(
  918. "<tool_call>\n"
  919. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  920. "</tool_call>\n"
  921. "<tool_call>\n"
  922. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('hello')\"}}\n"
  923. "</tool_call>",
  924. /* is_partial= */ false,
  925. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  926. assert_msg_equals(
  927. message_assist_multiple_calls,
  928. common_chat_parse(
  929. "<function=special_function>{\"arg1\": 1}</function>\n"
  930. "<function=python>{\"code\":\"print('hello')\"}</function>",
  931. /* is_partial= */ false,
  932. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  933. assert_msg_equals(
  934. simple_assist_msg(
  935. "This is not a tool call:",
  936. "",
  937. "special_function",
  938. "{\"arg1\": 1}"),
  939. common_chat_parse(
  940. "This is not a tool call:\n"
  941. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}",
  942. /* is_partial= */ false,
  943. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  944. assert_msg_equals(message_assist,
  945. common_chat_parse(
  946. "Hello, world!\nWhat's up?",
  947. /* is_partial= */ false,
  948. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  949. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  950. common_chat_parse(
  951. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  952. /* is_partial= */ false,
  953. {COMMON_CHAT_FORMAT_HERMES_2_PRO}));
  954. // assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  955. // common_chat_parse(
  956. // "I'm\nthinking</think>Hello, world!\nWhat's up?",
  957. // COMMON_CHAT_FORMAT_HERMES_2_PRO));
  958. assert_msg_equals(message_assist_thoughts,
  959. common_chat_parse(
  960. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  961. /* is_partial= */ false,
  962. {
  963. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  964. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  965. }));
  966. assert_msg_equals(message_assist_thoughts,
  967. common_chat_parse(
  968. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  969. /* is_partial= */ true,
  970. {
  971. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  972. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  973. }));
  974. assert_msg_equals(message_assist_thoughts_unparsed_md,
  975. common_chat_parse(
  976. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  977. /* is_partial= */ false,
  978. {
  979. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  980. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  981. /* .reasoning_in_content = */ true,
  982. /* .thinking_forced_open = */ false,
  983. /* .parse_tool_calls = */ false,
  984. }));
  985. assert_msg_equals(message_assist_thoughts_unparsed_md_partial,
  986. common_chat_parse(
  987. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?\n```json\n{}```",
  988. /* is_partial= */ true,
  989. {
  990. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  991. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  992. /* .reasoning_in_content = */ true,
  993. /* .thinking_forced_open = */ false,
  994. }));
  995. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  996. common_chat_parse(
  997. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  998. /* is_partial= */ false,
  999. {
  1000. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1001. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1002. }));
  1003. assert_msg_equals(message_assist_thoughts,
  1004. common_chat_parse(
  1005. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1006. /* is_partial= */ false,
  1007. {
  1008. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1009. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1010. /* .reasoning_in_content = */ false,
  1011. /* .thinking_forced_open = */ true,
  1012. }));
  1013. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1014. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1015. "<tool_call>\n"
  1016. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1017. "</tool_call>");
  1018. // Test multiple tool calls with template
  1019. common_chat_msg message_assist_multiple_calls_template;
  1020. message_assist_multiple_calls_template.role = "assistant";
  1021. message_assist_multiple_calls_template.content = "";
  1022. message_assist_multiple_calls_template.tool_calls.push_back({"special_function", "{\"arg1\": 1}", ""});
  1023. message_assist_multiple_calls_template.tool_calls.push_back({"python", "{\"code\":\"print('test')\"}", ""});
  1024. test_templates(tmpls.get(), end_tokens, message_assist_multiple_calls_template, tools,
  1025. "<tool_call>\n"
  1026. "{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}\n"
  1027. "</tool_call>\n"
  1028. "<tool_call>\n"
  1029. "{\"name\": \"python\", \"arguments\": {\"code\":\"print('test')\"}}\n"
  1030. "</tool_call>");
  1031. test_templates(tmpls.get(), end_tokens, message_assist_call_python_lines, tools,
  1032. "<tool_call>\n"
  1033. "{\"name\": \"python\", \"arguments\": {\"code\":\"# This is a program:\\nprint('hey')\"}}\n"
  1034. "</tool_call>");
  1035. assert_msg_equals(
  1036. simple_assist_msg("", /* reasoning_content= */ "<tool_call>nah uhg</tool_call>"),
  1037. common_chat_parse(
  1038. "<think><tool_call>nah uhg</tool_call>",
  1039. /* is_partial= */ false,
  1040. {
  1041. /* .format = */ COMMON_CHAT_FORMAT_HERMES_2_PRO,
  1042. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1043. }));
  1044. }
  1045. {
  1046. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.1-8B-Instruct.jinja");
  1047. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1048. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1049. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1050. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1051. common_chat_templates_apply(tmpls.get(), inputs_tools_builtin).format);
  1052. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS,
  1053. common_chat_templates_apply(
  1054. read_templates("models/templates/meta-llama-Llama-3.3-70B-Instruct.jinja").get(),
  1055. inputs_tools_builtin)
  1056. .format);
  1057. assert_equals(
  1058. message_assist_call,
  1059. common_chat_parse(
  1060. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}",
  1061. /* is_partial= */ false,
  1062. {COMMON_CHAT_FORMAT_LLAMA_3_X}));
  1063. // test_templates(tmpls.get(), end_tokens, message_assist, tools, R"(?)", /* expect_grammar_triggered= */ false);
  1064. test_templates(tmpls.get(), end_tokens, message_assist_call_code_interpreter, llama_3_1_tools,
  1065. "<|python_tag|>code_interpreter.call(code=\"print('hey')\")");
  1066. test_templates(tmpls.get(), end_tokens, message_assist_call_python, tools,
  1067. "<|python_tag|>python.call(code=\"print('hey')\")");
  1068. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1069. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1070. }
  1071. {
  1072. auto tmpls = read_templates("models/templates/meta-llama-Llama-3.2-3B-Instruct.jinja");
  1073. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1074. assert_equals(COMMON_CHAT_FORMAT_LLAMA_3_X, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1075. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1076. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1077. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1078. "{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}");
  1079. }
  1080. {
  1081. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.1.jinja");
  1082. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1083. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1084. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1085. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1,
  1086. common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1087. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY,
  1088. common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1089. for (auto is_partial : { false, true }) {
  1090. assert_equals(
  1091. message_assist_call,
  1092. common_chat_parse(
  1093. "<function=special_function>{\"arg1\": 1}</function>",
  1094. is_partial,
  1095. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1096. }
  1097. assert_equals(
  1098. message_assist_call,
  1099. common_chat_parse(
  1100. "<function=special_function>{\"arg1\": 1}<",
  1101. /* is_partial= */ true,
  1102. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1}));
  1103. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1104. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1105. "<function=special_function>{\"arg1\": 1}</function>");
  1106. }
  1107. {
  1108. auto tmpls = read_templates("models/templates/meetkai-functionary-medium-v3.2.jinja");
  1109. std::vector<std::string> end_tokens{ "<|eom_id|>", "<|eot_id|>" };
  1110. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1111. assert_equals(COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1112. assert_msg_equals(
  1113. simple_assist_msg(
  1114. "Hello, world!\nnono\nWhat's up?",
  1115. "",
  1116. "special_function",
  1117. "{\"arg1\": 1}"),
  1118. common_chat_parse(
  1119. "all\n"
  1120. "Hello, world!\n"
  1121. "nono\n"
  1122. "What's up?>>>special_function\n"
  1123. "{\"arg1\": 1}\n",
  1124. /* is_partial= */ false,
  1125. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1126. assert_msg_equals(message_assist_call_python_lines,
  1127. common_chat_parse(
  1128. "python\n"
  1129. "# This is a program:\n"
  1130. "print('hey')",
  1131. /* is_partial= */ false,
  1132. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1133. assert_msg_equals(message_assist_call_python_lines_unclosed,
  1134. common_chat_parse(
  1135. "python\n"
  1136. "# This is a program:\n"
  1137. "print('hey')",
  1138. /* is_partial= */ true,
  1139. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1140. assert_msg_equals(message_assist_call,
  1141. common_chat_parse(
  1142. "special_function\n"
  1143. "{\"arg1\": 1} \n ",
  1144. /* is_partial= */ false,
  1145. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1146. assert_msg_equals(message_assist,
  1147. common_chat_parse(
  1148. "all\n"
  1149. "Hello, world!\nWhat's up?",
  1150. /* is_partial= */ false,
  1151. {COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2}));
  1152. test_templates(tmpls.get(), end_tokens, message_assist, {},
  1153. "all\n"
  1154. "Hello, world!\n"
  1155. "What's up?",
  1156. /* expect_grammar_triggered= */ false);
  1157. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1158. "special_function\n"
  1159. "{\"arg1\": 1}");
  1160. }
  1161. {
  1162. auto tmpls = read_templates("models/templates/fireworks-ai-llama-3-firefunction-v2.jinja");
  1163. std::vector<std::string> end_tokens{ "<|eot_id|>" };
  1164. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1165. assert_equals(COMMON_CHAT_FORMAT_FIREFUNCTION_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1166. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1167. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1168. " functools[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]");
  1169. }
  1170. {
  1171. // Original DeepSeek R1 template. Leaves <|tool▁calls▁begin|> and others unclosed. Our logic fixes the prompt.
  1172. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-R1-Distill-Llama-8B.jinja");
  1173. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1174. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  1175. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  1176. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, params.format);
  1177. assert_equals(true, params.thinking_forced_open);
  1178. }
  1179. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1180. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1181. assert_msg_equals(
  1182. simple_assist_msg("Hello, world!\nWhat's up?", "<think>I'm\nthinking"),
  1183. common_chat_parse(
  1184. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1185. /* is_partial= */ false,
  1186. {
  1187. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1188. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1189. /* .reasoning_in_content = */ false,
  1190. /* .thinking_forced_open = */ true,
  1191. }));
  1192. assert_msg_equals(
  1193. simple_assist_msg("", "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with"),
  1194. common_chat_parse(
  1195. "I need to remember the correct syntax. It starts with <|tool▁calls▁begin|> and ends with",
  1196. /* is_partial= */ true,
  1197. {
  1198. COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1199. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1200. /* .reasoning_in_content = */ false,
  1201. /* .thinking_forced_open = */ true,
  1202. }));
  1203. assert_msg_equals(message_assist_thoughts,
  1204. common_chat_parse(
  1205. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1206. /* is_partial= */ false,
  1207. {
  1208. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1209. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1210. }));
  1211. assert_msg_equals(message_assist_thoughts_unopened_unparsed,
  1212. common_chat_parse(
  1213. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1214. /* is_partial= */ false,
  1215. {
  1216. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1217. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1218. }));
  1219. assert_msg_equals(message_assist_thoughts,
  1220. common_chat_parse(
  1221. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1222. /* is_partial= */ false,
  1223. {
  1224. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1225. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1226. /* .reasoning_in_content = */ false,
  1227. /* .thinking_forced_open = */ true,
  1228. }));
  1229. assert_msg_equals(message_assist_thoughts,
  1230. // Latest template update (ast of 20250209) adds a trailing <think>\n if add_generation_prompt is true.
  1231. common_chat_parse(
  1232. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1233. /* is_partial= */ false,
  1234. {
  1235. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1236. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1237. /* .reasoning_in_content = */ false,
  1238. /* .thinking_forced_open = */ true,
  1239. }));
  1240. // test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1241. // "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1242. // "```json\n"
  1243. // "{\"arg1\": 1}\n"
  1244. // // 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)
  1245. // "```<|tool▁call▁end|>",
  1246. // /* expect_grammar_triggered= */ true,
  1247. // /* test_grammar_if_triggered= */ false);
  1248. }
  1249. {
  1250. // Replacement DeepSeek R1 template. Makes the Distill Qwen 7B/32B models happy to call tools and all.
  1251. auto tmpls = read_templates("models/templates/llama-cpp-deepseek-r1.jinja");
  1252. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1253. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1254. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_R1, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1255. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1256. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1257. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1258. common_chat_parse(
  1259. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1260. /* is_partial= */ false,
  1261. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1262. assert_msg_equals(message_assist_thoughts,
  1263. common_chat_parse(
  1264. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1265. /* is_partial= */ false,
  1266. {
  1267. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1268. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1269. }));
  1270. assert_msg_equals(message_assist_thoughts,
  1271. common_chat_parse(
  1272. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1273. /* is_partial= */ false,
  1274. {
  1275. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1276. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1277. /* .reasoning_in_content = */ false,
  1278. /* .thinking_forced_open = */ true,
  1279. }));
  1280. assert_msg_equals(message_assist_call_thoughts_unparsed,
  1281. common_chat_parse(
  1282. "<think>I'm\nthinking</think>\n\n"
  1283. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1284. "```json\n"
  1285. "{\"arg1\": 1}\n"
  1286. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1287. /* is_partial= */ false,
  1288. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1289. assert_msg_equals(message_assist_call,
  1290. common_chat_parse(
  1291. "<|tool▁calls|>function<|tool▁sep|>special_function\n"
  1292. "```json\n"
  1293. "{\"arg1\": 1}\n"
  1294. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1295. /* is_partial= */ false,
  1296. {COMMON_CHAT_FORMAT_DEEPSEEK_R1}));
  1297. assert_msg_equals(message_assist_call_thoughts,
  1298. common_chat_parse(
  1299. "<think>I'm\nthinking</think>\n\n"
  1300. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1301. "```json\n"
  1302. "{\"arg1\": 1}\n"
  1303. "```<|tool▁call▁end|><|tool▁calls▁end|>",
  1304. /* is_partial= */ false,
  1305. {
  1306. /* .format = */ COMMON_CHAT_FORMAT_DEEPSEEK_R1,
  1307. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1308. }));
  1309. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1310. "<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>special_function\n"
  1311. "```json\n"
  1312. "{\"arg1\": 1}\n"
  1313. "```<|tool▁call▁end|><|tool▁calls▁end|>");
  1314. }
  1315. {
  1316. auto tmpls = read_templates("models/templates/ibm-granite-granite-3.3-2B-Instruct.jinja");
  1317. std::vector<std::string> end_tokens{ "<|end_of_text|>" };
  1318. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1319. assert_equals(COMMON_CHAT_FORMAT_GRANITE, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1320. // Test parsing regular content
  1321. assert_msg_equals(message_assist,
  1322. common_chat_parse(
  1323. "Hello, world!\nWhat's up?",
  1324. /* is_partial= */ false,
  1325. {COMMON_CHAT_FORMAT_GRANITE}));
  1326. assert_msg_equals(
  1327. message_assist,
  1328. common_chat_parse(
  1329. "Hello, world!\nWhat's up?",
  1330. /* is_partial= */ true,
  1331. {COMMON_CHAT_FORMAT_GRANITE}));
  1332. // Test parsing content with thinking
  1333. assert_msg_equals(message_assist_thoughts,
  1334. common_chat_parse(
  1335. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1336. /* is_partial= */ false,
  1337. {
  1338. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1339. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1340. }));
  1341. assert_msg_equals(message_assist_thoughts_unparsed_deepseek,
  1342. common_chat_parse(
  1343. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1344. /* is_partial= */ false,
  1345. {COMMON_CHAT_FORMAT_GRANITE}));
  1346. assert_msg_equals(message_assist_thoughts,
  1347. common_chat_parse(
  1348. "<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?",
  1349. /* is_partial= */ true,
  1350. {
  1351. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1352. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1353. }));
  1354. assert_msg_equals(message_assist_thoughts,
  1355. common_chat_parse(
  1356. "<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?</response>",
  1357. /* is_partial= */ false,
  1358. {
  1359. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1360. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1361. }));
  1362. assert_msg_equals(simple_assist_msg("<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?</response>"),
  1363. common_chat_parse(
  1364. "<think>I'm\nthinking</think><response>Hello, world!\nWhat's up?</response>",
  1365. /* is_partial= */ false,
  1366. {COMMON_CHAT_FORMAT_GRANITE}));
  1367. assert_msg_equals(message_assist_empty,
  1368. common_chat_parse(
  1369. "<think",
  1370. /* is_partial= */ true,
  1371. {
  1372. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1373. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1374. }));
  1375. assert_msg_equals(message_assist_empty,
  1376. common_chat_parse(
  1377. "<think",
  1378. /* is_partial= */ true,
  1379. {COMMON_CHAT_FORMAT_GRANITE}));
  1380. assert_msg_equals(message_assist_thoughts_no_content,
  1381. common_chat_parse(
  1382. "<think>I'm\nthinking",
  1383. /* is_partial= */ true,
  1384. {
  1385. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1386. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1387. }));
  1388. assert_msg_equals(
  1389. message_assist_empty,
  1390. common_chat_parse(
  1391. "<think>I'm\nthinking</think><response",
  1392. /* is_partial= */ true,
  1393. {COMMON_CHAT_FORMAT_GRANITE}));
  1394. // Test parsing tool calls
  1395. assert_msg_equals(message_assist_call,
  1396. common_chat_parse(
  1397. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]",
  1398. /* is_partial= */ false,
  1399. {COMMON_CHAT_FORMAT_GRANITE}));
  1400. assert_msg_equals(
  1401. message_assist_call_empty_args,
  1402. common_chat_parse(
  1403. "<|tool_call|>[{\"name\": \"special_function\"",
  1404. /* is_partial= */ true,
  1405. {COMMON_CHAT_FORMAT_GRANITE}));
  1406. assert_msg_equals(
  1407. message_assist_call_cutoff_args,
  1408. common_chat_parse(
  1409. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg",
  1410. /* is_partial= */ true,
  1411. {COMMON_CHAT_FORMAT_GRANITE}));
  1412. assert_msg_equals(
  1413. message_assist_call_cutoff_args,
  1414. common_chat_parse(
  1415. "<|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg",
  1416. /* is_partial= */ true,
  1417. {
  1418. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1419. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1420. }));
  1421. // Test parsing tool calls with thinking
  1422. assert_msg_equals(
  1423. message_assist_call_thoughts,
  1424. common_chat_parse(
  1425. "<think>I'm\nthinking</think><|tool_call|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}, {",
  1426. /* is_partial= */ true,
  1427. {
  1428. /* .format = */ COMMON_CHAT_FORMAT_GRANITE,
  1429. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1430. }));
  1431. // Test template generation for regular content
  1432. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1433. "Hello, world!\nWhat's up?",
  1434. /* expect_grammar_triggered= */ false);
  1435. // Test template generation for tool calls
  1436. test_templates(tmpls.get(), end_tokens, message_assist_call_id, tools,
  1437. "{\n"
  1438. " \"tool_calls\": [\n"
  1439. " {\n"
  1440. " \"name\": \"special_function\",\n"
  1441. " \"arguments\": {\n"
  1442. " \"arg1\": 1\n"
  1443. " },\n"
  1444. " \"id\": \"123456789\"\n"
  1445. " }\n"
  1446. " ]\n"
  1447. "}",
  1448. /* expect_grammar_triggered= */ false
  1449. );
  1450. }
  1451. {
  1452. auto tmpls = read_templates("models/templates/openai-gpt-oss-120b.jinja");
  1453. std::vector<std::string> end_tokens{ "<|return|>", "<|call|>" };
  1454. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1455. assert_equals(COMMON_CHAT_FORMAT_GPT_OSS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1456. assert_msg_equals(simple_assist_msg("", "I'm\nthink"),
  1457. common_chat_parse(
  1458. "<|channel|>analysis<|message|>I'm\nthink",
  1459. /* is_partial= */ true,
  1460. {
  1461. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1462. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1463. }));
  1464. assert_msg_equals(simple_assist_msg("", "I'm\nthinking"),
  1465. common_chat_parse(
  1466. "<|channel|>analysis<|message|>I'm\nthinking<|end|>",
  1467. /* is_partial= */ true,
  1468. {
  1469. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1470. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1471. }));
  1472. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1473. common_chat_parse(
  1474. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1475. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1476. /* is_partial= */ false,
  1477. {
  1478. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1479. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1480. }));
  1481. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1482. common_chat_parse(
  1483. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1484. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1",
  1485. /* is_partial= */ true,
  1486. {
  1487. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1488. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1489. }));
  1490. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1"),
  1491. common_chat_parse(
  1492. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1493. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1494. /* is_partial= */ true,
  1495. {
  1496. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1497. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1498. }));
  1499. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1500. common_chat_parse(
  1501. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1502. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1503. /* is_partial= */ false,
  1504. {
  1505. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1506. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1507. }));
  1508. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1509. common_chat_parse(
  1510. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1511. "<|start|>assistant<|channel|>analysis to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1512. /* is_partial= */ false,
  1513. {
  1514. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1515. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1516. }));
  1517. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1518. common_chat_parse(
  1519. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1520. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?",
  1521. /* is_partial= */ true,
  1522. {
  1523. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1524. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1525. }));
  1526. assert_msg_equals(simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1527. common_chat_parse(
  1528. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1529. "<|start|>assistant<|channel|>commentary<|message|>Hello, world!\nWhat's up?<|end|>"
  1530. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1531. /* is_partial= */ true,
  1532. {
  1533. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1534. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1535. }));
  1536. // Test parse_tool_calls == false
  1537. assert_msg_equals(
  1538. simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1539. common_chat_parse(
  1540. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1541. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1542. /* is_partial= */ true,
  1543. {
  1544. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1545. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1546. /* .reasoning_in_content = */ false,
  1547. /* .thinking_forced_open = */ false,
  1548. /* .parse_tool_calls = */ false,
  1549. }));
  1550. assert_msg_equals(
  1551. simple_assist_msg("", "I'm\nthinking"),
  1552. common_chat_parse(
  1553. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1554. "<|start|>assistant<|channel|>commentary to=functions.special_function<|message|>{\"arg1",
  1555. /* is_partial= */ true,
  1556. {
  1557. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1558. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1559. /* .reasoning_in_content = */ false,
  1560. /* .thinking_forced_open = */ false,
  1561. /* .parse_tool_calls = */ false,
  1562. }));
  1563. assert_msg_equals(
  1564. simple_assist_msg("", "I'm\nthinking"),
  1565. common_chat_parse(
  1566. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1567. "<|start|>assistant<|channel|>commentary to=functions.special_function <|constrain|>json<|message|>{\"arg1\": 1}",
  1568. /* is_partial= */ false,
  1569. {
  1570. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1571. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1572. /* .reasoning_in_content = */ false,
  1573. /* .thinking_forced_open = */ false,
  1574. /* .parse_tool_calls = */ false,
  1575. }));
  1576. // Test reasoning formats
  1577. assert_msg_equals(
  1578. simple_assist_msg(
  1579. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1580. common_chat_parse(
  1581. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1582. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1583. /* is_partial= */ false,
  1584. {
  1585. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1586. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  1587. }));
  1588. assert_msg_equals(
  1589. simple_assist_msg(
  1590. "<|channel|>analysis<|message|>I'm\nthinking<|end|>Hello, world!\nWhat's up?"),
  1591. common_chat_parse(
  1592. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1593. "<|start|>assistant<|channel|>final<|message|>Hello, world!\nWhat's up?",
  1594. /* is_partial= */ false,
  1595. {
  1596. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1597. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1598. /* .reasoning_in_content = */ true,
  1599. }));
  1600. // Test tool calling in role header
  1601. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1602. common_chat_parse(
  1603. " to=functions.special_function<|channel|>commentary <|constrain|>json<|message|>{\"arg1\": 1}",
  1604. /* is_partial= */ false,
  1605. {
  1606. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1607. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1608. }));
  1609. assert_msg_equals(simple_assist_msg("", "", "special_function", "{\"arg1\": 1}"),
  1610. common_chat_parse(
  1611. " to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1612. /* is_partial= */ false,
  1613. {
  1614. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1615. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1616. }));
  1617. assert_msg_equals(simple_assist_msg("", "I'm\nthinking", "special_function", "{\"arg1\": 1}"),
  1618. common_chat_parse(
  1619. "<|channel|>analysis<|message|>I'm\nthinking<|end|>"
  1620. "<|start|>assistant to=functions.special_function<|channel|>analysis <|constrain|>json<|message|>{\"arg1\": 1}",
  1621. /* is_partial= */ false,
  1622. {
  1623. /* .format = */ COMMON_CHAT_FORMAT_GPT_OSS,
  1624. /* .reasoning_format = */ COMMON_REASONING_FORMAT_AUTO,
  1625. }));
  1626. }
  1627. {
  1628. // Seed-OSS format tests
  1629. auto tmpls = read_templates("models/templates/ByteDance-Seed-OSS.jinja");
  1630. std::vector<std::string> end_tokens{ "<seed:eos>" };
  1631. assert_equals(COMMON_CHAT_FORMAT_SEED_OSS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1632. assert_equals(COMMON_CHAT_FORMAT_SEED_OSS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1633. test_templates(tmpls.get(), end_tokens, message_assist, tools, "Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1634. // Test simple reasoning content
  1635. assert_msg_equals(
  1636. simple_assist_msg("Hello, world!", "I'm thinking about the answer"),
  1637. common_chat_parse(
  1638. "<seed:think>I'm thinking about the answer</seed:think>Hello, world!",
  1639. /* is_partial= */ false,
  1640. {
  1641. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1642. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1643. }));
  1644. // Test budget reflection tags
  1645. common_chat_msg msg_budget_reflect;
  1646. msg_budget_reflect.role = "assistant";
  1647. 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.";
  1648. msg_budget_reflect.reasoning_content = "Token usage: 45/1000\nI should continue thinking to find the best solution.";
  1649. assert_msg_equals(
  1650. msg_budget_reflect,
  1651. common_chat_parse(
  1652. "<seed:think>Token usage: 45/1000\nI should continue thinking to find the best solution.</seed:think>"
  1653. "<seed:cot_budget_reflect>Token usage: 45/1000\nI should continue thinking to find the best solution.</seed:cot_budget_reflect>"
  1654. "I need to calculate this step by step.",
  1655. /* is_partial= */ false,
  1656. {
  1657. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1658. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1659. }));
  1660. // Test tool calls with Seed-OSS format
  1661. common_chat_msg msg_tool_call;
  1662. msg_tool_call.role = "assistant";
  1663. msg_tool_call.tool_calls.push_back({"calculate_sum", "{\"numbers\": [1, 2, 3]}", ""});
  1664. assert_msg_equals(
  1665. msg_tool_call,
  1666. common_chat_parse(
  1667. "<seed:tool_call>\n"
  1668. "<function=calculate_sum>\n"
  1669. "<parameter=numbers>[1, 2, 3]</parameter>\n"
  1670. "</function>\n"
  1671. "</seed:tool_call>",
  1672. /* is_partial= */ false,
  1673. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1674. // Test reasoning + tool call combination
  1675. common_chat_msg msg_reasoning_tool;
  1676. msg_reasoning_tool.role = "assistant";
  1677. msg_reasoning_tool.content = "";
  1678. msg_reasoning_tool.reasoning_content = "I need to calculate the sum of these numbers";
  1679. msg_reasoning_tool.tool_calls.push_back({"calculate_sum", "{\"numbers\": [1, 2, 3]}", ""});
  1680. assert_msg_equals(
  1681. msg_reasoning_tool,
  1682. common_chat_parse(
  1683. "<seed:think>I need to calculate the sum of these numbers</seed:think>"
  1684. "<seed:tool_call>\n"
  1685. "<function=calculate_sum>\n"
  1686. "<parameter=numbers>[1, 2, 3]</parameter>\n"
  1687. "</function>\n"
  1688. "</seed:tool_call>",
  1689. /* is_partial= */ false,
  1690. {
  1691. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1692. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1693. }));
  1694. // Test deltas: the number of tool calls in partial parses should never decrease
  1695. std::string tool_msg = "<seed:tool_call>\n"
  1696. "<function=fun>\n"
  1697. "<parameter=smth>[1, 2, 3]</parameter>\n"
  1698. "</function>";
  1699. std::size_t previousToolCalls = 0;
  1700. for (std::size_t i = std::string("<seed:tool_call>").length(); i < tool_msg.length() - 1; i++) {
  1701. auto partial = tool_msg.substr(0, i);
  1702. auto partial_res = common_chat_parse(partial, true, { COMMON_CHAT_FORMAT_SEED_OSS, COMMON_REASONING_FORMAT_DEEPSEEK });
  1703. if (partial_res.tool_calls.size() < previousToolCalls) {
  1704. 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()));
  1705. }
  1706. previousToolCalls = partial_res.tool_calls.size();
  1707. }
  1708. // Test multiple parameters in tool call
  1709. common_chat_msg msg_multi_param;
  1710. msg_multi_param.role = "assistant";
  1711. msg_multi_param.tool_calls.push_back({"process_data", "{\"input\": \"test\", \"format\": \"json\"}", ""});
  1712. assert_msg_equals(
  1713. msg_multi_param,
  1714. common_chat_parse(
  1715. "<seed:tool_call>\n"
  1716. "<function=process_data>\n"
  1717. "<parameter=input>test</parameter>\n"
  1718. "<parameter=format>json</parameter>\n"
  1719. "</function>\n"
  1720. "</seed:tool_call>",
  1721. /* is_partial= */ false,
  1722. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1723. // Test partial parsing for incomplete tool call - don't actually add the call until parsing parameters is done
  1724. assert_msg_equals(
  1725. simple_assist_msg("", ""),
  1726. common_chat_parse(
  1727. "<seed:tool_call>\n"
  1728. "<function=calculate_sum>\n"
  1729. "<parameter=numbers>[1,\n",
  1730. /* is_partial= */ true,
  1731. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1732. // Test incomplete reasoning tag
  1733. assert_msg_equals(
  1734. simple_assist_msg("", "I was thinking"),
  1735. common_chat_parse(
  1736. "<seed:think>I was thinking",
  1737. /* is_partial= */ true,
  1738. {
  1739. /* .format = */ COMMON_CHAT_FORMAT_SEED_OSS,
  1740. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1741. }));
  1742. // Test content without reasoning
  1743. assert_msg_equals(
  1744. simple_assist_msg("This is a simple response without reasoning."),
  1745. common_chat_parse(
  1746. "This is a simple response without reasoning.",
  1747. /* is_partial= */ false,
  1748. {COMMON_CHAT_FORMAT_SEED_OSS}));
  1749. }
  1750. {
  1751. auto tmpls = read_templates("models/templates/NVIDIA-Nemotron-Nano-v2.jinja");
  1752. std::vector<std::string> end_tokens{ "<SPECIAL_12>" };
  1753. assert_equals(COMMON_CHAT_FORMAT_NEMOTRON_V2, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1754. assert_equals(COMMON_CHAT_FORMAT_NEMOTRON_V2, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1755. // Test parsing regular content
  1756. assert_msg_equals(message_assist,
  1757. common_chat_parse(
  1758. "Hello, world!\nWhat's up?",
  1759. /* is_partial= */ false,
  1760. {COMMON_CHAT_FORMAT_NEMOTRON_V2}));
  1761. // Test parsing content with thinking
  1762. assert_msg_equals(message_assist_thoughts,
  1763. common_chat_parse(
  1764. "<think>I'm\nthinking</think>Hello, world!\nWhat's up?",
  1765. /* is_partial= */ false,
  1766. {
  1767. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1768. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1769. }));
  1770. // Test parsing tool calls
  1771. assert_msg_equals(message_assist_call,
  1772. common_chat_parse(
  1773. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1774. /* is_partial= */ false,
  1775. {COMMON_CHAT_FORMAT_NEMOTRON_V2}));
  1776. // Test parsing tool calls with thinking
  1777. assert_msg_equals(message_assist_call_thoughts,
  1778. common_chat_parse(
  1779. "<think>I'm\nthinking</think><TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1780. /* is_partial= */ false,
  1781. {
  1782. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1783. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1784. }));
  1785. // Test tool calls with extra content
  1786. assert_msg_equals(message_assist_call_content,
  1787. common_chat_parse(
  1788. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>Hello, world!\nWhat's up?",
  1789. /* is_partial= */ false,
  1790. {COMMON_CHAT_FORMAT_NEMOTRON_V2}
  1791. ));
  1792. // Test tool calls with extra content AND thinking
  1793. assert_msg_equals(message_assist_call_thoughts_content,
  1794. common_chat_parse(
  1795. "<think>I'm\nthinking</think><TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>Hello, world!\nWhat's up?",
  1796. /* is_partial= */ false,
  1797. {
  1798. /* .format = */ COMMON_CHAT_FORMAT_NEMOTRON_V2,
  1799. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1800. }));
  1801. // Test template generation for regular content
  1802. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1803. "Hello, world!\nWhat's up?\n",
  1804. /* expect_grammar_triggered= */ false);
  1805. // Test template generation for tool calls
  1806. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1807. "<TOOLCALL>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]</TOOLCALL>",
  1808. /* expect_grammar_triggered= */ true
  1809. );
  1810. }
  1811. {
  1812. auto tmpls = read_templates("models/templates/deepseek-ai-DeepSeek-V3.1.jinja");
  1813. std::vector<std::string> end_tokens{ "<|end▁of▁sentence|>" };
  1814. for (const auto & inputs : { inputs_no_tools, inputs_tools }) {
  1815. auto params = common_chat_templates_apply(tmpls.get(), inputs);
  1816. assert_equals(COMMON_CHAT_FORMAT_DEEPSEEK_V3_1, params.format);
  1817. assert_equals(true, params.thinking_forced_open);
  1818. }
  1819. test_templates(tmpls.get(), end_tokens, message_assist, tools, "</think>Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1820. test_templates(tmpls.get(), end_tokens, message_assist_thoughts, tools, "</think>Hello, world!\nWhat's up?", /* expect_grammar_triggered= */ false);
  1821. assert_msg_equals(
  1822. simple_assist_msg("Hello, world!\nWhat's up?", "I'm\nthinking"),
  1823. common_chat_parse(
  1824. "I'm\nthinking</think>Hello, world!\nWhat's up?",
  1825. /* is_partial= */ false,
  1826. {
  1827. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1828. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1829. /* .reasoning_in_content = */ false,
  1830. /* .thinking_forced_open = */ true,
  1831. }));
  1832. // variant: thinking forced open, reasoning_format none
  1833. assert_msg_equals(
  1834. simple_assist_msg("REASONING</think>ok", ""),
  1835. common_chat_parse(
  1836. "REASONING</think>ok",
  1837. /* is_partial= */ false,
  1838. {
  1839. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1840. /* .reasoning_format = */ COMMON_REASONING_FORMAT_NONE,
  1841. /* .reasoning_in_content = */ false,
  1842. /* .thinking_forced_open = */ true,
  1843. /* .parse_tool_calls = */ true,
  1844. }));
  1845. // variant: happy path for when it works as the model card says it should
  1846. assert_msg_equals(
  1847. simple_assist_msg("", "", "get_time", "{\"city\":\"Tokyo\"}"),
  1848. common_chat_parse(
  1849. "<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1850. /* is_partial= */ false,
  1851. {
  1852. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1853. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1854. /* .reasoning_in_content = */ false,
  1855. /* .thinking_forced_open = */ false,
  1856. /* .parse_tool_calls = */ true,
  1857. }));
  1858. // variant: simple + thinking open
  1859. assert_msg_equals(
  1860. simple_assist_msg("", "REASONING", "get_time", "{\"city\":\"Tokyo\"}"),
  1861. common_chat_parse(
  1862. "REASONING</think><|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1863. /* is_partial= */ false,
  1864. {
  1865. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1866. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1867. /* .reasoning_in_content = */ false,
  1868. /* .thinking_forced_open = */ true,
  1869. /* .parse_tool_calls = */ true,
  1870. }));
  1871. // variant: simple + multiple tool calls
  1872. common_chat_msg message_assist_multiple_calls;
  1873. message_assist_multiple_calls.role = "assistant";
  1874. message_assist_multiple_calls.content = "CONTENT";
  1875. message_assist_multiple_calls.tool_calls.push_back({"get_time", "{\"city\":\"Paris\"}", ""});
  1876. message_assist_multiple_calls.tool_calls.push_back({"get_weather", "{\"city\":\"Paris\"}", ""});
  1877. assert_msg_equals(
  1878. message_assist_multiple_calls,
  1879. common_chat_parse(
  1880. "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|>",
  1881. /* is_partial= */ false,
  1882. {
  1883. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1884. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1885. /* .reasoning_in_content = */ false,
  1886. /* .thinking_forced_open = */ false,
  1887. /* .parse_tool_calls = */ true,
  1888. }));
  1889. // variant: thinking forced open + tool call in reasoning content
  1890. assert_msg_equals(
  1891. 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\"}"),
  1892. common_chat_parse(
  1893. "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|>",
  1894. /* is_partial= */ false,
  1895. {
  1896. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1897. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1898. /* .reasoning_in_content = */ false,
  1899. /* .thinking_forced_open = */ true,
  1900. /* .parse_tool_calls = */ true,
  1901. }));
  1902. // variant: thinking forced open + tool call in reasoning content + no closing think + not partial
  1903. // This is a bit of a fine tuning issue on the model's part IMO. It really should not be attempting
  1904. // to make tool calls in reasoning content according to the model card, but it does sometimes, so
  1905. // add the reasoning content as regular content and parse the tool calls.
  1906. assert_msg_equals(
  1907. simple_assist_msg("REASONING", "", "get_time", "{\"city\":\"Tokyo\"}"),
  1908. common_chat_parse(
  1909. "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1910. /* is_partial= */ false,
  1911. {
  1912. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1913. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1914. /* .reasoning_in_content = */ false,
  1915. /* .thinking_forced_open = */ true,
  1916. /* .parse_tool_calls = */ true,
  1917. }));
  1918. // variant: thinking forced open + tool call in reasoning content + no closing think + partial
  1919. assert_msg_equals(
  1920. simple_assist_msg("", "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>", "", ""),
  1921. common_chat_parse(
  1922. "REASONING<|tool▁calls▁begin|><|tool▁call▁begin|>get_time<|tool▁sep|>{\"city\": \"Tokyo\"}<|tool▁call▁end|><|tool▁calls▁end|>",
  1923. /* is_partial= */ true,
  1924. {
  1925. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1926. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1927. /* .reasoning_in_content = */ false,
  1928. /* .thinking_forced_open = */ true,
  1929. /* .parse_tool_calls = */ true,
  1930. }));
  1931. // variant: thinking not forced open + missing reasoning + no tool calls
  1932. assert_msg_equals(
  1933. simple_assist_msg("CONTENT", ""),
  1934. common_chat_parse(
  1935. "CONTENT",
  1936. /* is_partial= */ false,
  1937. {
  1938. COMMON_CHAT_FORMAT_DEEPSEEK_V3_1,
  1939. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1940. /* .reasoning_in_content = */ false,
  1941. /* .thinking_forced_open = */ false,
  1942. /* .parse_tool_calls = */ true,
  1943. }));
  1944. }
  1945. {
  1946. auto tmpls = read_templates("models/templates/Apertus-8B-Instruct.jinja");
  1947. std::vector<std::string> end_tokens{ "<|assistant_end|>" };
  1948. assert_equals(COMMON_CHAT_FORMAT_APERTUS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1949. assert_equals(COMMON_CHAT_FORMAT_APERTUS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1950. // Test parsing regular content
  1951. assert_msg_equals(message_assist,
  1952. common_chat_parse(
  1953. "Hello, world!\nWhat's up?",
  1954. /* is_partial= */ false,
  1955. {COMMON_CHAT_FORMAT_APERTUS}));
  1956. // Test parsing content with thinking
  1957. assert_msg_equals(message_assist_thoughts,
  1958. common_chat_parse(
  1959. "<|inner_prefix|>I'm\nthinking<|inner_suffix|>Hello, world!\nWhat's up?",
  1960. /* is_partial= */ false,
  1961. {
  1962. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  1963. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1964. }));
  1965. // Test parsing tool calls
  1966. assert_msg_equals(message_assist_call,
  1967. common_chat_parse(
  1968. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  1969. /* is_partial= */ false,
  1970. {COMMON_CHAT_FORMAT_APERTUS}));
  1971. // Test parsing tool calls with thinking
  1972. assert_msg_equals(message_assist_call_thoughts,
  1973. common_chat_parse(
  1974. "<|inner_prefix|>I'm\nthinking<|inner_suffix|><|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  1975. /* is_partial= */ false,
  1976. {
  1977. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  1978. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1979. }));
  1980. // Test tool calls with extra content
  1981. assert_msg_equals(message_assist_call_content,
  1982. common_chat_parse(
  1983. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>Hello, world!\nWhat's up?",
  1984. /* is_partial= */ false,
  1985. {COMMON_CHAT_FORMAT_APERTUS}
  1986. ));
  1987. // Test tool calls with extra content AND thinking
  1988. assert_msg_equals(message_assist_call_thoughts_content,
  1989. common_chat_parse(
  1990. "<|inner_prefix|>I'm\nthinking<|inner_suffix|><|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>Hello, world!\nWhat's up?",
  1991. /* is_partial= */ false,
  1992. {
  1993. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  1994. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1995. }));
  1996. // Test template generation for regular content
  1997. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1998. "Hello, world!\nWhat's up?",
  1999. /* expect_grammar_triggered= */ false);
  2000. // Test template generation for tool calls
  2001. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  2002. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  2003. /* expect_grammar_triggered= */ true
  2004. );
  2005. assert_equals(true, common_chat_templates_support_enable_thinking(tmpls.get()));
  2006. }
  2007. {
  2008. // LFM2 format tests
  2009. auto tmpls = read_templates("models/templates/llama-cpp-lfm2.jinja");
  2010. std::vector<std::string> end_tokens{ "<|im_end|>" };
  2011. auto inputs_tools_forced_json_schema = std::invoke([&]() -> common_chat_templates_inputs {
  2012. common_chat_templates_inputs inputs;
  2013. inputs.messages = {
  2014. std::invoke([&]() -> common_chat_msg {
  2015. common_chat_msg msg;
  2016. msg.role = "system";
  2017. msg.content = "force json schema.\n";
  2018. return msg;
  2019. }),
  2020. message_user,
  2021. };
  2022. inputs.tools = {special_function_tool};
  2023. return inputs;
  2024. });
  2025. {
  2026. auto params = common_chat_templates_apply(tmpls.get(), inputs_no_tools);
  2027. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, params.format);
  2028. assert_equals(false, params.grammar_lazy);
  2029. assert_equals(std::string(R"(<|im_start|>user
  2030. Hey there!<|im_end|>
  2031. <|im_start|>assistant
  2032. )"), params.prompt);
  2033. }
  2034. {
  2035. auto params = common_chat_templates_apply(tmpls.get(), inputs_tools);
  2036. assert_equals(COMMON_CHAT_FORMAT_CONTENT_ONLY, params.format);
  2037. assert_equals(false, params.grammar_lazy);
  2038. assert_equals(std::string(R"(<|im_start|>system
  2039. 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|>
  2040. <|im_start|>user
  2041. Hey there!<|im_end|>
  2042. <|im_start|>assistant
  2043. )"), params.prompt);
  2044. assert_equals(true, params.grammar.empty());
  2045. }
  2046. {
  2047. auto params = common_chat_templates_apply(tmpls.get(), inputs_tools_forced_json_schema);
  2048. assert_equals(COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS, params.format);
  2049. assert_equals(true, params.grammar_lazy);
  2050. assert_equals(std::string(R"(<|im_start|>system
  2051. 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|>
  2052. <|im_start|>user
  2053. Hey there!<|im_end|>
  2054. <|im_start|>assistant
  2055. )"), params.prompt);
  2056. assert_equals(false, params.grammar.empty());
  2057. }
  2058. // Test parsing regular content
  2059. assert_msg_equals(message_assist,
  2060. common_chat_parse(
  2061. "Hello, world!\nWhat's up?",
  2062. /* is_partial= */ false,
  2063. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2064. // Test single tool call with JSON format
  2065. common_chat_msg msg_single_tool_call;
  2066. msg_single_tool_call.role = "assistant";
  2067. msg_single_tool_call.tool_calls.push_back({"special_function", "{\"arg1\":1}", ""});
  2068. assert_msg_equals(
  2069. msg_single_tool_call,
  2070. common_chat_parse(
  2071. "<|tool_call_start|>[{\"name\": \"special_function\", \"arguments\": {\"arg1\": 1}}]<|tool_call_end|>",
  2072. /* is_partial= */ false,
  2073. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2074. // Test tool call with string argument
  2075. common_chat_msg msg_tool_call_string;
  2076. msg_tool_call_string.role = "assistant";
  2077. msg_tool_call_string.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2078. assert_msg_equals(
  2079. msg_tool_call_string,
  2080. common_chat_parse(
  2081. "<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}]<|tool_call_end|>",
  2082. /* is_partial= */ false,
  2083. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2084. // Test tool call with multiple arguments
  2085. common_chat_msg msg_multi_args;
  2086. msg_multi_args.role = "assistant";
  2087. msg_multi_args.tool_calls.push_back({"calculate", "{\"x\":10,\"y\":20,\"operation\":\"add\"}", ""});
  2088. assert_msg_equals(
  2089. msg_multi_args,
  2090. common_chat_parse(
  2091. "<|tool_call_start|>[{\"name\": \"calculate\", \"arguments\": {\"x\": 10, \"y\": 20, \"operation\": \"add\"}}]<|tool_call_end|>",
  2092. /* is_partial= */ false,
  2093. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2094. // Test multiple tool calls in single array
  2095. common_chat_msg msg_multiple_tools;
  2096. msg_multiple_tools.role = "assistant";
  2097. msg_multiple_tools.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2098. msg_multiple_tools.tool_calls.push_back({"get_time", "{\"timezone\":\"UTC\"}", ""});
  2099. assert_msg_equals(
  2100. msg_multiple_tools,
  2101. common_chat_parse(
  2102. "<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}, {\"name\": \"get_time\", \"arguments\": {\"timezone\": \"UTC\"}}]<|tool_call_end|>",
  2103. /* is_partial= */ false,
  2104. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2105. // Test tool call with content before
  2106. common_chat_msg msg_content_before_tool;
  2107. msg_content_before_tool.role = "assistant";
  2108. msg_content_before_tool.content = "Let me check the weather for you.";
  2109. msg_content_before_tool.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2110. assert_msg_equals(
  2111. msg_content_before_tool,
  2112. common_chat_parse(
  2113. "Let me check the weather for you.<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}]<|tool_call_end|>",
  2114. /* is_partial= */ false,
  2115. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2116. // Test tool call with content after
  2117. common_chat_msg msg_content_after_tool;
  2118. msg_content_after_tool.role = "assistant";
  2119. msg_content_after_tool.content = "Here's the result.";
  2120. msg_content_after_tool.tool_calls.push_back({"get_weather", "{\"location\":\"Paris\"}", ""});
  2121. assert_msg_equals(
  2122. msg_content_after_tool,
  2123. common_chat_parse(
  2124. "<|tool_call_start|>[{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Paris\"}}]<|tool_call_end|>Here's the result.",
  2125. /* is_partial= */ false,
  2126. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2127. // Test tool call with newlines (common in LLM output)
  2128. common_chat_msg msg_tool_call_newlines;
  2129. msg_tool_call_newlines.role = "assistant";
  2130. msg_tool_call_newlines.tool_calls.push_back({"get_current_time", "{\"location\":\"Paris\"}", ""});
  2131. assert_msg_equals(
  2132. msg_tool_call_newlines,
  2133. common_chat_parse(
  2134. "<|tool_call_start|>[{\n \"name\": \"get_current_time\",\n \"arguments\": {\n \"location\": \"Paris\"\n }\n}]<|tool_call_end|>",
  2135. /* is_partial= */ false,
  2136. {COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS}));
  2137. // Note: LFM2 uses JSON format for tool calls: [{"name": "...", "arguments": {...}}]
  2138. // Unlike other formats, LFM2 template does not render tool calls in conversation history,
  2139. // so we don't use test_templates() for tool call generation. Instead, the parsing tests
  2140. // above verify edge cases and format variations for the tool call output format.
  2141. }
  2142. }
  2143. static void test_msg_diffs_compute() {
  2144. printf("[%s]\n", __func__);
  2145. {
  2146. common_chat_msg msg1;
  2147. common_chat_msg msg2;
  2148. msg2.content = "Hello, world!";
  2149. common_chat_msg_diff diff;
  2150. diff.content_delta = "Hello, world!";
  2151. assert_equals(
  2152. {diff},
  2153. common_chat_msg_diff::compute_diffs(msg1, msg2));
  2154. }
  2155. {
  2156. common_chat_msg msg1;
  2157. msg1.content = "Hello,";
  2158. common_chat_msg msg2;
  2159. msg2.content = "Hello, world!";
  2160. common_chat_msg_diff diff;
  2161. diff.content_delta = " world!";
  2162. assert_equals(
  2163. {diff},
  2164. common_chat_msg_diff::compute_diffs(msg1, msg2));
  2165. }
  2166. {
  2167. common_chat_msg msg0;
  2168. common_chat_msg msg1;
  2169. msg1.tool_calls = { { "special_function", "{\"ar", /* .id = */ "123" } };
  2170. common_chat_msg msg2;
  2171. msg2.tool_calls = { { "special_function", "{\"arg1\": 1}", /* .id = */ "123" } };
  2172. common_chat_msg_diff diff01;
  2173. diff01.tool_call_index = 0;
  2174. diff01.tool_call_delta.name = "special_function";
  2175. diff01.tool_call_delta.id = "123";
  2176. diff01.tool_call_delta.arguments = "{\"ar";
  2177. assert_equals(
  2178. {diff01},
  2179. common_chat_msg_diff::compute_diffs(msg0, msg1));
  2180. common_chat_msg_diff diff12;
  2181. diff12.tool_call_index = 0;
  2182. // Note: neither id nor name change here.
  2183. diff12.tool_call_delta.arguments = "g1\": 1}";
  2184. assert_equals(
  2185. {diff12},
  2186. common_chat_msg_diff::compute_diffs(msg1, msg2));
  2187. }
  2188. {
  2189. common_chat_msg msg0;
  2190. common_chat_msg msg2;
  2191. msg2.tool_calls = {
  2192. { "f1", "{\"arg1\": 1}", /* .id = */ "123" },
  2193. { "f2", "{\"arg2\": 2}", /* .id = */ "222" },
  2194. };
  2195. common_chat_msg_diff diff1;
  2196. diff1.tool_call_index = 0;
  2197. diff1.tool_call_delta.name = "f1";
  2198. diff1.tool_call_delta.id = "123";
  2199. diff1.tool_call_delta.arguments = "{\"arg1\": 1}";
  2200. common_chat_msg_diff diff2;
  2201. diff2.tool_call_index = 1;
  2202. diff2.tool_call_delta.name = "f2";
  2203. diff2.tool_call_delta.id = "222";
  2204. diff2.tool_call_delta.arguments = "{\"arg2\": 2}";
  2205. assert_equals(
  2206. {diff1, diff2},
  2207. common_chat_msg_diff::compute_diffs(msg0, msg2));
  2208. }
  2209. }
  2210. int main(int argc, char ** argv) {
  2211. common_log_set_verbosity_thold(999);
  2212. // try {
  2213. #ifndef _WIN32
  2214. if (argc > 1) {
  2215. common_chat_templates_inputs inputs;
  2216. common_chat_msg msg;
  2217. msg.role = "user";
  2218. msg.content = "Hey";
  2219. inputs.messages = {msg};
  2220. inputs.tools = { special_function_tool };
  2221. std::cout << "| Template | Format |\n";
  2222. std::cout << "|----------|--------|\n";
  2223. for (int i = 1; i < argc; i++) {
  2224. try {
  2225. std::string path = argv[i];
  2226. if (path.rfind(".jinja") != path.size() - 6) {
  2227. std::cerr << "Skipping non-jinja file: " << path << '\n';
  2228. continue;
  2229. }
  2230. auto tmpls = read_templates(path);
  2231. auto parts = string_split(path, "/");
  2232. auto name = parts[parts.size() - 1];
  2233. auto format = common_chat_format_name(common_chat_templates_apply(tmpls.get(), inputs).format);
  2234. std::cout << "| " << name << " | " << format << " |\n";
  2235. } catch (const std::exception & e) {
  2236. std::cerr << "Failed to process " << argv[i] << ": " << e.what() << '\n';
  2237. }
  2238. }
  2239. } else
  2240. #endif
  2241. {
  2242. test_msg_diffs_compute();
  2243. test_msgs_oaicompat_json_conversion();
  2244. test_tools_oaicompat_json_conversion();
  2245. test_template_output_parsers();
  2246. std::cout << "\n[chat] All tests passed!" << '\n';
  2247. }
  2248. return 0;
  2249. // } catch (const std::exception & e) {
  2250. // std::cerr << "Error: " << e.what() << '\n';
  2251. // return 1;
  2252. // }
  2253. }