chat-template.hpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. if (full.find(prefix) != 0) {
  226. if (prefix.rfind(eos_token_) == prefix.size() - eos_token_.size()) {
  227. prefix = prefix.substr(0, prefix.size() - eos_token_.size());
  228. }
  229. }
  230. if (full.find(prefix) != 0) {
  231. fprintf(stderr, "Failed to infer a tool call example (possible template bug)\n");
  232. }
  233. tool_call_example_ = full.substr(prefix.size());
  234. }
  235. } catch (const std::exception & e) {
  236. fprintf(stderr, "Failed to generate tool call example: %s\n", e.what());
  237. }
  238. }
  239. const std::string & source() const { return source_; }
  240. const std::string & bos_token() const { return bos_token_; }
  241. const std::string & eos_token() const { return eos_token_; }
  242. const chat_template_caps & original_caps() const { return caps_; }
  243. // Deprecated, please use the form with chat_template_inputs and chat_template_options
  244. std::string apply(
  245. const nlohmann::ordered_json & messages,
  246. const nlohmann::ordered_json & tools,
  247. bool add_generation_prompt,
  248. const nlohmann::ordered_json & extra_context = nlohmann::ordered_json(),
  249. bool apply_polyfills = true)
  250. {
  251. fprintf(stderr, "[%s] Deprecated!\n", __func__);
  252. chat_template_inputs inputs;
  253. inputs.messages = messages;
  254. inputs.tools = tools;
  255. inputs.add_generation_prompt = add_generation_prompt;
  256. inputs.extra_context = extra_context;
  257. inputs.now = std::chrono::system_clock::now();
  258. chat_template_options opts;
  259. opts.apply_polyfills = apply_polyfills;
  260. return apply(inputs, opts);
  261. }
  262. std::string apply(
  263. const chat_template_inputs & inputs,
  264. const chat_template_options & opts = chat_template_options()) const
  265. {
  266. json actual_messages;
  267. auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
  268. auto has_tool_calls = false;
  269. auto has_tool_responses = false;
  270. auto has_string_content = false;
  271. for (const auto & message : inputs.messages) {
  272. if (message.contains("tool_calls") && !message["tool_calls"].is_null()) {
  273. has_tool_calls = true;
  274. }
  275. if (message.contains("role") && message["role"] == "tool") {
  276. has_tool_responses = true;
  277. }
  278. if (message.contains("content") && message["content"].is_string()) {
  279. has_string_content = true;
  280. }
  281. }
  282. auto polyfill_system_role = opts.polyfill_system_role && !caps_.supports_system_role;
  283. auto polyfill_tools = opts.polyfill_tools && has_tools && !caps_.supports_tools;
  284. auto polyfill_tool_call_example = polyfill_tools && opts.polyfill_tool_call_examples;
  285. auto polyfill_tool_calls = opts.polyfill_tool_calls && has_tool_calls && !caps_.supports_tool_calls;
  286. auto polyfill_tool_responses = opts.polyfill_tool_responses && has_tool_responses && !caps_.supports_tool_responses;
  287. auto polyfill_object_arguments = opts.polyfill_object_arguments && has_tool_calls && caps_.requires_object_arguments;
  288. auto polyfill_typed_content = opts.polyfill_typed_content && has_string_content && caps_.requires_typed_content;
  289. auto needs_polyfills = opts.apply_polyfills && (false
  290. || polyfill_system_role
  291. || polyfill_tools
  292. || polyfill_tool_calls
  293. || polyfill_tool_responses
  294. || polyfill_object_arguments
  295. || polyfill_typed_content
  296. );
  297. if (needs_polyfills) {
  298. actual_messages = json::array();
  299. auto add_message = [&](const json & msg) {
  300. if (polyfill_typed_content && msg.contains("content") && !msg.at("content").is_null() && msg.at("content").is_string()) {
  301. actual_messages.push_back({
  302. {"role", msg.at("role")},
  303. {"content", {{
  304. {"type", "text"},
  305. {"text", msg.at("content")},
  306. }}},
  307. });
  308. } else {
  309. actual_messages.push_back(msg);
  310. }
  311. };
  312. std::string pending_system;
  313. auto flush_sys = [&]() {
  314. if (!pending_system.empty()) {
  315. add_message({
  316. {"role", "user"},
  317. {"content", pending_system},
  318. });
  319. pending_system.clear();
  320. }
  321. };
  322. json adjusted_messages;
  323. if (polyfill_tools) {
  324. adjusted_messages = add_system(inputs.messages,
  325. "You can call any of the following tools to satisfy the user's requests: " + minja::Value(inputs.tools).dump(2, /* to_json= */ true) +
  326. (!polyfill_tool_call_example || tool_call_example_.empty() ? "" : "\n\nExample tool call syntax:\n\n" + tool_call_example_));
  327. } else {
  328. adjusted_messages = inputs.messages;
  329. }
  330. for (const auto & message_ : adjusted_messages) {
  331. auto message = message_;
  332. if (!message.contains("role") || !message.contains("content")) {
  333. throw std::runtime_error("message must have 'role' and 'content' fields: " + message.dump());
  334. }
  335. std::string role = message.at("role");
  336. if (message.contains("tool_calls")) {
  337. if (polyfill_object_arguments || polyfill_tool_calls) {
  338. for (auto & tool_call : message.at("tool_calls")) {
  339. if (tool_call["type"] == "function") {
  340. auto & function = tool_call.at("function");
  341. auto & arguments = function.at("arguments");
  342. if (arguments.is_string()) {
  343. try {
  344. arguments = json::parse(arguments.get<std::string>());
  345. } catch (const std::exception & ecvt) {
  346. fprintf(stderr, "Failed to parse arguments: %s\n", ecvt.what());
  347. }
  348. }
  349. }
  350. }
  351. }
  352. if (polyfill_tool_calls) {
  353. auto content = message.at("content");
  354. auto tool_calls = json::array();
  355. for (const auto & tool_call : message.at("tool_calls")) {
  356. if (tool_call.at("type") != "function") {
  357. continue;
  358. }
  359. const auto & function = tool_call.at("function");
  360. auto tc = json {
  361. {"name", function.at("name")},
  362. {"arguments", function.at("arguments")},
  363. };
  364. if (tool_call.contains("id")) {
  365. tc["id"] = tool_call["id"];
  366. }
  367. tool_calls.push_back(tc);
  368. }
  369. auto obj = json {
  370. {"tool_calls", tool_calls},
  371. };
  372. if (!content.is_null() && content != "") {
  373. obj["content"] = content;
  374. }
  375. message["content"] = obj.dump(2);
  376. message.erase("tool_calls");
  377. }
  378. }
  379. if (polyfill_tool_responses && role == "tool") {
  380. message["role"] = "user";
  381. auto obj = json {
  382. {"tool_response", {
  383. {"content", message.at("content")},
  384. }},
  385. };
  386. if (message.contains("name")) {
  387. obj["tool_response"]["name"] = message.at("name");
  388. }
  389. if (message.contains("tool_call_id")) {
  390. obj["tool_response"]["tool_call_id"] = message.at("tool_call_id");
  391. }
  392. message["content"] = obj.dump(2);
  393. message.erase("name");
  394. }
  395. if (!message["content"].is_null() && polyfill_system_role) {
  396. std::string content = message.at("content");
  397. if (role == "system") {
  398. if (!pending_system.empty()) pending_system += "\n";
  399. pending_system += content;
  400. continue;
  401. } else {
  402. if (role == "user") {
  403. if (!pending_system.empty()) {
  404. message["content"] = pending_system + (content.empty() ? "" : "\n" + content);
  405. pending_system.clear();
  406. }
  407. } else {
  408. flush_sys();
  409. }
  410. }
  411. }
  412. add_message(message);
  413. }
  414. flush_sys();
  415. } else {
  416. actual_messages = inputs.messages;
  417. }
  418. auto context = minja::Context::make(json({
  419. {"messages", actual_messages},
  420. {"add_generation_prompt", inputs.add_generation_prompt},
  421. }));
  422. context->set("bos_token", opts.use_bos_token ? bos_token_ : "");
  423. context->set("eos_token", opts.use_eos_token ? eos_token_ : "");
  424. if (opts.define_strftime_now) {
  425. auto now = inputs.now;
  426. context->set("strftime_now", Value::callable([now](const std::shared_ptr<minja::Context> &, minja::ArgumentsValue & args) {
  427. args.expectArgs("strftime_now", {1, 1}, {0, 0});
  428. auto format = args.args[0].get<std::string>();
  429. auto time = std::chrono::system_clock::to_time_t(now);
  430. auto local_time = *std::localtime(&time);
  431. std::ostringstream ss;
  432. ss << std::put_time(&local_time, format.c_str());
  433. return ss.str();
  434. }));
  435. }
  436. if (!inputs.tools.is_null()) {
  437. context->set("tools", minja::Value(inputs.tools));
  438. }
  439. if (!inputs.extra_context.is_null()) {
  440. for (auto & kv : inputs.extra_context.items()) {
  441. context->set(kv.key(), minja::Value(kv.value()));
  442. }
  443. }
  444. auto ret = template_root_->render(context);
  445. // fprintf(stderr, "actual_messages: %s\n", actual_messages.dump(2).c_str());
  446. // fprintf(stderr, "apply: %s\n\n", ret.c_str());
  447. return ret;
  448. }
  449. static nlohmann::ordered_json add_system(const nlohmann::ordered_json & messages, const std::string & system_prompt) {
  450. json messages_with_system = messages;
  451. if (messages_with_system.size() > 0 && messages_with_system[0].at("role") == "system") {
  452. std::string existing_system = messages_with_system.at(0).at("content");
  453. messages_with_system[0] = json {
  454. {"role", "system"},
  455. {"content", existing_system + "\n\n" + system_prompt},
  456. };
  457. } else {
  458. messages_with_system.insert(messages_with_system.begin(), json {
  459. {"role", "system"},
  460. {"content", system_prompt},
  461. });
  462. }
  463. return messages_with_system;
  464. }
  465. };
  466. } // namespace minja