| 217 | }; |
| 218 | |
| 219 | static delta_data init_delta(const struct common_chat_templates * tmpls, const std::vector<std::string> & end_tokens, |
| 220 | const common_chat_msg & user_message, |
| 221 | const common_chat_msg & delta_message, |
| 222 | const std::vector<common_chat_tool> & tools, |
| 223 | const common_chat_tool_choice & tool_choice) { |
| 224 | common_chat_templates_inputs inputs; |
| 225 | inputs.parallel_tool_calls = true; |
| 226 | inputs.messages.push_back(user_message); |
| 227 | inputs.tools = tools; |
| 228 | inputs.tool_choice = tool_choice; |
| 229 | auto params_prefix = common_chat_templates_apply(tmpls, inputs); |
| 230 | |
| 231 | inputs.messages.push_back(delta_message); |
| 232 | inputs.add_generation_prompt = false; |
| 233 | auto params_full = common_chat_templates_apply(tmpls, inputs); |
| 234 | |
| 235 | std::string prefix = params_prefix.prompt; |
| 236 | std::string full = params_full.prompt; |
| 237 | |
| 238 | if (full == prefix) { |
| 239 | throw std::runtime_error("Full message is the same as the prefix"); |
| 240 | } |
| 241 | |
| 242 | size_t common_prefix_length = 0; |
| 243 | for (size_t i = 0; i < prefix.size() && i < full.size(); ++i) { |
| 244 | if (prefix[i] != full[i]) { |
| 245 | break; |
| 246 | } |
| 247 | if (prefix[i] == '<') { |
| 248 | // DeepSeek R1's template (as of 20250209) adds a trailing <think> if add_generation_prompt, |
| 249 | // but it removes thinking tags for past messages. |
| 250 | // The prefix and full strings diverge at <think> vs. <|tool▁calls▁begin|>, we avoid consuming the leading <. |
| 251 | continue; |
| 252 | } |
| 253 | common_prefix_length = i + 1; |
| 254 | } |
| 255 | auto delta = full.substr(common_prefix_length); |
| 256 | |
| 257 | // Strip end tokens |
| 258 | for (const auto & end_token : end_tokens) { |
| 259 | // rfind to find the last occurrence |
| 260 | auto pos = delta.rfind(end_token); |
| 261 | if (pos != std::string::npos) { |
| 262 | delta = delta.substr(0, pos); |
| 263 | break; |
| 264 | } |
| 265 | } |
| 266 | return { delta, params_full }; |
| 267 | } |
| 268 | |
| 269 | /* |
| 270 | Applies the template to 1 user message w/ add_generation_prompt=true, then w/ the test message w/ add_generation_prompt=false, |
no test coverage detected