chat-template.hpp 23 KB

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