1
0

test-chat.cpp 105 KB

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