| 434 | } |
| 435 | |
| 436 | std::string common_chat_format_single( |
| 437 | const struct common_chat_templates * tmpls, |
| 438 | const std::vector<common_chat_msg> & past_msg, |
| 439 | const common_chat_msg & new_msg, |
| 440 | bool add_ass, |
| 441 | bool use_jinja) { |
| 442 | |
| 443 | common_chat_templates_inputs inputs; |
| 444 | inputs.use_jinja = use_jinja; |
| 445 | |
| 446 | std::string fmt_past_msg; |
| 447 | if (!past_msg.empty()) { |
| 448 | inputs.messages = past_msg; |
| 449 | inputs.add_generation_prompt = false; |
| 450 | fmt_past_msg = common_chat_templates_apply(tmpls, inputs).prompt; |
| 451 | } |
| 452 | std::ostringstream ss; |
| 453 | // if the past_msg ends with a newline, we must preserve it in the formatted version |
| 454 | if (add_ass && !fmt_past_msg.empty() && fmt_past_msg.back() == '\n') { |
| 455 | ss << "\n"; |
| 456 | }; |
| 457 | // format chat with new_msg |
| 458 | inputs.messages.push_back(new_msg); |
| 459 | inputs.add_generation_prompt = add_ass; |
| 460 | auto fmt_new_msg = common_chat_templates_apply(tmpls, inputs).prompt; |
| 461 | // get the diff part |
| 462 | ss << fmt_new_msg.substr(fmt_past_msg.size(), fmt_new_msg.size() - fmt_past_msg.size()); |
| 463 | return ss.str(); |
| 464 | } |
| 465 | |
| 466 | std::string common_chat_format_example(const struct common_chat_templates * tmpls, bool use_jinja) { |
| 467 | common_chat_templates_inputs inputs; |