chat.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  1. #include "chat.h"
  2. #include "json-schema-to-grammar.h"
  3. #include "log.h"
  4. #include "minja/chat-template.hpp"
  5. #include "minja/minja.hpp"
  6. #include <optional>
  7. typedef minja::chat_template common_chat_template;
  8. struct common_chat_templates {
  9. bool has_explicit_template; // Model had builtin template or template overridde was specified.
  10. std::unique_ptr<common_chat_template> template_default; // always set (defaults to chatml)
  11. std::unique_ptr<common_chat_template> template_tool_use;
  12. };
  13. struct templates_params {
  14. json messages;
  15. json tools;
  16. common_chat_tool_choice tool_choice;
  17. json json_schema;
  18. bool parallel_tool_calls;
  19. bool stream;
  20. std::string grammar;
  21. bool add_generation_prompt = true;
  22. bool extract_reasoning = true;
  23. };
  24. common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::string & tool_choice) {
  25. if (tool_choice == "auto") {
  26. return COMMON_CHAT_TOOL_CHOICE_AUTO;
  27. }
  28. if (tool_choice == "none") {
  29. return COMMON_CHAT_TOOL_CHOICE_NONE;
  30. }
  31. if (tool_choice == "required") {
  32. return COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  33. }
  34. throw std::runtime_error("Invalid tool_choice: " + tool_choice);
  35. }
  36. template <>
  37. std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const json & messages) {
  38. std::vector<common_chat_msg> msgs;
  39. try {
  40. if (!messages.is_array()) {
  41. throw std::runtime_error("Expected 'messages' to be an array, got " + messages.dump());
  42. }
  43. for (const auto & message : messages) {
  44. if (!message.is_object()) {
  45. throw std::runtime_error("Expected 'message' to be an object, got " + message.dump());
  46. }
  47. common_chat_msg msg;
  48. if (!message.contains("role")) {
  49. throw std::runtime_error("Missing 'role' in message: " + message.dump());
  50. }
  51. msg.role = message.at("role");
  52. if (message.contains("content")) {
  53. const auto & content = message.at("content");
  54. if (content.is_string()) {
  55. msg.content = content;
  56. } else if (content.is_array()) {
  57. for (const auto & part : content) {
  58. if (!part.contains("type")) {
  59. throw std::runtime_error("Missing content part type: " + part.dump());
  60. }
  61. const auto & type = part.at("type");
  62. if (type != "text") {
  63. throw std::runtime_error("Unsupported content part type: " + type.dump());
  64. }
  65. common_chat_msg_content_part msg_part;
  66. msg_part.type = type;
  67. msg_part.text = part.at("text");
  68. msg.content_parts.push_back(msg_part);
  69. }
  70. } else if (!content.is_null()) {
  71. throw std::runtime_error("Invalid 'content' type: expected string or array, got " + content.dump() + " (ref: https://github.com/ggml-org/llama.cpp/issues/8367)");
  72. }
  73. } else {
  74. throw std::runtime_error("Expected 'content' (ref: https://github.com/ggml-org/llama.cpp/issues/8367)");
  75. }
  76. if (message.contains("reasoning_content")) {
  77. msg.reasoning_content = message.at("reasoning_content");
  78. }
  79. if (message.contains("name")) {
  80. msg.tool_name = message.at("name");
  81. }
  82. if (message.contains("tool_call_id")) {
  83. msg.tool_call_id = message.at("tool_call_id");
  84. }
  85. if (message.contains("tool_calls")) {
  86. for (const auto & tool_call : message.at("tool_calls")) {
  87. common_chat_tool_call tc;
  88. if (!tool_call.contains("type")) {
  89. throw std::runtime_error("Missing tool call type: " + tool_call.dump());
  90. }
  91. const auto & type = tool_call.at("type");
  92. if (type != "function") {
  93. throw std::runtime_error("Unsupported tool call type: " + tool_call.dump());
  94. }
  95. if (!tool_call.contains("function")) {
  96. throw std::runtime_error("Missing tool call function: " + tool_call.dump());
  97. }
  98. const auto & fc = tool_call.at("function");
  99. if (!fc.contains("name")) {
  100. throw std::runtime_error("Missing tool call name: " + tool_call.dump());
  101. }
  102. tc.name = fc.at("name");
  103. tc.arguments = fc.at("arguments");
  104. if (tool_call.contains("id")) {
  105. tc.id = tool_call.at("id");
  106. }
  107. msg.tool_calls.push_back(tc);
  108. }
  109. }
  110. msgs.push_back(msg);
  111. }
  112. } catch (const std::exception & e) {
  113. throw std::runtime_error("Failed to parse messages: " + std::string(e.what()) + "; messages = " + messages.dump(2));
  114. }
  115. return msgs;
  116. }
  117. template <>
  118. json common_chat_msgs_to_json_oaicompat(const std::vector<common_chat_msg> & msgs, bool concat_typed_text) {
  119. json messages = json::array();
  120. for (const auto & msg : msgs) {
  121. if (!msg.content.empty() && !msg.content_parts.empty()) {
  122. throw std::runtime_error("Cannot specify both content and content_parts");
  123. }
  124. json jmsg {
  125. {"role", msg.role},
  126. };
  127. if (!msg.content.empty()) {
  128. jmsg["content"] = msg.content;
  129. } else if (!msg.content_parts.empty()) {
  130. if (concat_typed_text) {
  131. std::string text;
  132. for (const auto & part : msg.content_parts) {
  133. if (part.type != "text") {
  134. LOG_WRN("Ignoring content part type: %s\n", part.type.c_str());
  135. continue;
  136. }
  137. if (!text.empty()) {
  138. text += '\n';
  139. }
  140. text += part.text;
  141. }
  142. jmsg["content"] = text;
  143. } else {
  144. auto & parts = jmsg["content"] = json::array();
  145. for (const auto & part : msg.content_parts) {
  146. parts.push_back({
  147. {"type", part.type},
  148. {"text", part.text},
  149. });
  150. }
  151. }
  152. } else {
  153. jmsg["content"] = json(); // null
  154. }
  155. if (!msg.reasoning_content.empty()) {
  156. jmsg["reasoning_content"] = msg.reasoning_content;
  157. }
  158. if (!msg.tool_name.empty()) {
  159. jmsg["name"] = msg.tool_name;
  160. }
  161. if (!msg.tool_call_id.empty()) {
  162. jmsg["tool_call_id"] = msg.tool_call_id;
  163. }
  164. if (!msg.tool_calls.empty()) {
  165. auto & tool_calls = jmsg["tool_calls"] = json::array();
  166. for (const auto & tool_call : msg.tool_calls) {
  167. json tc {
  168. {"type", "function"},
  169. {"function", {
  170. {"name", tool_call.name},
  171. {"arguments", tool_call.arguments},
  172. }},
  173. };
  174. if (!tool_call.id.empty()) {
  175. tc["id"] = tool_call.id;
  176. }
  177. tool_calls.push_back(tc);
  178. }
  179. }
  180. messages.push_back(jmsg);
  181. }
  182. return messages;
  183. }
  184. template <>
  185. std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const std::string & messages) {
  186. return common_chat_msgs_parse_oaicompat(json::parse(messages));
  187. }
  188. template <>
  189. std::vector<common_chat_tool> common_chat_tools_parse_oaicompat(const json & tools) {
  190. std::vector<common_chat_tool> result;
  191. try {
  192. if (!tools.is_null()) {
  193. if (!tools.is_array()) {
  194. throw std::runtime_error("Expected 'tools' to be an array, got " + tools.dump());
  195. }
  196. for (const auto & tool : tools) {
  197. if (!tool.contains("type")) {
  198. throw std::runtime_error("Missing tool type: " + tool.dump());
  199. }
  200. const auto & type = tool.at("type");
  201. if (!type.is_string() || type != "function") {
  202. throw std::runtime_error("Unsupported tool type: " + tool.dump());
  203. }
  204. if (!tool.contains("function")) {
  205. throw std::runtime_error("Missing tool function: " + tool.dump());
  206. }
  207. const auto & function = tool.at("function");
  208. result.push_back({
  209. /* .name = */ function.at("name"),
  210. /* .description = */ function.at("description"),
  211. /* .parameters = */ function.at("parameters").dump(),
  212. });
  213. }
  214. }
  215. } catch (const std::exception & e) {
  216. throw std::runtime_error("Failed to parse tools: " + std::string(e.what()) + "; tools = " + tools.dump(2));
  217. }
  218. return result;
  219. }
  220. template <>
  221. std::vector<common_chat_tool> common_chat_tools_parse_oaicompat(const std::string & tools) {
  222. return common_chat_tools_parse_oaicompat(json::parse(tools));
  223. }
  224. template <>
  225. json common_chat_tools_to_json_oaicompat(const std::vector<common_chat_tool> & tools) {
  226. if (tools.empty()) {
  227. return json();
  228. }
  229. auto result = json::array();
  230. for (const auto & tool : tools) {
  231. result.push_back({
  232. {"type", "function"},
  233. {"function", {
  234. {"name", tool.name},
  235. {"description", tool.description},
  236. {"parameters", json::parse(tool.parameters)},
  237. }},
  238. });
  239. }
  240. return result;
  241. }
  242. bool common_chat_verify_template(const std::string & tmpl, bool use_jinja) {
  243. if (use_jinja) {
  244. try {
  245. common_chat_msg msg;
  246. msg.role = "user";
  247. msg.content = "test";
  248. auto tmpls = common_chat_templates_init(/* model= */ nullptr, tmpl);
  249. common_chat_templates_inputs inputs;
  250. inputs.messages = {msg};
  251. common_chat_templates_apply(tmpls.get(), inputs);
  252. return true;
  253. } catch (const std::exception & e) {
  254. LOG_ERR("%s: failed to apply template: %s\n", __func__, e.what());
  255. return false;
  256. }
  257. }
  258. llama_chat_message chat[] = {{"user", "test"}};
  259. const int res = llama_chat_apply_template(tmpl.c_str(), chat, 1, true, nullptr, 0);
  260. return res >= 0;
  261. }
  262. std::string common_chat_format_single(
  263. const struct common_chat_templates * tmpls,
  264. const std::vector<common_chat_msg> & past_msg,
  265. const common_chat_msg & new_msg,
  266. bool add_ass,
  267. bool use_jinja) {
  268. common_chat_templates_inputs inputs;
  269. inputs.use_jinja = use_jinja;
  270. std::string fmt_past_msg;
  271. if (!past_msg.empty()) {
  272. inputs.messages = past_msg;
  273. inputs.add_generation_prompt = false;
  274. fmt_past_msg = common_chat_templates_apply(tmpls, inputs).prompt;
  275. }
  276. std::ostringstream ss;
  277. // if the past_msg ends with a newline, we must preserve it in the formatted version
  278. if (add_ass && !fmt_past_msg.empty() && fmt_past_msg.back() == '\n') {
  279. ss << "\n";
  280. };
  281. // format chat with new_msg
  282. inputs.messages.push_back(new_msg);
  283. inputs.add_generation_prompt = add_ass;
  284. auto fmt_new_msg = common_chat_templates_apply(tmpls, inputs).prompt;
  285. // get the diff part
  286. ss << fmt_new_msg.substr(fmt_past_msg.size(), fmt_new_msg.size() - fmt_past_msg.size());
  287. return ss.str();
  288. }
  289. std::string common_chat_format_example(const struct common_chat_templates * tmpls, bool use_jinja) {
  290. common_chat_templates_inputs inputs;
  291. inputs.use_jinja = use_jinja;
  292. auto add_simple_msg = [&](auto role, auto content) {
  293. common_chat_msg msg;
  294. msg.role = role;
  295. msg.content = content;
  296. inputs.messages.push_back(msg);
  297. };
  298. add_simple_msg("system", "You are a helpful assistant");
  299. add_simple_msg("user", "Hello");
  300. add_simple_msg("assistant", "Hi there");
  301. add_simple_msg("user", "How are you?");
  302. return common_chat_templates_apply(tmpls, inputs).prompt;
  303. }
  304. #define CHATML_TEMPLATE_SRC \
  305. "{%- for message in messages -%}\n" \
  306. " {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' -}}\n" \
  307. "{%- endfor -%}\n" \
  308. "{%- if add_generation_prompt -%}\n" \
  309. " {{- '<|im_start|>assistant\n' -}}\n" \
  310. "{%- endif -%}"
  311. void common_chat_templates_free(struct common_chat_templates * tmpls) {
  312. delete tmpls;
  313. }
  314. bool common_chat_templates_was_explicit(const struct common_chat_templates * tmpls) {
  315. return tmpls->has_explicit_template;
  316. }
  317. const char * common_chat_templates_source(const struct common_chat_templates * tmpls, const char * variant) {
  318. if (variant != nullptr) {
  319. if (strcmp(variant, "tool_use") == 0) {
  320. if (tmpls->template_tool_use) {
  321. return tmpls->template_tool_use->source().c_str();
  322. }
  323. return nullptr;
  324. } else {
  325. LOG_DBG("%s: unknown template variant: %s\n", __func__, variant);
  326. }
  327. }
  328. return tmpls->template_default->source().c_str();
  329. }
  330. common_chat_templates_ptr common_chat_templates_init(
  331. const struct llama_model * model,
  332. const std::string & chat_template_override,
  333. const std::string & bos_token_override,
  334. const std::string & eos_token_override)
  335. {
  336. std::string default_template_src;
  337. std::string template_tool_use_src;
  338. bool has_explicit_template = !chat_template_override.empty();
  339. if (chat_template_override.empty()) {
  340. GGML_ASSERT(model != nullptr);
  341. const auto * str = llama_model_chat_template(model, /* name */ nullptr);
  342. if (str) {
  343. default_template_src = str;
  344. has_explicit_template = true;
  345. }
  346. str = llama_model_chat_template(model, /* name */ "tool_use");
  347. if (str) {
  348. template_tool_use_src = str;
  349. has_explicit_template = true;
  350. }
  351. } else {
  352. default_template_src = chat_template_override;
  353. }
  354. if (default_template_src.empty() || default_template_src == "chatml") {
  355. if (!template_tool_use_src.empty()) {
  356. default_template_src = template_tool_use_src;
  357. } else {
  358. default_template_src = CHATML_TEMPLATE_SRC;
  359. }
  360. }
  361. std::string token_bos = bos_token_override;
  362. std::string token_eos = eos_token_override;
  363. if (model) {
  364. const auto * vocab = llama_model_get_vocab(model);
  365. const auto get_token = [&](llama_token token, const char * name, const char * jinja_variable_name) {
  366. if (token == LLAMA_TOKEN_NULL) {
  367. if (default_template_src.find(jinja_variable_name) != std::string::npos
  368. || template_tool_use_src.find(jinja_variable_name) != std::string::npos) {
  369. LOG_WRN("common_chat_templates_init: warning: vocab does not have a %s token, jinja template won't work as intended.\n", name);
  370. }
  371. return std::string();
  372. }
  373. return common_token_to_piece(vocab, token, true);
  374. };
  375. token_bos = get_token(llama_vocab_bos(vocab), "BOS", "bos_token");
  376. token_eos = get_token(llama_vocab_eos(vocab), "EOS", "eos_token");
  377. }
  378. common_chat_templates_ptr tmpls(new common_chat_templates());
  379. tmpls->has_explicit_template = has_explicit_template;
  380. try {
  381. tmpls->template_default = std::make_unique<minja::chat_template>(default_template_src, token_bos, token_eos);
  382. } catch (const std::exception & e) {
  383. LOG_ERR("%s: failed to parse chat template (defaulting to chatml): %s \n", __func__, e.what());
  384. tmpls->template_default = std::make_unique<minja::chat_template>(CHATML_TEMPLATE_SRC, token_bos, token_eos);
  385. }
  386. if (!template_tool_use_src.empty()) {
  387. try {
  388. tmpls->template_tool_use = std::make_unique<minja::chat_template>(template_tool_use_src, token_bos, token_eos);
  389. } catch (const std::exception & e) {
  390. LOG_ERR("%s: failed to parse tool use chat template (ignoring it): %s\n", __func__, e.what());
  391. }
  392. }
  393. return tmpls;
  394. }
  395. std::string common_chat_format_name(common_chat_format format) {
  396. switch (format) {
  397. case COMMON_CHAT_FORMAT_CONTENT_ONLY: return "Content-only";
  398. case COMMON_CHAT_FORMAT_GENERIC: return "Generic";
  399. case COMMON_CHAT_FORMAT_MISTRAL_NEMO: return "Mistral Nemo";
  400. case COMMON_CHAT_FORMAT_LLAMA_3_X: return "Llama 3.x";
  401. case COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS: return "Llama 3.x with builtin tools";
  402. case COMMON_CHAT_FORMAT_DEEPSEEK_R1: return "DeepSeek R1";
  403. case COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING: return "DeepSeek R1 (extract reasoning)";
  404. case COMMON_CHAT_FORMAT_FIREFUNCTION_V2: return "FireFunction v2";
  405. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2: return "Functionary v3.2";
  406. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1: return "Functionary v3.1 Llama 3.1";
  407. case COMMON_CHAT_FORMAT_HERMES_2_PRO: return "Hermes 2 Pro";
  408. case COMMON_CHAT_FORMAT_COMMAND_R7B: return "Command R7B";
  409. case COMMON_CHAT_FORMAT_COMMAND_R7B_EXTRACT_REASONING: return "Command R7B (extract reasoning)";
  410. default:
  411. throw std::runtime_error("Unknown chat format");
  412. }
  413. }
  414. const common_grammar_options grammar_options {
  415. /* .dotall = */ false,
  416. /* .compact_spaces = */ false,
  417. // /* .compact_spaces = */ true,
  418. };
  419. static bool parse_json(std::string::const_iterator & it, const std::string::const_iterator & end, json & out) {
  420. // // https://json.nlohmann.me/features/parsing/sax_interface/
  421. struct json_error_locator : public nlohmann::json_sax<json> {
  422. std::size_t position;
  423. bool found_error;
  424. json_error_locator() : position(0), found_error(false) {}
  425. bool parse_error(std::size_t position, const std::string &, const json::exception &) override { // NOLINT
  426. this->position = position - 1;
  427. this->found_error = true;
  428. return false;
  429. }
  430. bool null() override { return true; } // NOLINT
  431. bool boolean(bool) override { return true; } // NOLINT
  432. bool number_integer(number_integer_t) override { return true; } // NOLINT
  433. bool number_unsigned(number_unsigned_t) override { return true; } // NOLINT
  434. bool number_float(number_float_t, const string_t &) override { return true; } // NOLINT
  435. bool string(string_t &) override { return true; } // NOLINT
  436. bool binary(binary_t &) override { return true; } // NOLINT
  437. bool start_object(std::size_t) override { return true; } // NOLINT
  438. bool key(string_t &) override { return true; } // NOLINT
  439. bool end_object() override { return true; }
  440. bool start_array(std::size_t) override { return true; } // NOLINT
  441. bool end_array() override { return true; }
  442. };
  443. json_error_locator err_loc;
  444. json::sax_parse(it, end, &err_loc);
  445. std::string::const_iterator temptative_end;
  446. if (err_loc.found_error) {
  447. temptative_end = it + err_loc.position;
  448. } else {
  449. temptative_end = end;
  450. }
  451. std::string json_sub {it, temptative_end};
  452. try {
  453. out = json::parse(json_sub);
  454. it = temptative_end;
  455. return true;
  456. } catch (const std::exception &) {
  457. return false;
  458. }
  459. }
  460. /**
  461. * Takes a prefix regex that must have 1 group to capture the function name, a closing suffix, and expects json parameters in between.
  462. * Aggregates the prefix, suffix and in-between text into the content.
  463. */
  464. static common_chat_msg parse_json_tool_calls(
  465. const std::string& input,
  466. const std::optional<std::regex> & trigger_opt,
  467. const std::regex & function_regex,
  468. const std::regex & close_regex) {
  469. std::smatch match;
  470. common_chat_msg result;
  471. result.role = "assistant";
  472. auto end = input.end();
  473. auto it = input.begin();
  474. if (trigger_opt) {
  475. if (!std::regex_search(it, end, match, *trigger_opt)) {
  476. result.content = input;
  477. return result;
  478. }
  479. result.content = match.prefix().str();
  480. it = match.suffix().first;
  481. }
  482. while (it != end) {
  483. std::sregex_iterator rend;
  484. std::sregex_iterator rit(it, end, function_regex);
  485. if (rit == rend) {
  486. result.content += std::string(it, end);
  487. break;
  488. }
  489. auto name = rit->str(1);
  490. result.content += std::string(it, rit->prefix().second);
  491. it = rit->suffix().first;
  492. json arguments;
  493. if (!parse_json(it, end, arguments)) {
  494. throw std::runtime_error("Failed to parse json tool call arguments: " + input);
  495. }
  496. if (!std::regex_search(it, end, match, close_regex)) {
  497. throw std::runtime_error("Malformed input, missing closing pattern: " + input);
  498. }
  499. it = match.suffix().first;
  500. result.tool_calls.push_back({name, arguments.is_string() ? arguments.get<std::string>() : arguments.dump(), /* id= */ ""});
  501. }
  502. if (!result.tool_calls.empty()) {
  503. if (!string_strip(result.content).empty()) {
  504. LOG_WRN("Content found with tool calls: %s\n", result.content.c_str());
  505. }
  506. result.content = "";
  507. }
  508. return result;
  509. }
  510. static common_chat_msg parse_prefixed_json_tool_call_array(const std::string& input, const std::string & prefix, size_t rstrip_prefix = 0) {
  511. auto content_end = input.find(prefix);
  512. size_t tc_start = std::string::npos;
  513. common_chat_msg result;
  514. result.role = "assistant";
  515. const auto process_tool_calls = [&](const json & tool_calls) {
  516. for (const auto & tool_call : tool_calls) {
  517. const auto & arguments = tool_call.at("arguments");
  518. result.tool_calls.push_back({
  519. tool_call.at("name"),
  520. arguments.is_string() ? arguments.get<std::string>() : arguments.dump(),
  521. tool_call.contains("id") ? tool_call.at("id") : "",
  522. });
  523. }
  524. };
  525. if (content_end == std::string::npos) {
  526. result.content = input;
  527. } else {
  528. tc_start = content_end + prefix.size() - rstrip_prefix;
  529. result.content = input.substr(0, content_end);
  530. auto tool_calls = json::parse(input.substr(tc_start));
  531. process_tool_calls(tool_calls);
  532. }
  533. return result;
  534. }
  535. static void foreach_function(const json & tools, const std::function<void(const json &)> & fn) {
  536. for (const auto & tool : tools) {
  537. if (!tool.contains("type") || tool.at("type") != "function" || !tool.contains("function")) {
  538. LOG_INF("Skipping tool without function: %s", tool.dump(2).c_str());
  539. continue;
  540. }
  541. fn(tool);
  542. }
  543. }
  544. static std::string apply(
  545. const common_chat_template & tmpl,
  546. const nlohmann::ordered_json & messages,
  547. const nlohmann::ordered_json & tools,
  548. bool add_generation_prompt,
  549. const nlohmann::ordered_json & extra_context = nlohmann::ordered_json())
  550. {
  551. minja::chat_template_inputs tmpl_inputs;
  552. tmpl_inputs.messages = messages;
  553. tmpl_inputs.tools = tools;
  554. tmpl_inputs.add_generation_prompt = add_generation_prompt;
  555. tmpl_inputs.extra_context = extra_context;
  556. // TODO: add flag to control date/time, if only for testing purposes.
  557. // tmpl_inputs.now = std::chrono::system_clock::now();
  558. minja::chat_template_options tmpl_opts;
  559. // To avoid double BOS / EOS tokens, we're manually removing begining / trailing tokens
  560. // instead of using `chat_template_options.use_bos_token = false`, since these tokens
  561. // may be needed inside the template / between messages too.
  562. auto result = tmpl.apply(tmpl_inputs, tmpl_opts);
  563. if (string_starts_with(result, tmpl.bos_token())) {
  564. result = result.substr(tmpl.bos_token().size());
  565. }
  566. if (string_ends_with(result, tmpl.eos_token())) {
  567. result = result.substr(0, result.size() - tmpl.eos_token().size());
  568. }
  569. return result;
  570. }
  571. static common_chat_params common_chat_params_init_generic(const common_chat_template & tmpl, const struct templates_params & inputs) {
  572. common_chat_params data;
  573. auto tool_call_schemas = json::array();
  574. foreach_function(inputs.tools, [&](const json & tool) {
  575. const auto & function = tool.at("function");
  576. auto tool_schema = json {
  577. {"type", "object"},
  578. {"properties", {
  579. {"name", {
  580. {"type", "string"},
  581. {"const", function.at("name")},
  582. }},
  583. {"arguments", function.at("parameters")},
  584. }},
  585. {"required", json::array({"name", "arguments"})},
  586. };
  587. if (function.contains("description")) {
  588. tool_schema["description"] = function.at("description");
  589. }
  590. if (inputs.parallel_tool_calls) {
  591. tool_schema.at("properties")["id"] = {
  592. {"type", "string"},
  593. {"minLength", 4},
  594. };
  595. tool_schema.at("required").push_back("id");
  596. }
  597. tool_call_schemas.emplace_back(tool_schema);
  598. });
  599. const auto tool_call =
  600. inputs.parallel_tool_calls
  601. ? json {
  602. {"type", "object"},
  603. {"properties", {
  604. {"tool_calls", {
  605. {"type", "array"},
  606. {"items", tool_call_schemas.size() == 1 ? tool_call_schemas[0] : json {
  607. {"anyOf", tool_call_schemas},
  608. }},
  609. {"minItems", 1},
  610. }},
  611. }},
  612. {"required", json::array({"tool_calls"})},
  613. }
  614. : json {
  615. {"type", "object"},
  616. {"properties", {
  617. {"tool_call", tool_call_schemas.size() == 1 ? tool_call_schemas[0] : json {
  618. {"anyOf", tool_call_schemas},
  619. }},
  620. }},
  621. {"required", json::array({"tool_call"})},
  622. };
  623. const auto schema =
  624. inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED
  625. ? json {
  626. {"anyOf", json::array({
  627. tool_call,
  628. {
  629. {"type", "object"},
  630. {"properties", {
  631. {"response", inputs.json_schema.is_null()
  632. ? json {{"type", "string"}}
  633. : inputs.json_schema
  634. },
  635. }},
  636. {"required", json::array({"response"})},
  637. },
  638. })}
  639. }
  640. : tool_call;
  641. data.grammar_lazy = false;
  642. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  643. builder.add_schema("root", schema);
  644. }, grammar_options);
  645. auto tweaked_messages = common_chat_template::add_system(
  646. inputs.messages,
  647. "Respond in JSON format, either with `tool_call` (a request to call tools) or with `response` reply to the user's request");
  648. data.prompt = apply(tmpl, tweaked_messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  649. data.format = COMMON_CHAT_FORMAT_GENERIC;
  650. return data;
  651. }
  652. static common_chat_msg common_chat_parse_generic(const std::string & input) {
  653. json data = json::parse(input);
  654. common_chat_msg result;
  655. result.role = "assistant";
  656. if (data.contains("tool_calls")) {
  657. for (const auto & tool_call : data.at("tool_calls")) {
  658. result.tool_calls.push_back({
  659. tool_call.at("name"),
  660. tool_call.at("arguments").dump(),
  661. tool_call.contains("id") ? tool_call.at("id") : "",
  662. });
  663. }
  664. } else if (data.contains("tool_call")) {
  665. result.tool_calls.push_back({
  666. data.at("tool_call").at("name"),
  667. data.at("tool_call").at("arguments").dump(),
  668. /* id= */ "",
  669. });
  670. } else if (data.contains("response")) {
  671. const auto & response = data.at("response");
  672. result.content = response.is_string() ? response.get<std::string>() : response.dump(2);
  673. }
  674. return result;
  675. }
  676. static common_chat_params common_chat_params_init_mistral_nemo(const common_chat_template & tmpl, const struct templates_params & inputs) {
  677. common_chat_params data;
  678. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  679. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  680. auto schemas = json::array();
  681. foreach_function(inputs.tools, [&](const json & tool) {
  682. const auto & function = tool.at("function");
  683. schemas.push_back({
  684. {"type", "object"},
  685. {"properties", {
  686. // Important note: the model is probably trained to take a JSON stringified arguments value.
  687. // It's hard to constrain that for now (while reusing the JSON schema conversion), so we're just expecting a plain object.
  688. {"name", {
  689. {"type", "string"},
  690. {"const", function.at("name")},
  691. }},
  692. {"arguments", function.at("parameters")},
  693. {"id", {
  694. {"type", "string"},
  695. // Nemo's template expects a 9-character alphanumeric ID.
  696. {"pattern", "^[a-zA-Z0-9]{9}$"},
  697. }},
  698. }},
  699. {"required", json::array({"name", "arguments", "id"})},
  700. });
  701. });
  702. auto schema = json {
  703. {"type", "array"},
  704. {"items", schemas.size() == 1 ? schemas[0] : json {{"anyOf", schemas}}},
  705. {"minItems", 1},
  706. };
  707. if (!inputs.parallel_tool_calls) {
  708. schema["maxItems"] = 1;
  709. }
  710. builder.add_rule("root", "\"[TOOL_CALLS]\" " + builder.add_schema("tool_calls", schema));
  711. }, grammar_options);
  712. data.grammar_triggers.push_back({"[TOOL_CALLS]", /* .at_start = */ true});
  713. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  714. data.format = COMMON_CHAT_FORMAT_MISTRAL_NEMO;
  715. return data;
  716. }
  717. static common_chat_msg common_chat_parse_mistral_nemo(const std::string & input) {
  718. return parse_prefixed_json_tool_call_array(input, "[TOOL_CALLS]");
  719. }
  720. static common_chat_params common_chat_params_init_command_r7b(const common_chat_template & tmpl, const struct templates_params & inputs) {
  721. common_chat_params data;
  722. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  723. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  724. auto schemas = json::array();
  725. foreach_function(inputs.tools, [&](const json & tool) {
  726. const auto & function = tool.at("function");
  727. schemas.push_back({
  728. {"type", "object"},
  729. {"properties", {
  730. {"tool_call_id", {
  731. {"type", "string"},
  732. // Command-R's template expects an integer string.
  733. {"pattern", "^[0-9]{1,10}$"},
  734. }},
  735. {"tool_name", {
  736. {"type", "string"},
  737. {"const", function.at("name")},
  738. }},
  739. {"parameters", function.at("parameters")},
  740. }},
  741. {"required", json::array({"tool_call_id", "tool_name", "parameters"})},
  742. });
  743. });
  744. auto schema = json {
  745. {"type", "array"},
  746. {"items", schemas.size() == 1 ? schemas[0] : json {{"anyOf", schemas}}},
  747. {"minItems", 1},
  748. };
  749. if (!inputs.parallel_tool_calls) {
  750. schema["maxItems"] = 1;
  751. }
  752. builder.add_rule("root", "\"<|START_ACTION|>\" " + builder.add_schema("tool_calls", schema) + " \"<|END_ACTION|>\"");
  753. }, grammar_options);
  754. data.grammar_triggers.push_back({"<|START_ACTION|>", /* .at_start = */ false});
  755. data.preserved_tokens = {
  756. "<|START_RESPONSE|>",
  757. "<|END_RESPONSE|>",
  758. "<|START_THINKING|>",
  759. "<|END_THINKING|>",
  760. "<|END_ACTION|>",
  761. };
  762. auto adjusted_messages = json::array();
  763. for (const auto & msg : inputs.messages) {
  764. auto has_reasoning_content = msg.contains("reasoning_content") && msg.at("reasoning_content").is_string();
  765. auto has_tool_calls = msg.contains("tool_calls") && msg.at("tool_calls").is_array();
  766. if (has_reasoning_content && has_tool_calls) {
  767. auto adjusted_message = msg;
  768. adjusted_message["tool_plan"] = msg.at("reasoning_content");
  769. adjusted_message.erase("reasoning_content");
  770. adjusted_messages.push_back(adjusted_message);
  771. } else {
  772. adjusted_messages.push_back(msg);
  773. }
  774. }
  775. data.prompt = apply(tmpl, adjusted_messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt, {});
  776. data.format = inputs.extract_reasoning ? COMMON_CHAT_FORMAT_COMMAND_R7B_EXTRACT_REASONING : COMMON_CHAT_FORMAT_COMMAND_R7B;
  777. return data;
  778. }
  779. static common_chat_msg common_chat_parse_command_r7b(const std::string & input, bool extract_reasoning) {
  780. static std::regex thought_regex("(<\\|START_THINKING\\|>([\\s\\S\\n\\r]*?)<\\|END_THINKING\\|>)([\\s\\S\\n\\r]*)");
  781. static std::regex action_regex("<\\|START_ACTION\\|>([\\s\\S\\n\\r]*?)<\\|END_ACTION\\|>");
  782. static std::regex response_regex("(?:<\\|START_RESPONSE\\|>)?([\\s\\S\\n\\r]*?)<\\|END_RESPONSE\\|>");
  783. std::smatch match;
  784. common_chat_msg result;
  785. result.role = "assistant";
  786. std::string rest = input;
  787. if (std::regex_match(rest, match, thought_regex)) {
  788. if (extract_reasoning) {
  789. result.reasoning_content = match[2].str();
  790. } else if (!match[2].str().empty()) {
  791. // Let the unparsed thinking tags through in content only if their insides aren't empty.
  792. result.content = match[1].str();
  793. }
  794. rest = match[3].str();
  795. }
  796. if (std::regex_match(rest, match, action_regex)) {
  797. auto actions_str = match[1].str();
  798. auto actions = json::parse(actions_str);
  799. for (const auto & action : actions) {
  800. result.tool_calls.push_back({
  801. /* .name = */ action.at("tool_name"),
  802. /* .arguments = */ action.at("parameters").dump(),
  803. /* .id = */ action.at("tool_call_id"),
  804. });
  805. }
  806. } else if (std::regex_match(rest, match, response_regex)) {
  807. auto response = match[1].str();
  808. result.content += response;
  809. } else {
  810. result.content += rest;
  811. }
  812. return result;
  813. }
  814. static void expect_tool_parameters(const std::string & name, const json & parameters, const std::vector<std::string> & expected_properties) {
  815. if (!parameters.is_object() || !parameters.contains("type") || parameters.at("type") != "object" || !parameters.contains("properties") || !parameters.contains("required")) {
  816. throw std::runtime_error("Parameters of tool " + name + " must be an object w/ required properties");
  817. }
  818. const auto & parameters_properties = parameters.at("properties");
  819. const auto & parameters_required = parameters.at("required");
  820. for (const auto & prop : expected_properties) {
  821. if (!parameters_properties.contains(prop)) {
  822. throw std::runtime_error("Parameters of tool " + name + " is missing property: " + prop); // NOLINT
  823. }
  824. if (std::find(parameters_required.begin(), parameters_required.end(), json(prop)) == parameters_required.end()) {
  825. throw std::runtime_error("Parameters of tool " + name + " must have property marked as required: " + prop); // NOLINT
  826. }
  827. }
  828. if (parameters_properties.size() != expected_properties.size()) {
  829. throw std::runtime_error("Parameters of tool " + name + " must only have these properties:" + string_join(expected_properties, ", "));
  830. }
  831. }
  832. static common_chat_params common_chat_params_init_llama_3_1_tool_calls(const common_chat_template & tmpl, const struct templates_params & inputs, bool allow_python_tag_builtin_tools) {
  833. auto builtin_tools = json::array();
  834. common_chat_params data;
  835. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  836. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  837. std::vector<std::string> tool_rules;
  838. auto handle_builtin_tool = [&](const std::string & name, const json & parameters) {
  839. if (name == "wolfram_alpha" || name == "web_search" || name == "brave_search") {
  840. // https://github.com/meta-llama/llama-stack/blob/main/llama_stack/providers/remote/tool_runtime/wolfram_alpha/wolfram_alpha.py
  841. // https://github.com/meta-llama/llama-stack/blob/main/llama_stack/providers/remote/tool_runtime/brave_search/brave_search.py
  842. expect_tool_parameters(name, parameters, {"query"});
  843. } else if (name == "python" || name == "code_interpreter") {
  844. // https://github.com/meta-llama/llama-stack/blob/main/llama_stack/providers/inline/tool_runtime/code_interpreter/code_interpreter.py
  845. expect_tool_parameters(name, parameters, {"code"});
  846. } else {
  847. return false;
  848. }
  849. std::vector<std::string> kvs;
  850. for (const auto & [key, value] : parameters.at("properties").items()) {
  851. kvs.push_back("\"" + key + "=\" " + builder.add_schema(name + "-args-" + key, value)); // NOLINT
  852. }
  853. tool_rules.push_back(
  854. builder.add_rule(
  855. name + "-call",
  856. "\"<|python_tag|>" + name + ".call(\" " + string_join(kvs, " \", \" ") + " \")\""));
  857. builtin_tools.push_back(name);
  858. return true;
  859. };
  860. foreach_function(inputs.tools, [&](const json & tool) {
  861. const auto & function = tool.at("function");
  862. std::string name = function.at("name");
  863. auto parameters = function.at("parameters");
  864. builder.resolve_refs(parameters);
  865. // https://github.com/meta-llama/llama-stack/tree/main/llama_stack/providers/remote/tool_runtime
  866. if (allow_python_tag_builtin_tools) {
  867. handle_builtin_tool(name, parameters);
  868. }
  869. tool_rules.push_back(
  870. builder.add_rule(
  871. name + "-call",
  872. "\"{\" space "
  873. "( \"\\\"type\\\":\" space \"\\\"function\\\",\" space )? "
  874. "\"\\\"name\\\": \\\"" + name + "\\\", \\\"parameters\\\": \" " +
  875. builder.add_schema(name + "-args", parameters) +
  876. " \"}\""));
  877. data.grammar_triggers.push_back({"{\"name\": \"" + name + "\"", /* .at_start = */ true});
  878. });
  879. data.grammar_triggers.push_back({"{\"name\":", /* .at_start = */ true});
  880. data.grammar_triggers.push_back({"{\n \"name\":", /* .at_start = */ true});
  881. data.grammar_triggers.push_back({"{\n \"name\":", /* .at_start = */ true});
  882. data.grammar_triggers.push_back({"{\"type\": \"function\"", /* .at_start = */ true});
  883. data.grammar_triggers.push_back({"{\n \"type\": \"function\"", /* .at_start = */ true});
  884. data.grammar_triggers.push_back({"{\n \"type\": \"function\"", /* .at_start = */ true});
  885. if (!builtin_tools.empty()) {
  886. data.grammar_triggers.push_back({"<|python_tag|>", /* .at_start = */ false});
  887. }
  888. builder.add_rule("root", string_join(tool_rules, " | "));
  889. }, grammar_options);
  890. data.additional_stops.push_back("<|eom_id|>");
  891. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt, {
  892. {"tools_in_user_message", false},
  893. {"builtin_tools", builtin_tools.empty() ? json() : builtin_tools},
  894. });
  895. data.format = allow_python_tag_builtin_tools && !builtin_tools.empty()
  896. ? COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS
  897. : COMMON_CHAT_FORMAT_LLAMA_3_X;
  898. return data;
  899. }
  900. static common_chat_msg common_chat_parse_llama_3_1(const std::string & input, bool with_builtin_tools = false) {
  901. // TODO: tighten & simplify the parser, don't accept leading text context.
  902. static std::regex function_regex("\\{[\\s\\n\\r]*(?:\"type\"[\\s\\n\\r]*:[\\s\\n\\r]*\"function\"[\\s\\n\\r]*,[\\s\\n\\r]*|[\\s\\n\\r]*)\"name\"[\\s\\n\\r]*:[\\s\\n\\r]*\"([^\"]+)\"[\\s\\n\\r]*,[\\s\\n\\r]*\"parameters\": ");
  903. static std::regex close_regex("\\}");
  904. static std::regex builtin_call_regex("<\\|python_tag\\|>([^.(]+)\\.call\\((.*)\\)");
  905. if (with_builtin_tools) {
  906. std::smatch match;
  907. if (std::regex_match(input, match, builtin_call_regex)) {
  908. auto name = match[1].str();
  909. auto raw_args = match[2].str();
  910. // TODO: if/when builtin tools start accepting more than 1 argument, use parse_json for real parsing.
  911. auto it_eq = raw_args.find('=');
  912. auto arg_name = raw_args.substr(0, it_eq);
  913. auto arg_value_str = raw_args.substr(it_eq + 1);
  914. auto arg_value = json::parse(arg_value_str);
  915. common_chat_msg msg;
  916. msg.role = "assistant";
  917. msg.content = match.prefix().str();
  918. msg.tool_calls.push_back({
  919. /* .name = */ name,
  920. /* .arguments = */ (json {
  921. {arg_name, arg_value},
  922. }).dump(),
  923. /* .id = */ "",
  924. });
  925. return msg;
  926. }
  927. }
  928. return parse_json_tool_calls(input, std::nullopt, function_regex, close_regex);
  929. }
  930. static common_chat_params common_chat_params_init_deepseek_r1(const common_chat_template & tmpl, const struct templates_params & inputs) {
  931. common_chat_params data;
  932. if (inputs.tools.is_array() && !inputs.tools.empty()) {
  933. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED && inputs.json_schema.is_null();
  934. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  935. std::vector<std::string> tool_rules;
  936. foreach_function(inputs.tools, [&](const json & tool) {
  937. const auto & function = tool.at("function");
  938. std::string name = function.at("name");
  939. auto parameters = function.at("parameters");
  940. builder.resolve_refs(parameters);
  941. auto args_rule = builder.add_schema(name + "-args", parameters);
  942. tool_rules.push_back(builder.add_rule(name + "-call",
  943. "\"<|tool▁call▁begin|>function<|tool▁sep|>" + name + "\\n"
  944. "```json\\n\" " + args_rule + " \"```<|tool▁call▁end|>\""));
  945. });
  946. // Distill Qwen 7B & 32B models seem confused re/ syntax of their tool call opening tag,
  947. // so we accept common variants (then it's all constrained)
  948. builder.add_rule("root",
  949. "( \"<|tool▁calls▁begin|>\" | \"<|tool_calls_begin|>\" | \"<|tool calls begin|>\" | \"<|tool\\\\_calls\\\\_begin|>\" ) "
  950. "(" + string_join(tool_rules, " | ") + ")" + (inputs.parallel_tool_calls ? "*" : "") + " "
  951. "\"<|tool▁calls▁end|>\""
  952. " space");
  953. data.grammar_triggers.push_back({"<|tool▁calls▁begin|>", /* .at_start = */ false});
  954. data.grammar_triggers.push_back({"<|tool_calls_begin|>", /* .at_start = */ false});
  955. data.grammar_triggers.push_back({"<|tool calls begin|>", /* .at_start = */ false});
  956. data.grammar_triggers.push_back({"<|tool\\_calls\\_begin|>", /* .at_start = */ false});
  957. data.preserved_tokens = {
  958. "<think>",
  959. "</think>",
  960. "<|tool▁sep|>",
  961. "<|tool▁calls▁end|",
  962. "<|tool▁call▁end|>",
  963. };
  964. }, grammar_options);
  965. }
  966. auto prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  967. // Hacks to fix the official (broken) prompt.
  968. // It is advisable to use --chat-template-file models/templates/llama-cpp-deepseek-r1.jinja instead,
  969. // until the official template is fixed.
  970. if (tmpl.source().find("{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}") != std::string::npos) {
  971. // Don't leave the chat dangling after tool results
  972. if (string_ends_with(prompt, "<|tool▁outputs▁end|>")) {
  973. prompt += "<|end▁of▁sentence|>";
  974. if (inputs.add_generation_prompt) {
  975. prompt += "<|Assistant|>";
  976. }
  977. }
  978. // Fix up tool call delta example added by Minja
  979. prompt = std::regex_replace(
  980. prompt,
  981. std::regex("(<|tool▁call▁end|>)[\\s\\r\\n]*(<|tool▁outputs▁begin|>|<|User|>)"),
  982. "$1<|tool▁calls▁end|><|end▁of▁sentence|>$2");
  983. }
  984. data.prompt = prompt;
  985. data.format = inputs.extract_reasoning ? COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING : COMMON_CHAT_FORMAT_DEEPSEEK_R1;
  986. return data;
  987. }
  988. static common_chat_msg common_chat_parse_deepseek_r1(const std::string & input, bool extract_reasoning) {
  989. static std::regex function_regex("<|tool▁call▁begin|>function<|tool▁sep|>([^\n]+)\n```json\n");
  990. static std::regex close_regex("```[\\s\\r\\n]*<|tool▁call▁end|>");
  991. static std::regex reasoning_content_regex("((?:<think>)?([\\s\\S\\r\\n]*?)</think>)?([\\s\\S\\r\\n]*)");
  992. static std::regex tool_calls_regex("[\\s\\r\\n]*(?:<|tool▁calls▁begin|>|<|tool_calls_begin|>|<|tool calls begin|>|<|tool\\\\_calls\\\\_begin|>)([\\s\\S\\r\\n]*?)<|tool▁calls▁end|>");
  993. common_chat_msg msg;
  994. msg.role = "assistant";
  995. std::smatch match;
  996. if (std::regex_match(input, match, reasoning_content_regex)) {
  997. std::string rest;
  998. if (extract_reasoning) {
  999. msg.reasoning_content = string_strip(match[2].str());
  1000. } else {
  1001. msg.content = match[1].str();
  1002. }
  1003. rest = match[3].str();
  1004. if (std::regex_search(rest, match, tool_calls_regex)) {
  1005. auto tool_calls = match[1].str();
  1006. auto msg2 = parse_json_tool_calls(tool_calls, std::nullopt, function_regex, close_regex);
  1007. msg.tool_calls = std::move(msg2.tool_calls);
  1008. } else {
  1009. msg.content += std::string(rest.begin() + rest.find_first_not_of(" \r\n"), rest.end());
  1010. }
  1011. } else {
  1012. msg.content = input;
  1013. }
  1014. return msg;
  1015. }
  1016. static common_chat_params common_chat_params_init_firefunction_v2(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1017. LOG_DBG("%s\n", __func__);
  1018. common_chat_params data;
  1019. data.prompt = apply(tmpl, inputs.messages, /* tools= */ nullptr, inputs.add_generation_prompt, {
  1020. {"datetime", "Jan 29 2025 13:00:00 GMT"},
  1021. {"functions", json(inputs.tools.empty() ? "" : inputs.tools.dump(2))},
  1022. });
  1023. if (inputs.tools.is_array() && !inputs.tools.empty()) {
  1024. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  1025. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  1026. auto schemas = json::array();
  1027. foreach_function(inputs.tools, [&](const json & tool) {
  1028. const auto & function = tool.at("function");
  1029. schemas.push_back({
  1030. {"type", "object"},
  1031. {"properties", {
  1032. {"name", {
  1033. {"type", "string"},
  1034. {"const", function.at("name")},
  1035. }},
  1036. {"arguments", function.at("parameters")},
  1037. }},
  1038. {"required", json::array({"name", "arguments", "id"})},
  1039. });
  1040. });
  1041. auto schema = json {
  1042. {"type", "array"},
  1043. {"items", schemas.size() == 1 ? schemas[0] : json {{"anyOf", schemas}}},
  1044. {"minItems", 1},
  1045. };
  1046. if (!inputs.parallel_tool_calls) {
  1047. schema["maxItems"] = 1;
  1048. }
  1049. builder.add_rule("root", "\" functools\"? " + builder.add_schema("tool_calls", schema));
  1050. }, grammar_options);
  1051. data.grammar_triggers.push_back({" functools[", /* .at_start = */ false});
  1052. data.format = COMMON_CHAT_FORMAT_FIREFUNCTION_V2;
  1053. } else {
  1054. data.format = COMMON_CHAT_FORMAT_CONTENT_ONLY;
  1055. }
  1056. return data;
  1057. }
  1058. static common_chat_msg common_chat_parse_firefunction_v2(const std::string & input) {
  1059. return parse_prefixed_json_tool_call_array(input, " functools[", /* rstrip_prefix= */ 1);
  1060. }
  1061. static common_chat_params common_chat_params_init_functionary_v3_2(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1062. // >>>all\nlet's call functions>>>fn1\n{"arg1": 1...}\n>>>fn2\n{"arg1": 1...}...
  1063. // Using ">>>f1\n", ">>>f2\n"... as trigger words for the grammar
  1064. common_chat_params data;
  1065. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  1066. data.format = COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2;
  1067. if (inputs.tools.is_array() && !inputs.tools.empty()) {
  1068. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  1069. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  1070. std::vector<std::string> first_tool_rules;
  1071. std::vector<std::string> subsequent_tool_rules;
  1072. foreach_function(inputs.tools, [&](const json & tool) {
  1073. const auto & function = tool.at("function");
  1074. std::string name = function.at("name");
  1075. auto parameters = function.at("parameters");
  1076. builder.resolve_refs(parameters);
  1077. auto args_rule = builder.add_schema(name + "-args", parameters);
  1078. first_tool_rules.push_back(builder.add_rule(name + "-call", "\"" + name + "\\n\" " + args_rule));
  1079. subsequent_tool_rules.push_back(builder.add_rule(name + "-call2", "\">>>" + name + "\\n\" " + args_rule));
  1080. data.grammar_triggers.push_back({name, /* .at_start = */ true});
  1081. data.grammar_triggers.push_back({">>>" + name, /* .at_start = */ false});
  1082. });
  1083. auto first_rule = first_tool_rules.empty() ? "" : builder.add_rule("first_tool_call", string_join(first_tool_rules, " | ")) + " space";
  1084. if (inputs.parallel_tool_calls) {
  1085. auto subsequent_rule = builder.add_rule("subsequent_tool_call", string_join(subsequent_tool_rules, " | ")) + " space";
  1086. builder.add_rule("root", first_rule + " (" + subsequent_rule + ")*");
  1087. } else {
  1088. builder.add_rule("root", first_rule);
  1089. }
  1090. }, grammar_options);
  1091. }
  1092. return data;
  1093. }
  1094. static bool consume(std::string::const_iterator & it, const std::string::const_iterator & end, const std::string & expected) {
  1095. auto expected_it = expected.begin();
  1096. auto tmp_it = it;
  1097. while (tmp_it != end && expected_it != expected.end() && *tmp_it == *expected_it) {
  1098. ++tmp_it;
  1099. ++expected_it;
  1100. }
  1101. if (expected_it == expected.end()) {
  1102. it = tmp_it;
  1103. return true;
  1104. }
  1105. return false;
  1106. }
  1107. static common_chat_msg common_chat_parse_functionary_v3_2(const std::string & input) {
  1108. static std::regex function_regex(R"((?:>>>)?(\w+)\n)");
  1109. static std::regex close_regex(R"($|(?=>>>))");
  1110. std::string content;
  1111. auto it = input.begin();
  1112. const auto end = input.end();
  1113. if (consume(it, end, "all\n")) {
  1114. std::smatch match;
  1115. if (std::regex_search(it, end, match, function_regex)) {
  1116. auto fun_it = match.prefix().second;
  1117. content = std::string(it, fun_it);
  1118. it = fun_it;
  1119. } else {
  1120. common_chat_msg res;
  1121. res.role = "assistant";
  1122. res.content = std::string(it, end);
  1123. return res;
  1124. }
  1125. }
  1126. // TODO: tighten & simplify.
  1127. try {
  1128. auto res = parse_json_tool_calls(std::string(it, end), std::nullopt, function_regex, close_regex);
  1129. res.content = content + res.content;
  1130. return res;
  1131. } catch (const std::exception & e) {
  1132. LOG_ERR("Failed to parse functionary v3.2 input: %s\n", e.what());
  1133. common_chat_msg res;
  1134. res.role = "assistant";
  1135. res.content = input;
  1136. return res;
  1137. }
  1138. }
  1139. static common_chat_params common_chat_params_init_functionary_v3_1_llama_3_1(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1140. // https://github.com/MeetKai/functionary/blob/main/tests/prompt_test_v3-llama3.1.txt
  1141. common_chat_params data;
  1142. json tools = inputs.tools.is_null() ? inputs.tools : json::array();
  1143. std::string python_code_argument_name;
  1144. auto has_raw_python = false;
  1145. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  1146. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  1147. std::vector<std::string> tool_rules;
  1148. foreach_function(inputs.tools, [&](const json & tool) {
  1149. const auto & function = tool.at("function");
  1150. const auto & parameters = function.at("parameters");
  1151. std::string name = function.at("name");
  1152. if (name == "python" || name == "ipython") {
  1153. if (!parameters.contains("type")) {
  1154. throw std::runtime_error("Missing type in python tool");
  1155. }
  1156. has_raw_python = true;
  1157. const auto & type = parameters.at("type");
  1158. if (type == "object") {
  1159. auto properties = parameters.at("properties");
  1160. for (auto it = properties.begin(); it != properties.end(); ++it) {
  1161. if (it.value().at("type") == "string") {
  1162. if (!python_code_argument_name.empty()) {
  1163. throw std::runtime_error("Multiple string arguments found in python tool");
  1164. }
  1165. python_code_argument_name = it.key();
  1166. }
  1167. }
  1168. if (python_code_argument_name.empty()) {
  1169. throw std::runtime_error("No string argument found in python tool");
  1170. }
  1171. } else if (type != "string") {
  1172. throw std::runtime_error("Invalid type in python tool: " + type.dump());
  1173. }
  1174. }
  1175. tool_rules.push_back(builder.add_rule(name + "-call", "\"<function=" + name + ">\" " + builder.add_schema(name + "-args", parameters) + " \"</function>\" space"));
  1176. });
  1177. if (has_raw_python) {
  1178. tool_rules.push_back(builder.add_rule("python-call", "\"<|python_tag|>\" .*"));
  1179. data.grammar_triggers.push_back({"<|python_tag|>", /* .at_start = */ false});
  1180. }
  1181. auto tool_call = builder.add_rule("tool_call", string_join(tool_rules, " | ")) + " space";
  1182. builder.add_rule("root", inputs.parallel_tool_calls ? "(" + tool_call + ")+" : tool_call);
  1183. data.grammar_triggers.push_back({"<function=", /* .at_start = */ false});
  1184. }, grammar_options);
  1185. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  1186. // TODO: if (has_raw_python)
  1187. data.format = COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1;
  1188. return data;
  1189. }
  1190. static common_chat_msg common_chat_parse_functionary_v3_1_llama_3_1(const std::string & input) {
  1191. // This version of Functionary still supports the llama 3.1 tool call format for the python tool.
  1192. static std::regex python_tag_regex(R"(<\|python_tag\|>([\s\S\n]*)$)");
  1193. std::smatch match;
  1194. if (std::regex_search(input, match, python_tag_regex)) {
  1195. auto code = match[1].str();
  1196. common_chat_msg msg;
  1197. msg.role = "assistant";
  1198. msg.content = match.prefix().str();
  1199. msg.tool_calls.push_back({
  1200. /* .name = */ "python",
  1201. /* .arguments = */ (json {{"code", code}}).dump(),
  1202. /* .id = */ "",
  1203. });
  1204. return msg;
  1205. }
  1206. static std::regex function_regex(R"(<function=(\w+)>)");
  1207. static std::regex close_regex(R"(</function>)");
  1208. // TODO: tighten & simplify.
  1209. return parse_json_tool_calls(input, std::nullopt, function_regex, close_regex);
  1210. }
  1211. static common_chat_params common_chat_params_init_hermes_2_pro(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1212. common_chat_params data;
  1213. // (content)?(<tool_call>{"name": "foo", "arguments": {"a": 1}}</tool_call>)*
  1214. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  1215. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  1216. std::vector<std::string> tool_rules;
  1217. foreach_function(inputs.tools, [&](const json & tool) {
  1218. const auto & function = tool.at("function");
  1219. std::string name = function.at("name");
  1220. auto parameters = function.at("parameters");
  1221. builder.resolve_refs(parameters);
  1222. tool_rules.push_back(builder.add_schema(name + "-call", {
  1223. {"type", "object"},
  1224. {"properties", json {
  1225. {"name", json {{"const", name}}},
  1226. {"arguments", parameters},
  1227. }},
  1228. {"required", json::array({"name", "arguments"})},
  1229. }));
  1230. });
  1231. auto tool_call = "\"<tool_call>\" space " + builder.add_rule("tool_call", string_join(tool_rules, " | ")) + " \"</tool_call>\" space";
  1232. builder.add_rule("root", inputs.parallel_tool_calls ? "(" + tool_call + ")+" : tool_call);
  1233. data.grammar_triggers.push_back({"<tool_call>", /* .at_start = */ false});
  1234. data.preserved_tokens = { "</tool_call>" };
  1235. }, grammar_options);
  1236. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  1237. data.format = COMMON_CHAT_FORMAT_HERMES_2_PRO;
  1238. return data;
  1239. }
  1240. static common_chat_msg common_chat_parse_hermes_2_pro(const std::string & input) {
  1241. try {
  1242. std::regex start_pattern(R"([\n\s]*<tool_call>)");
  1243. std::regex middle_pattern(R"([\n\s]*</tool_call>[\n\s]*<tool_call>)");
  1244. std::regex end_pattern(R"([\n\s]*</tool_call>[\n\s]*$)");
  1245. common_chat_msg msg;
  1246. msg.role = "assistant";
  1247. auto end = input.end();
  1248. std::sregex_iterator rend;
  1249. std::sregex_iterator rit(input.begin(), end, start_pattern);
  1250. if (rit == rend) {
  1251. msg.content = input;
  1252. return msg;
  1253. }
  1254. msg.content = rit->prefix();
  1255. auto it = rit->suffix().first;
  1256. while (it != end) {
  1257. json call;
  1258. if (!parse_json(it, end, call)) {
  1259. throw std::runtime_error("Failed to parse json tool call");
  1260. }
  1261. const auto & arguments = call.at("arguments");
  1262. msg.tool_calls.push_back({
  1263. call.at("name"),
  1264. arguments.dump(),
  1265. // arguments.is_string() ? arguments.get<std::string>() : arguments.dump(),
  1266. /* id= */ "",
  1267. });
  1268. rit = {it, end, middle_pattern};
  1269. if (rit != rend) {
  1270. it = rit->suffix().first;
  1271. } else {
  1272. rit = {it, end, end_pattern};
  1273. if (rit == rend) {
  1274. throw std::runtime_error("Malformed input, missing </tool_call>");
  1275. }
  1276. break;
  1277. }
  1278. }
  1279. return msg;
  1280. } catch (const std::exception & e) {
  1281. LOG_ERR("Failed to parse hermes 2 pro input: %s\n", e.what());
  1282. common_chat_msg msg;
  1283. msg.role = "assistant";
  1284. msg.content = input;
  1285. return msg;
  1286. }
  1287. }
  1288. static common_chat_params common_chat_params_init_without_tools(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1289. common_chat_params data;
  1290. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  1291. data.format = COMMON_CHAT_FORMAT_CONTENT_ONLY;
  1292. data.grammar_lazy = false;
  1293. if (!inputs.json_schema.is_null()) {
  1294. if (!inputs.grammar.empty()) {
  1295. throw std::runtime_error("Either \"json_schema\" or \"grammar\" can be specified, but not both");
  1296. }
  1297. data.grammar = json_schema_to_grammar(inputs.json_schema);
  1298. } else {
  1299. data.grammar = inputs.grammar;
  1300. }
  1301. return data;
  1302. }
  1303. static common_chat_params common_chat_templates_apply_jinja(
  1304. const struct common_chat_templates * tmpls,
  1305. const struct common_chat_templates_inputs & inputs)
  1306. {
  1307. templates_params params;
  1308. params.tools = common_chat_tools_to_json_oaicompat<json>(inputs.tools);
  1309. const auto & tmpl = params.tools.is_array() && tmpls->template_tool_use
  1310. ? *tmpls->template_tool_use
  1311. : *tmpls->template_default;
  1312. const auto & src = tmpl.source();
  1313. const auto & caps = tmpl.original_caps();
  1314. params.messages = common_chat_msgs_to_json_oaicompat<json>(inputs.messages, /* concat_text= */ !tmpl.original_caps().requires_typed_content);
  1315. params.add_generation_prompt = inputs.add_generation_prompt;
  1316. params.extract_reasoning = inputs.extract_reasoning;
  1317. params.tool_choice = inputs.tool_choice;
  1318. params.grammar = inputs.grammar;
  1319. if (!inputs.json_schema.empty()) {
  1320. params.json_schema = json::parse(inputs.json_schema);
  1321. }
  1322. if (inputs.parallel_tool_calls && !tmpl.original_caps().supports_parallel_tool_calls) {
  1323. LOG_DBG("Disabling parallel_tool_calls because the template does not support it\n");
  1324. params.parallel_tool_calls = false;
  1325. } else {
  1326. params.parallel_tool_calls = inputs.parallel_tool_calls;
  1327. }
  1328. if (params.tools.is_array()) {
  1329. if (params.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE && !params.grammar.empty()) {
  1330. throw std::runtime_error("Cannot specify grammar with tools");
  1331. }
  1332. if (caps.supports_tool_calls && !caps.supports_tools) {
  1333. LOG_WRN("Template supports tool calls but does not natively describe tools. The fallback behaviour used may produce bad results, inspect prompt w/ --verbose & consider overriding the template.\n");
  1334. }
  1335. }
  1336. // DeepSeek R1: use handler in all cases except json schema (thinking / tools).
  1337. if (src.find("<|tool▁calls▁begin|>") != std::string::npos && params.json_schema.is_null()) {
  1338. return common_chat_params_init_deepseek_r1(tmpl, params);
  1339. }
  1340. // Command R7B: : use handler in all cases except json schema (thinking / tools).
  1341. if (src.find("<|END_THINKING|><|START_ACTION|>") != std::string::npos && params.json_schema.is_null()) {
  1342. return common_chat_params_init_command_r7b(tmpl, params);
  1343. }
  1344. // Use generic handler when mixing tools + JSON schema.
  1345. // TODO: support that mix in handlers below.
  1346. if ((params.tools.is_array() && params.json_schema.is_object())) {
  1347. return common_chat_params_init_generic(tmpl, params);
  1348. }
  1349. // Functionary prepends "all\n" to plain content outputs, so we use its handler in all cases.
  1350. if (src.find(">>>all") != std::string::npos) {
  1351. return common_chat_params_init_functionary_v3_2(tmpl, params);
  1352. }
  1353. // Firefunction v2 requires datetime and functions in the context even w/o tools, so we also use its handler in all cases.
  1354. if (src.find(" functools[") != std::string::npos) {
  1355. return common_chat_params_init_firefunction_v2(tmpl, params);
  1356. }
  1357. // Plain handler (no tools)
  1358. if (params.tools.is_null() || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_NONE) {
  1359. return common_chat_params_init_without_tools(tmpl, params);
  1360. }
  1361. // Hermes 2/3 Pro, Qwen 2.5 Instruct (w/ tools)
  1362. if (src.find("<tool_call>") != std::string::npos) {
  1363. return common_chat_params_init_hermes_2_pro(tmpl, params);
  1364. }
  1365. // Functionary v3.1 (w/ tools)
  1366. if (src.find("<|start_header_id|>") != std::string::npos
  1367. && src.find("<function=") != std::string::npos) {
  1368. return common_chat_params_init_functionary_v3_1_llama_3_1(tmpl, params);
  1369. }
  1370. // Llama 3.1, 3.2, 3.3 (w/ tools)
  1371. if (src.find("<|start_header_id|>ipython<|end_header_id|>") != std::string::npos) {
  1372. auto allow_python_tag_builtin_tools = src.find("<|python_tag|>") != std::string::npos;
  1373. return common_chat_params_init_llama_3_1_tool_calls(tmpl, params, allow_python_tag_builtin_tools);
  1374. }
  1375. // Mistral Nemo (w/ tools)
  1376. if (src.find("[TOOL_CALLS]") != std::string::npos) {
  1377. return common_chat_params_init_mistral_nemo(tmpl, params);
  1378. }
  1379. // Generic fallback
  1380. return common_chat_params_init_generic(tmpl, params);
  1381. }
  1382. // Legacy template route (adhoc C++ implementation of known templates), forward to llama_chat_apply_template.
  1383. static common_chat_params common_chat_templates_apply_legacy(
  1384. const struct common_chat_templates * tmpls,
  1385. const struct common_chat_templates_inputs & inputs)
  1386. {
  1387. int alloc_size = 0;
  1388. std::vector<llama_chat_message> chat;
  1389. std::vector<std::string> contents;
  1390. for (const auto & msg : inputs.messages) {
  1391. auto content = msg.content;
  1392. for (const auto & part : msg.content_parts) {
  1393. if (part.type != "text") {
  1394. LOG_WRN("Ignoring non-text content part: %s\n", part.type.c_str());
  1395. continue;
  1396. }
  1397. if (!content.empty()) {
  1398. content += "\n";;
  1399. }
  1400. content += part.text;
  1401. }
  1402. contents.emplace_back(std::move(content));
  1403. }
  1404. for (size_t i = 0; i < contents.size(); ++i) {
  1405. const auto & msg = inputs.messages[i];
  1406. const auto & content = contents[i];
  1407. chat.push_back({msg.role.c_str(), content.c_str()});
  1408. alloc_size += (msg.role.size() + content.size()) * 1.25;
  1409. }
  1410. std::vector<char> buf(alloc_size);
  1411. // run the first time to get the total output length
  1412. const auto & src = tmpls->template_default->source();
  1413. int32_t res = llama_chat_apply_template(src.c_str(), chat.data(), chat.size(), inputs.add_generation_prompt, buf.data(), buf.size());
  1414. // error: chat template is not supported
  1415. if (res < 0) {
  1416. // if the custom "tmpl" is not supported, we throw an error
  1417. // this is a bit redundant (for good), since we're not sure if user validated the custom template with llama_chat_verify_template()
  1418. throw std::runtime_error("this custom template is not supported");
  1419. }
  1420. // if it turns out that our buffer is too small, we resize it
  1421. if ((size_t) res > buf.size()) {
  1422. buf.resize(res);
  1423. res = llama_chat_apply_template(src.c_str(), chat.data(), chat.size(), inputs.add_generation_prompt, buf.data(), buf.size());
  1424. }
  1425. common_chat_params params;
  1426. params.prompt = std::string(buf.data(), res);
  1427. if (!inputs.json_schema.empty()) {
  1428. params.grammar = json_schema_to_grammar(json::parse(inputs.json_schema));
  1429. } else {
  1430. params.grammar = inputs.grammar;
  1431. }
  1432. return params;
  1433. }
  1434. common_chat_params common_chat_templates_apply(
  1435. const struct common_chat_templates * tmpls,
  1436. const struct common_chat_templates_inputs & inputs)
  1437. {
  1438. GGML_ASSERT(tmpls != nullptr);
  1439. return inputs.use_jinja
  1440. ? common_chat_templates_apply_jinja(tmpls, inputs)
  1441. : common_chat_templates_apply_legacy(tmpls, inputs);
  1442. }
  1443. static common_chat_msg common_chat_parse_content_only(const std::string & input) {
  1444. common_chat_msg msg;
  1445. msg.role = "assistant";
  1446. msg.content = input;
  1447. return msg;
  1448. }
  1449. common_chat_msg common_chat_parse(const std::string & input, common_chat_format format) {
  1450. switch (format) {
  1451. case COMMON_CHAT_FORMAT_CONTENT_ONLY:
  1452. return common_chat_parse_content_only(input);
  1453. case COMMON_CHAT_FORMAT_GENERIC:
  1454. return common_chat_parse_generic(input);
  1455. case COMMON_CHAT_FORMAT_MISTRAL_NEMO:
  1456. return common_chat_parse_mistral_nemo(input);
  1457. case COMMON_CHAT_FORMAT_LLAMA_3_X:
  1458. return common_chat_parse_llama_3_1(input);
  1459. case COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS:
  1460. return common_chat_parse_llama_3_1(input, /* with_builtin_tools= */ true);
  1461. case COMMON_CHAT_FORMAT_DEEPSEEK_R1:
  1462. return common_chat_parse_deepseek_r1(input, /* extract_reasoning= */ false);
  1463. case COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING:
  1464. return common_chat_parse_deepseek_r1(input, /* extract_reasoning= */ true);
  1465. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2:
  1466. return common_chat_parse_functionary_v3_2(input);
  1467. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1:
  1468. return common_chat_parse_functionary_v3_1_llama_3_1(input);
  1469. case COMMON_CHAT_FORMAT_HERMES_2_PRO:
  1470. return common_chat_parse_hermes_2_pro(input);
  1471. case COMMON_CHAT_FORMAT_FIREFUNCTION_V2:
  1472. return common_chat_parse_firefunction_v2(input);
  1473. case COMMON_CHAT_FORMAT_COMMAND_R7B:
  1474. return common_chat_parse_command_r7b(input, /* extract_reasoning= */ false);
  1475. case COMMON_CHAT_FORMAT_COMMAND_R7B_EXTRACT_REASONING:
  1476. return common_chat_parse_command_r7b(input, /* extract_reasoning= */ true);
  1477. default:
  1478. throw std::runtime_error("Unsupported format: " + common_chat_format_name(format));
  1479. }
  1480. }