chat-template.hpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*
  2. Copyright 2024 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. // SPDX-License-Identifier: MIT
  8. #pragma once
  9. #include "minja.hpp"
  10. #include <chrono>
  11. #include <cstddef>
  12. #include <cstdio>
  13. #include <ctime>
  14. #include <exception>
  15. #include <iomanip>
  16. #include <memory>
  17. #include <sstream>
  18. #include <stdexcept>
  19. #include <string>
  20. #include <vector>
  21. #include <nlohmann/json.hpp>
  22. using json = nlohmann::ordered_json;
  23. namespace minja {
  24. struct chat_template_caps {
  25. bool supports_tools = false;
  26. bool supports_tool_calls = false;
  27. bool supports_tool_responses = false;
  28. bool supports_system_role = false;
  29. bool supports_parallel_tool_calls = false;
  30. bool supports_tool_call_id = false;
  31. // meta-llama/Llama-3.1-8B-Instruct expects arguments to be an object.
  32. // Most other templates (and OpenAI's API) expect the arguments object to be stringified.
  33. bool requires_object_arguments = false;
  34. // CohereForAI/c4ai-command-r-plus simple variant
  35. bool requires_non_null_content = false;
  36. // MiniMaxAI/MiniMax-Text-01 special
  37. bool requires_typed_content = false;
  38. };
  39. struct chat_template_inputs {
  40. nlohmann::ordered_json messages;
  41. nlohmann::ordered_json tools;
  42. bool add_generation_prompt = true;
  43. nlohmann::ordered_json extra_context;
  44. std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
  45. };
  46. struct chat_template_options {
  47. bool apply_polyfills = true;
  48. bool use_bos_token = true;
  49. bool use_eos_token = true;
  50. bool define_strftime_now = true;
  51. bool polyfill_tools = true;
  52. bool polyfill_tool_call_examples = true;
  53. bool polyfill_tool_calls = true;
  54. bool polyfill_tool_responses = true;
  55. bool polyfill_system_role = true;
  56. bool polyfill_object_arguments = true;
  57. bool polyfill_typed_content = true;
  58. };
  59. class chat_template {
  60. private:
  61. chat_template_caps caps_;
  62. std::string source_;
  63. std::string bos_token_;
  64. std::string eos_token_;
  65. std::shared_ptr<minja::TemplateNode> template_root_;
  66. std::string tool_call_example_;
  67. std::string try_raw_render(
  68. const nlohmann::ordered_json & messages,
  69. const nlohmann::ordered_json & tools,
  70. bool add_generation_prompt,
  71. const nlohmann::ordered_json & extra_context = nlohmann::ordered_json()) const
  72. {
  73. try {
  74. chat_template_inputs inputs;
  75. inputs.messages = messages;
  76. inputs.tools = tools;
  77. inputs.add_generation_prompt = add_generation_prompt;
  78. inputs.extra_context = extra_context;
  79. // Use fixed date for tests
  80. inputs.now = std::chrono::system_clock::from_time_t(0);
  81. chat_template_options opts;
  82. opts.apply_polyfills = false;
  83. auto prompt = apply(inputs, opts);
  84. // fprintf(stderr, "try_raw_render: %s\n", prompt.c_str());
  85. return prompt;
  86. } catch (const std::exception & e) {
  87. // fprintf(stderr, "try_raw_render error: %s\n", e.what());
  88. return "";
  89. }
  90. }
  91. public:
  92. chat_template(const std::string & source, const std::string & bos_token, const std::string & eos_token)
  93. : source_(source), bos_token_(bos_token), eos_token_(eos_token)
  94. {
  95. template_root_ = minja::Parser::parse(source_, {
  96. /* .trim_blocks = */ true,
  97. /* .lstrip_blocks = */ true,
  98. /* .keep_trailing_newline = */ false,
  99. });
  100. auto contains = [](const std::string & haystack, const std::string & needle) {
  101. return haystack.find(needle) != std::string::npos;
  102. };
  103. const std::string user_needle = "<User Needle>";
  104. const std::string sys_needle = "<System Needle>";
  105. const json dummy_str_user_msg = {{"role", "user"}, {"content", user_needle}};
  106. const json dummy_typed_user_msg = {{"role", "user"}, {"content", json::array({{{"type", "text"}, {"text", user_needle}}})}};
  107. caps_.requires_typed_content =
  108. !contains(try_raw_render(json::array({dummy_str_user_msg}), {}, false), user_needle)
  109. && contains(try_raw_render(json::array({dummy_typed_user_msg}), {}, false), user_needle);
  110. const auto dummy_user_msg = caps_.requires_typed_content
  111. ? dummy_typed_user_msg
  112. : dummy_str_user_msg;
  113. const json needle_system_msg = {
  114. {"role", "system"},
  115. {"content", caps_.requires_typed_content ? json::array({{{"type", "text"}, {"text", sys_needle}}}) : json(sys_needle)},
  116. };
  117. caps_.supports_system_role = contains(try_raw_render({needle_system_msg, dummy_user_msg,}, {}, false), sys_needle);
  118. auto out = try_raw_render(json::array({
  119. dummy_user_msg
  120. }), json::array({
  121. {
  122. {"name", "some_tool"},
  123. {"type", "function"},
  124. {"function", {
  125. {"name", "some_tool"},
  126. {"description", "Some tool."},
  127. {"parameters", {
  128. {"type", "object"},
  129. {"properties", {
  130. {"arg", {
  131. {"type", "string"},
  132. {"description", "Some argument."},
  133. }},
  134. }},
  135. {"required", json::array({ "arg" })},
  136. }},
  137. }},
  138. },
  139. }), false);
  140. caps_.supports_tools = contains(out, "some_tool");
  141. auto make_tool_calls_msg = [&](const json & tool_calls) {
  142. return json {
  143. {"role", "assistant"},
  144. {"content", nullptr},
  145. {"tool_calls", tool_calls},
  146. };
  147. };
  148. auto make_tool_call = [](const std::string & tool_name, const json & arguments) {
  149. return json {
  150. {"id", "call_1___"},
  151. {"type", "function"},
  152. {"function", {
  153. {"arguments", arguments},
  154. {"name", tool_name},
  155. }},
  156. };
  157. };
  158. const json dummy_args_obj {{"argument_needle", "print('Hello, World!')"}};
  159. // Note: the arguments are rendered in both cases, but may be double-escaped, which we don't want.
  160. out = try_raw_render(json::array({
  161. dummy_user_msg,
  162. make_tool_calls_msg(json::array({make_tool_call("ipython", dummy_args_obj.dump())})),
  163. }), {}, false);
  164. auto tool_call_renders_str_arguments = contains(out, "\"argument_needle\":") || contains(out, "'argument_needle':");
  165. out = try_raw_render(json::array({
  166. dummy_user_msg,
  167. make_tool_calls_msg(json::array({make_tool_call("ipython", dummy_args_obj)})),
  168. }), {}, false);
  169. auto tool_call_renders_obj_arguments = contains(out, "\"argument_needle\":") || contains(out, "'argument_needle':");
  170. caps_.supports_tool_calls = tool_call_renders_str_arguments || tool_call_renders_obj_arguments;
  171. caps_.requires_object_arguments = !tool_call_renders_str_arguments && tool_call_renders_obj_arguments;
  172. auto out_empty = try_raw_render(json::array({dummy_user_msg, {{"role", "assistant"}, {"content", ""}}}), {}, false);
  173. auto out_null = try_raw_render(json::array({dummy_user_msg, {{"role", "assistant"}, {"content", nullptr}}}), {}, false);
  174. caps_.requires_non_null_content = contains(out_empty, user_needle) && !contains(out_null, user_needle);
  175. if (caps_.supports_tool_calls) {
  176. auto dummy_args = caps_.requires_object_arguments ? dummy_args_obj : json(dummy_args_obj.dump());
  177. auto tc1 = make_tool_call("test_tool1", dummy_args);
  178. auto tc2 = make_tool_call("test_tool2", dummy_args);
  179. auto out = try_raw_render(json::array({
  180. dummy_user_msg,
  181. make_tool_calls_msg(json::array({tc1, tc2})),
  182. }), {}, false);
  183. caps_.supports_parallel_tool_calls = contains(out, "test_tool1") && contains(out, "test_tool2");
  184. out = try_raw_render(json::array({
  185. dummy_user_msg,
  186. make_tool_calls_msg(json::array({tc1})),
  187. {
  188. {"role", "tool"},
  189. {"name", "test_tool1"},
  190. {"content", "Some response!"},
  191. {"tool_call_id", "call_911_"},
  192. }
  193. }), {}, false);
  194. caps_.supports_tool_responses = contains(out, "Some response!");
  195. caps_.supports_tool_call_id = contains(out, "call_911_");
  196. }
  197. try {
  198. if (!caps_.supports_tools) {
  199. const json user_msg {
  200. {"role", "user"},
  201. {"content", "Hey"},
  202. };
  203. const json args {
  204. {"arg1", "some_value"},
  205. };
  206. const json tool_call_msg {
  207. {"role", "assistant"},
  208. {"content", nullptr},
  209. {"tool_calls", json::array({
  210. {
  211. // TODO: detect if requires numerical id or fixed length == 6 like Nemo
  212. {"id", "call_1___"},
  213. {"type", "function"},
  214. {"function", {
  215. {"name", "tool_name"},
  216. {"arguments", (caps_.requires_object_arguments ? args : json(minja::Value(args).dump(-1, /* to_json= */ true)))},
  217. }},
  218. },
  219. })},
  220. };
  221. std::string prefix, full;
  222. {
  223. chat_template_inputs inputs;
  224. inputs.messages = json::array({user_msg});
  225. inputs.add_generation_prompt = true;
  226. prefix = apply(inputs);
  227. }
  228. {
  229. chat_template_inputs inputs;
  230. inputs.messages = json::array({user_msg, tool_call_msg});
  231. inputs.add_generation_prompt = false;
  232. full = apply(inputs);
  233. }
  234. auto eos_pos_last = full.rfind(eos_token_);
  235. if (eos_pos_last == prefix.size() - eos_token_.size() ||
  236. (full[full.size() - 1] == '\n' && (eos_pos_last == full.size() - eos_token_.size() - 1))) {
  237. full = full.substr(0, eos_pos_last);
  238. }
  239. size_t common_prefix_length = 0;
  240. for (size_t i = 0; i < prefix.size() && i < full.size(); ++i) {
  241. if (prefix[i] != full[i]) {
  242. break;
  243. }
  244. if (prefix[i] == '<') {
  245. // DeepSeek R1's template (as of 20250209) adds a trailing <think> if add_generation_prompt,
  246. // but it removes thinking tags for past messages.
  247. // The prefix and full strings diverge at <think> vs. <|tool▁calls▁begin|>, we avoid consuming the leading <.
  248. continue;
  249. }
  250. common_prefix_length = i + 1;
  251. }
  252. auto example = full.substr(common_prefix_length);
  253. if (example.find("tool_name") == std::string::npos && example.find("some_value") == std::string::npos) {
  254. fprintf(stderr, "Failed to infer a tool call example (possible template bug)\n");
  255. } else {
  256. tool_call_example_ = example;
  257. }
  258. }
  259. } catch (const std::exception & e) {
  260. fprintf(stderr, "Failed to generate tool call example: %s\n", e.what());
  261. }
  262. }
  263. const std::string & source() const { return source_; }
  264. const std::string & bos_token() const { return bos_token_; }
  265. const std::string & eos_token() const { return eos_token_; }
  266. const chat_template_caps & original_caps() const { return caps_; }
  267. // Deprecated, please use the form with chat_template_inputs and chat_template_options
  268. std::string apply(
  269. const nlohmann::ordered_json & messages,
  270. const nlohmann::ordered_json & tools,
  271. bool add_generation_prompt,
  272. const nlohmann::ordered_json & extra_context = nlohmann::ordered_json(),
  273. bool apply_polyfills = true)
  274. {
  275. fprintf(stderr, "[%s] Deprecated!\n", __func__);
  276. chat_template_inputs inputs;
  277. inputs.messages = messages;
  278. inputs.tools = tools;
  279. inputs.add_generation_prompt = add_generation_prompt;
  280. inputs.extra_context = extra_context;
  281. inputs.now = std::chrono::system_clock::now();
  282. chat_template_options opts;
  283. opts.apply_polyfills = apply_polyfills;
  284. return apply(inputs, opts);
  285. }
  286. std::string apply(
  287. const chat_template_inputs & inputs,
  288. const chat_template_options & opts = chat_template_options()) const
  289. {
  290. json actual_messages;
  291. auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
  292. auto has_tool_calls = false;
  293. auto has_tool_responses = false;
  294. auto has_string_content = false;
  295. for (const auto & message : inputs.messages) {
  296. if (message.contains("tool_calls") && !message["tool_calls"].is_null()) {
  297. has_tool_calls = true;
  298. }
  299. if (message.contains("role") && message["role"] == "tool") {
  300. has_tool_responses = true;
  301. }
  302. if (message.contains("content") && message["content"].is_string()) {
  303. has_string_content = true;
  304. }
  305. }
  306. auto polyfill_system_role = opts.polyfill_system_role && !caps_.supports_system_role;
  307. auto polyfill_tools = opts.polyfill_tools && has_tools && !caps_.supports_tools;
  308. auto polyfill_tool_call_example = polyfill_tools && opts.polyfill_tool_call_examples;
  309. auto polyfill_tool_calls = opts.polyfill_tool_calls && has_tool_calls && !caps_.supports_tool_calls;
  310. auto polyfill_tool_responses = opts.polyfill_tool_responses && has_tool_responses && !caps_.supports_tool_responses;
  311. auto polyfill_object_arguments = opts.polyfill_object_arguments && has_tool_calls && caps_.requires_object_arguments;
  312. auto polyfill_typed_content = opts.polyfill_typed_content && has_string_content && caps_.requires_typed_content;
  313. auto needs_polyfills = opts.apply_polyfills && (false
  314. || polyfill_system_role
  315. || polyfill_tools
  316. || polyfill_tool_calls
  317. || polyfill_tool_responses
  318. || polyfill_object_arguments
  319. || polyfill_typed_content
  320. );
  321. if (needs_polyfills) {
  322. actual_messages = json::array();
  323. auto add_message = [&](const json & msg) {
  324. if (polyfill_typed_content && msg.contains("content") && !msg.at("content").is_null() && msg.at("content").is_string()) {
  325. actual_messages.push_back({
  326. {"role", msg.at("role")},
  327. {"content", {{
  328. {"type", "text"},
  329. {"text", msg.at("content")},
  330. }}},
  331. });
  332. } else {
  333. actual_messages.push_back(msg);
  334. }
  335. };
  336. std::string pending_system;
  337. auto flush_sys = [&]() {
  338. if (!pending_system.empty()) {
  339. add_message({
  340. {"role", "user"},
  341. {"content", pending_system},
  342. });
  343. pending_system.clear();
  344. }
  345. };
  346. json adjusted_messages;
  347. if (polyfill_tools) {
  348. adjusted_messages = add_system(inputs.messages,
  349. "You can call any of the following tools to satisfy the user's requests: " + minja::Value(inputs.tools).dump(2, /* to_json= */ true) +
  350. (!polyfill_tool_call_example || tool_call_example_.empty() ? "" : "\n\nExample tool call syntax:\n\n" + tool_call_example_ + "\n\n"));
  351. } else {
  352. adjusted_messages = inputs.messages;
  353. }
  354. for (const auto & message_ : adjusted_messages) {
  355. auto message = message_;
  356. if (!message.contains("role") || (!message.contains("content") && !message.contains("tool_calls"))) {
  357. throw std::runtime_error("message must have 'role' and one of 'content' or 'tool_calls' fields: " + message.dump());
  358. }
  359. std::string role = message.at("role");
  360. if (message.contains("tool_calls")) {
  361. if (polyfill_object_arguments || polyfill_tool_calls) {
  362. for (auto & tool_call : message.at("tool_calls")) {
  363. if (tool_call["type"] == "function") {
  364. auto & function = tool_call.at("function");
  365. auto & arguments = function.at("arguments");
  366. if (arguments.is_string()) {
  367. try {
  368. arguments = json::parse(arguments.get<std::string>());
  369. } catch (const std::exception & ecvt) {
  370. fprintf(stderr, "Failed to parse arguments: %s\n", ecvt.what());
  371. }
  372. }
  373. }
  374. }
  375. }
  376. if (polyfill_tool_calls) {
  377. auto tool_calls = json::array();
  378. for (const auto & tool_call : message.at("tool_calls")) {
  379. if (tool_call.at("type") != "function") {
  380. continue;
  381. }
  382. const auto & function = tool_call.at("function");
  383. auto tc = json {
  384. {"name", function.at("name")},
  385. {"arguments", function.at("arguments")},
  386. };
  387. if (tool_call.contains("id")) {
  388. tc["id"] = tool_call["id"];
  389. }
  390. tool_calls.push_back(tc);
  391. }
  392. auto obj = json {
  393. {"tool_calls", tool_calls},
  394. };
  395. if (message.contains("content")) {
  396. auto content = message.at("content");
  397. if (!content.is_null() && !content.empty()) {
  398. obj["content"] = content;
  399. }
  400. }
  401. message["content"] = obj.dump(2);
  402. message.erase("tool_calls");
  403. }
  404. }
  405. if (polyfill_tool_responses && role == "tool") {
  406. message["role"] = "user";
  407. auto obj = json {
  408. {"tool_response", json::object()},
  409. };
  410. if (message.contains("name")) {
  411. obj["tool_response"]["tool"] = message.at("name");
  412. }
  413. obj["tool_response"]["content"] = message.at("content");
  414. if (message.contains("tool_call_id")) {
  415. obj["tool_response"]["tool_call_id"] = message.at("tool_call_id");
  416. }
  417. message["content"] = obj.dump(2);
  418. message.erase("name");
  419. }
  420. if (!message["content"].is_null() && polyfill_system_role) {
  421. std::string content = message.at("content");
  422. if (role == "system") {
  423. if (!pending_system.empty()) pending_system += "\n";
  424. pending_system += content;
  425. continue;
  426. } else {
  427. if (role == "user") {
  428. if (!pending_system.empty()) {
  429. message["content"] = pending_system + (content.empty() ? "" : "\n" + content);
  430. pending_system.clear();
  431. }
  432. } else {
  433. flush_sys();
  434. }
  435. }
  436. }
  437. add_message(message);
  438. }
  439. flush_sys();
  440. } else {
  441. actual_messages = inputs.messages;
  442. }
  443. auto context = minja::Context::make(json({
  444. {"messages", actual_messages},
  445. {"add_generation_prompt", inputs.add_generation_prompt},
  446. }));
  447. context->set("bos_token", opts.use_bos_token ? bos_token_ : "");
  448. context->set("eos_token", opts.use_eos_token ? eos_token_ : "");
  449. if (opts.define_strftime_now) {
  450. auto now = inputs.now;
  451. context->set("strftime_now", Value::callable([now](const std::shared_ptr<minja::Context> &, minja::ArgumentsValue & args) {
  452. args.expectArgs("strftime_now", {1, 1}, {0, 0});
  453. auto format = args.args[0].get<std::string>();
  454. auto time = std::chrono::system_clock::to_time_t(now);
  455. auto local_time = *std::localtime(&time);
  456. std::ostringstream ss;
  457. ss << std::put_time(&local_time, format.c_str());
  458. return ss.str();
  459. }));
  460. }
  461. if (!inputs.tools.is_null()) {
  462. context->set("tools", minja::Value(inputs.tools));
  463. }
  464. if (!inputs.extra_context.is_null()) {
  465. for (auto & kv : inputs.extra_context.items()) {
  466. context->set(kv.key(), minja::Value(kv.value()));
  467. }
  468. }
  469. auto ret = template_root_->render(context);
  470. // fprintf(stderr, "actual_messages: %s\n", actual_messages.dump(2).c_str());
  471. // fprintf(stderr, "apply: %s\n\n", ret.c_str());
  472. return ret;
  473. }
  474. static nlohmann::ordered_json add_system(const nlohmann::ordered_json & messages, const std::string & system_prompt) {
  475. json messages_with_system = messages;
  476. if (!messages_with_system.empty() && messages_with_system[0].at("role") == "system") {
  477. std::string existing_system = messages_with_system.at(0).at("content");
  478. messages_with_system[0] = json {
  479. {"role", "system"},
  480. {"content", existing_system + "\n\n" + system_prompt},
  481. };
  482. } else {
  483. messages_with_system.insert(messages_with_system.begin(), json {
  484. {"role", "system"},
  485. {"content", system_prompt},
  486. });
  487. }
  488. return messages_with_system;
  489. }
  490. };
  491. } // namespace minja