test-chat.cpp 101 KB

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