chat-template.hpp 22 KB

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