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