chat-template.hpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. class chat_template {
  16. public:
  17. private:
  18. bool supports_tools_ = true;
  19. // Meta-Llama-3.1-8B-Instruct's template expects arguments to be an object.
  20. // Most other templates (and OpenAI's API) expect the arguments object to be stringified.
  21. bool requires_object_arguments_ = false;
  22. bool supports_system_role_ = true;
  23. bool supports_parallel_tool_calls_ = false;
  24. std::string source_;
  25. std::string bos_token_;
  26. std::string eos_token_;
  27. std::shared_ptr<minja::TemplateNode> template_root_;
  28. std::string try_render(
  29. const nlohmann::ordered_json & messages,
  30. const nlohmann::ordered_json & tools,
  31. bool add_generation_prompt,
  32. const nlohmann::ordered_json & extra_context = nlohmann::ordered_json()) const
  33. {
  34. try {
  35. auto prompt = apply(messages, tools, add_generation_prompt, extra_context);
  36. // fprintf(stderr, "Prompt: %s\n", prompt.c_str());
  37. return prompt;
  38. } catch (const std::exception & e) {
  39. // fprintf(stderr, "Error: %s\n", e.what());
  40. return "";
  41. }
  42. }
  43. public:
  44. chat_template(const std::string & source, const std::string & bos_token, const std::string & eos_token)
  45. : source_(source), bos_token_(bos_token), eos_token_(eos_token)
  46. {
  47. template_root_ = minja::Parser::parse(source_, {
  48. /* .trim_blocks = */ true,
  49. /* .lstrip_blocks = */ true,
  50. /* .keep_trailing_newline = */ false,
  51. });
  52. supports_tools_ = source.find("tools") != std::string::npos;
  53. auto renders_string_arguments =
  54. try_render({
  55. {
  56. {"role", "user"},
  57. {"content", "Hey"}
  58. },
  59. {
  60. {"role", "assistant"},
  61. {"tool_calls", json::array({
  62. {
  63. {"id", "call_1___"},
  64. {"type", "function"},
  65. {"function", {
  66. {"arguments", "{\"code\": \"print('Hello, World!')\"}"},
  67. {"name", "ipython"},
  68. }},
  69. },
  70. })},
  71. }
  72. }, {}, false).find("{\"code\": \"print") != std::string::npos;
  73. if (!renders_string_arguments) {
  74. auto renders_object_arguments =
  75. try_render({
  76. {
  77. {"role", "user"},
  78. {"content", "Hey"}
  79. },
  80. {
  81. {"role", "assistant"},
  82. {"tool_calls", json::array({
  83. {
  84. {"id", "call_1___"},
  85. {"type", "function"},
  86. {"function", {
  87. {"arguments", {
  88. {"code", "print('Hello, World!')"},
  89. }},
  90. {"name", "ipython"},
  91. }},
  92. },
  93. })},
  94. }
  95. }, {}, false).find("{\"code\": \"print") != std::string::npos;
  96. requires_object_arguments_ = renders_object_arguments;
  97. }
  98. supports_parallel_tool_calls_ = source.find("tool_call_id") != std::string::npos;
  99. supports_system_role_ = try_render({
  100. {{"role", "system"}, {"content", "<System Needle>"}},
  101. {{"role", "user"}, {"content", "Hey"}}
  102. }, {}, false).find("<System Needle>") != std::string::npos;
  103. }
  104. const std::string & source() const { return source_; }
  105. const std::string & bos_token() const { return bos_token_; }
  106. const std::string & eos_token() const { return eos_token_; }
  107. bool supports_tools() const { return supports_tools_; }
  108. bool supports_parallel_tool_calls() const { return supports_parallel_tool_calls_; }
  109. std::string apply(
  110. const nlohmann::ordered_json & messages,
  111. const nlohmann::ordered_json & tools,
  112. bool add_generation_prompt,
  113. const nlohmann::ordered_json & extra_context = nlohmann::ordered_json()) const
  114. {
  115. json actual_messages;
  116. // First, "fix" messages so they have a chance to be rendered correctly by the template
  117. if (requires_object_arguments_ || !supports_system_role_ || !supports_tools_) {
  118. actual_messages = json::array();
  119. std::string pending_system;
  120. auto flush_sys = [&]() {
  121. if (!pending_system.empty()) {
  122. actual_messages.push_back({
  123. {"role", "user"},
  124. {"content", pending_system},
  125. });
  126. pending_system.clear();
  127. }
  128. };
  129. for (const auto & message_ : messages) {
  130. auto message = message_;
  131. if (!message.contains("role") || !message.contains("content")) {
  132. throw std::runtime_error("message must have 'role' and 'content' fields: " + message.dump());
  133. }
  134. std::string role = message.at("role");
  135. if (message.contains("tool_calls")) {
  136. if (requires_object_arguments_ || !supports_tools_) {
  137. for (auto & tool_call : message.at("tool_calls")) {
  138. if (tool_call["type"] == "function") {
  139. auto & function = tool_call.at("function");
  140. std::string arguments = function.at("arguments");
  141. function["arguments"] = json::parse(arguments);
  142. }
  143. }
  144. }
  145. if (!supports_tools_) {
  146. auto content = message.at("content");
  147. auto tool_calls = json::array();
  148. for (const auto & tool_call : message.at("tool_calls")) {
  149. if (tool_call.at("type") != "function") {
  150. continue;
  151. }
  152. const auto & function = tool_call.at("function");
  153. auto tc = json {
  154. {"name", function.at("name")},
  155. {"arguments", function.at("arguments")},
  156. };
  157. if (tool_call.contains("id")) {
  158. tc["id"] = tool_call["id"];
  159. }
  160. tool_calls.push_back(tc);
  161. }
  162. auto obj = json {
  163. {"tool_calls", tool_calls},
  164. };
  165. if (!content.is_null() && content != "") {
  166. obj["content"] = content;
  167. }
  168. message["content"] = obj.dump(2);
  169. message.erase("tool_calls");
  170. }
  171. }
  172. if (!supports_tools_ && role == "tool") {
  173. message["role"] = "user";
  174. auto obj = json {
  175. {"tool_response", {
  176. {"tool", message.at("name")},
  177. {"content", message.at("content")},
  178. }},
  179. };
  180. if (message.contains("tool_call_id")) {
  181. obj["tool_response"]["tool_call_id"] = message.at("tool_call_id");
  182. }
  183. message["content"] = obj.dump(2);
  184. message.erase("name");
  185. }
  186. if (!message["content"].is_null() && !supports_system_role_) {
  187. std::string content = message.at("content");
  188. if (role == "system") {
  189. if (!pending_system.empty()) pending_system += "\n";
  190. pending_system += content;
  191. continue;
  192. } else {
  193. if (role == "user") {
  194. if (!pending_system.empty()) {
  195. message["content"] = pending_system + (content.empty() ? "" : "\n" + content);
  196. pending_system.clear();
  197. }
  198. } else {
  199. flush_sys();
  200. }
  201. }
  202. }
  203. actual_messages.push_back(message);
  204. }
  205. flush_sys();
  206. } else {
  207. actual_messages = messages;
  208. }
  209. auto context = minja::Context::make(json({
  210. {"messages", actual_messages},
  211. {"add_generation_prompt", add_generation_prompt},
  212. {"bos_token", bos_token_},
  213. {"eos_token", eos_token_},
  214. }));
  215. if (!tools.is_null()) {
  216. auto tools_val = minja::Value(tools);
  217. context->set("tools", tools_val);
  218. }
  219. if (!extra_context.is_null()) {
  220. for (auto & kv : extra_context.items()) {
  221. minja::Value val(kv.value());
  222. context->set(kv.key(), val);
  223. }
  224. }
  225. return template_root_->render(context);
  226. }
  227. };
  228. } // namespace minja