test-chat.cpp 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262
  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. auto tmpls = read_templates("models/templates/Apertus-8B-Instruct.jinja");
  1934. std::vector<std::string> end_tokens{ "<|assistant_end|>" };
  1935. assert_equals(COMMON_CHAT_FORMAT_APERTUS, common_chat_templates_apply(tmpls.get(), inputs_no_tools).format);
  1936. assert_equals(COMMON_CHAT_FORMAT_APERTUS, common_chat_templates_apply(tmpls.get(), inputs_tools).format);
  1937. // Test parsing regular content
  1938. assert_msg_equals(message_assist,
  1939. common_chat_parse(
  1940. "Hello, world!\nWhat's up?",
  1941. /* is_partial= */ false,
  1942. {COMMON_CHAT_FORMAT_APERTUS}));
  1943. // Test parsing content with thinking
  1944. assert_msg_equals(message_assist_thoughts,
  1945. common_chat_parse(
  1946. "<|inner_prefix|>I'm\nthinking<|inner_suffix|>Hello, world!\nWhat's up?",
  1947. /* is_partial= */ false,
  1948. {
  1949. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  1950. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK,
  1951. }));
  1952. // Test parsing tool calls
  1953. assert_msg_equals(message_assist_call,
  1954. common_chat_parse(
  1955. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  1956. /* is_partial= */ false,
  1957. {COMMON_CHAT_FORMAT_APERTUS}));
  1958. // Test parsing tool calls with thinking
  1959. assert_msg_equals(message_assist_call_thoughts,
  1960. common_chat_parse(
  1961. "<|inner_prefix|>I'm\nthinking<|inner_suffix|><|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  1962. /* is_partial= */ false,
  1963. {
  1964. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  1965. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1966. }));
  1967. // Test tool calls with extra content
  1968. assert_msg_equals(message_assist_call_content,
  1969. common_chat_parse(
  1970. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>Hello, world!\nWhat's up?",
  1971. /* is_partial= */ false,
  1972. {COMMON_CHAT_FORMAT_APERTUS}
  1973. ));
  1974. // Test tool calls with extra content AND thinking
  1975. assert_msg_equals(message_assist_call_thoughts_content,
  1976. common_chat_parse(
  1977. "<|inner_prefix|>I'm\nthinking<|inner_suffix|><|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>Hello, world!\nWhat's up?",
  1978. /* is_partial= */ false,
  1979. {
  1980. /* .format = */ COMMON_CHAT_FORMAT_APERTUS,
  1981. /* .reasoning_format = */ COMMON_REASONING_FORMAT_DEEPSEEK
  1982. }));
  1983. // Test template generation for regular content
  1984. test_templates(tmpls.get(), end_tokens, message_assist, tools,
  1985. "Hello, world!\nWhat's up?",
  1986. /* expect_grammar_triggered= */ false);
  1987. // Test template generation for tool calls
  1988. test_templates(tmpls.get(), end_tokens, message_assist_call, tools,
  1989. "<|tools_prefix|>[{\"special_function\": {\"arg1\": 1}}]<|tools_suffix|>",
  1990. /* expect_grammar_triggered= */ true
  1991. );
  1992. assert_equals(true, common_chat_templates_support_enable_thinking(tmpls.get()));
  1993. }
  1994. }
  1995. static void test_msg_diffs_compute() {
  1996. printf("[%s]\n", __func__);
  1997. {
  1998. common_chat_msg msg1;
  1999. common_chat_msg msg2;
  2000. msg2.content = "Hello, world!";
  2001. common_chat_msg_diff diff;
  2002. diff.content_delta = "Hello, world!";
  2003. assert_equals(
  2004. {diff},
  2005. common_chat_msg_diff::compute_diffs(msg1, msg2));
  2006. }
  2007. {
  2008. common_chat_msg msg1;
  2009. msg1.content = "Hello,";
  2010. common_chat_msg msg2;
  2011. msg2.content = "Hello, world!";
  2012. common_chat_msg_diff diff;
  2013. diff.content_delta = " world!";
  2014. assert_equals(
  2015. {diff},
  2016. common_chat_msg_diff::compute_diffs(msg1, msg2));
  2017. }
  2018. {
  2019. common_chat_msg msg0;
  2020. common_chat_msg msg1;
  2021. msg1.tool_calls = { { "special_function", "{\"ar", /* .id = */ "123" } };
  2022. common_chat_msg msg2;
  2023. msg2.tool_calls = { { "special_function", "{\"arg1\": 1}", /* .id = */ "123" } };
  2024. common_chat_msg_diff diff01;
  2025. diff01.tool_call_index = 0;
  2026. diff01.tool_call_delta.name = "special_function";
  2027. diff01.tool_call_delta.id = "123";
  2028. diff01.tool_call_delta.arguments = "{\"ar";
  2029. assert_equals(
  2030. {diff01},
  2031. common_chat_msg_diff::compute_diffs(msg0, msg1));
  2032. common_chat_msg_diff diff12;
  2033. diff12.tool_call_index = 0;
  2034. // Note: neither id nor name change here.
  2035. diff12.tool_call_delta.arguments = "g1\": 1}";
  2036. assert_equals(
  2037. {diff12},
  2038. common_chat_msg_diff::compute_diffs(msg1, msg2));
  2039. }
  2040. {
  2041. common_chat_msg msg0;
  2042. common_chat_msg msg2;
  2043. msg2.tool_calls = {
  2044. { "f1", "{\"arg1\": 1}", /* .id = */ "123" },
  2045. { "f2", "{\"arg2\": 2}", /* .id = */ "222" },
  2046. };
  2047. common_chat_msg_diff diff1;
  2048. diff1.tool_call_index = 0;
  2049. diff1.tool_call_delta.name = "f1";
  2050. diff1.tool_call_delta.id = "123";
  2051. diff1.tool_call_delta.arguments = "{\"arg1\": 1}";
  2052. common_chat_msg_diff diff2;
  2053. diff2.tool_call_index = 1;
  2054. diff2.tool_call_delta.name = "f2";
  2055. diff2.tool_call_delta.id = "222";
  2056. diff2.tool_call_delta.arguments = "{\"arg2\": 2}";
  2057. assert_equals(
  2058. {diff1, diff2},
  2059. common_chat_msg_diff::compute_diffs(msg0, msg2));
  2060. }
  2061. }
  2062. int main(int argc, char ** argv) {
  2063. common_log_set_verbosity_thold(999);
  2064. // try {
  2065. #ifndef _WIN32
  2066. if (argc > 1) {
  2067. common_chat_templates_inputs inputs;
  2068. common_chat_msg msg;
  2069. msg.role = "user";
  2070. msg.content = "Hey";
  2071. inputs.messages = {msg};
  2072. inputs.tools = { special_function_tool };
  2073. std::cout << "| Template | Format |\n";
  2074. std::cout << "|----------|--------|\n";
  2075. for (int i = 1; i < argc; i++) {
  2076. try {
  2077. std::string path = argv[i];
  2078. if (path.rfind(".jinja") != path.size() - 6) {
  2079. std::cerr << "Skipping non-jinja file: " << path << '\n';
  2080. continue;
  2081. }
  2082. auto tmpls = read_templates(path);
  2083. auto parts = string_split(path, "/");
  2084. auto name = parts[parts.size() - 1];
  2085. auto format = common_chat_format_name(common_chat_templates_apply(tmpls.get(), inputs).format);
  2086. std::cout << "| " << name << " | " << format << " |\n";
  2087. } catch (const std::exception & e) {
  2088. std::cerr << "Failed to process " << argv[i] << ": " << e.what() << '\n';
  2089. }
  2090. }
  2091. } else
  2092. #endif
  2093. {
  2094. test_msg_diffs_compute();
  2095. test_msgs_oaicompat_json_conversion();
  2096. test_tools_oaicompat_json_conversion();
  2097. test_template_output_parsers();
  2098. std::cout << "\n[chat] All tests passed!" << '\n';
  2099. }
  2100. return 0;
  2101. // } catch (const std::exception & e) {
  2102. // std::cerr << "Error: " << e.what() << '\n';
  2103. // return 1;
  2104. // }
  2105. }