chat.cpp 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762
  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. static bool parse_json(std::string::const_iterator & it, const std::string::const_iterator & end, json & out) {
  415. // // https://json.nlohmann.me/features/parsing/sax_interface/
  416. struct json_error_locator : public nlohmann::json_sax<json> {
  417. std::size_t position;
  418. bool found_error;
  419. json_error_locator() : position(0), found_error(false) {}
  420. bool parse_error(std::size_t position, const std::string &, const json::exception &) override { // NOLINT
  421. this->position = position - 1;
  422. this->found_error = true;
  423. return false;
  424. }
  425. bool null() override { return true; } // NOLINT
  426. bool boolean(bool) override { return true; } // NOLINT
  427. bool number_integer(number_integer_t) override { return true; } // NOLINT
  428. bool number_unsigned(number_unsigned_t) override { return true; } // NOLINT
  429. bool number_float(number_float_t, const string_t &) override { return true; } // NOLINT
  430. bool string(string_t &) override { return true; } // NOLINT
  431. bool binary(binary_t &) override { return true; } // NOLINT
  432. bool start_object(std::size_t) override { return true; } // NOLINT
  433. bool key(string_t &) override { return true; } // NOLINT
  434. bool end_object() override { return true; }
  435. bool start_array(std::size_t) override { return true; } // NOLINT
  436. bool end_array() override { return true; }
  437. };
  438. json_error_locator err_loc;
  439. json::sax_parse(it, end, &err_loc);
  440. std::string::const_iterator temptative_end;
  441. if (err_loc.found_error) {
  442. temptative_end = it + err_loc.position;
  443. } else {
  444. temptative_end = end;
  445. }
  446. std::string json_sub {it, temptative_end};
  447. try {
  448. out = json::parse(json_sub);
  449. it = temptative_end;
  450. return true;
  451. } catch (const std::exception &) {
  452. return false;
  453. }
  454. }
  455. static bool parse_literal(std::string::const_iterator & it, const std::string::const_iterator & end, const std::string & expected) {
  456. auto expected_it = expected.begin();
  457. auto tmp_it = it;
  458. while (tmp_it != end && expected_it != expected.end() && *tmp_it == *expected_it) {
  459. ++tmp_it;
  460. ++expected_it;
  461. }
  462. if (expected_it == expected.end()) {
  463. it = tmp_it;
  464. return true;
  465. }
  466. return false;
  467. }
  468. static std::optional<std::smatch> parse_pattern(std::string::const_iterator & it, const std::string::const_iterator & end, const std::regex & expected) {
  469. std::smatch match;
  470. if (std::regex_match(it, end, match, expected)) {
  471. it = match.suffix().first;
  472. return match;
  473. }
  474. return std::nullopt;
  475. }
  476. static void consume_spaces(std::string::const_iterator & it, const std::string::const_iterator & end) {
  477. while (it != end && std::isspace(*it)) {
  478. ++it;
  479. }
  480. }
  481. /**
  482. * Takes a prefix regex that must have 1 group to capture the function name, a closing suffix, and expects json parameters in between.
  483. * Aggregates the prefix, suffix and in-between text into the content.
  484. */
  485. static common_chat_msg parse_json_tool_calls(
  486. const std::string& input,
  487. const std::optional<std::regex> & trigger_opt,
  488. const std::regex & function_regex,
  489. const std::regex & close_regex,
  490. bool allow_raw_python = false) {
  491. std::smatch match;
  492. common_chat_msg result;
  493. result.role = "assistant";
  494. auto end = input.end();
  495. auto it = input.begin();
  496. if (trigger_opt) {
  497. if (!std::regex_search(it, end, match, *trigger_opt)) {
  498. result.content = input;
  499. return result;
  500. }
  501. result.content = match.prefix().str();
  502. it = match.suffix().first;
  503. }
  504. while (it != end) {
  505. std::sregex_iterator rend;
  506. std::sregex_iterator rit(it, end, function_regex);
  507. if (rit == rend) {
  508. result.content += std::string(it, end);
  509. break;
  510. }
  511. auto name = rit->str(1);
  512. result.content += std::string(it, rit->prefix().second);
  513. it = rit->suffix().first;
  514. json arguments;
  515. if (parse_json(it, end, arguments)) {
  516. if (!std::regex_search(it, end, match, close_regex)) {
  517. throw std::runtime_error("Malformed input, missing closing pattern: " + input);
  518. }
  519. it = match.suffix().first;
  520. result.tool_calls.push_back({name, arguments.is_string() ? arguments.get<std::string>() : arguments.dump(), /* id= */ ""});
  521. } else {
  522. if (allow_raw_python && name == "python") {
  523. result.tool_calls.push_back({name, json({{"code", std::string(it, end)}}).dump(), /* id= */ ""});
  524. break;
  525. }
  526. throw std::runtime_error("Failed to parse json tool call arguments: " + input);
  527. }
  528. }
  529. if (!result.tool_calls.empty()) {
  530. if (!string_strip(result.content).empty()) {
  531. LOG_WRN("Content found with tool calls: %s\n", result.content.c_str());
  532. }
  533. result.content = "";
  534. }
  535. return result;
  536. }
  537. static common_chat_tool_call process_tool_call(const json & tool_call) {
  538. const auto & arguments = tool_call.at("arguments");
  539. return {
  540. /* .name = */ tool_call.at("name"),
  541. /* .arguments = */ arguments.is_string() ? arguments.get<std::string>() : arguments.dump(),
  542. /* .id = */ tool_call.contains("id") ? tool_call.at("id") : "",
  543. };
  544. }
  545. static common_chat_msg parse_prefixed_json_tool_call_array(const std::string& input, const std::string & prefix, size_t rstrip_prefix = 0) {
  546. auto content_end = input.find(prefix);
  547. size_t tc_start = std::string::npos;
  548. common_chat_msg result;
  549. result.role = "assistant";
  550. if (content_end == std::string::npos) {
  551. result.content = input;
  552. } else {
  553. tc_start = content_end + prefix.size() - rstrip_prefix;
  554. result.content = input.substr(0, content_end);
  555. auto tool_calls = json::parse(input.substr(tc_start));
  556. for (const auto & tool_call : tool_calls) {
  557. result.tool_calls.emplace_back(process_tool_call(tool_call));
  558. }
  559. }
  560. return result;
  561. }
  562. static void foreach_function(const json & tools, const std::function<void(const json &)> & fn) {
  563. for (const auto & tool : tools) {
  564. if (!tool.contains("type") || tool.at("type") != "function" || !tool.contains("function")) {
  565. LOG_INF("Skipping tool without function: %s", tool.dump(2).c_str());
  566. continue;
  567. }
  568. fn(tool);
  569. }
  570. }
  571. static std::string apply(
  572. const common_chat_template & tmpl,
  573. const nlohmann::ordered_json & messages,
  574. const nlohmann::ordered_json & tools,
  575. bool add_generation_prompt,
  576. const nlohmann::ordered_json & extra_context = nlohmann::ordered_json())
  577. {
  578. minja::chat_template_inputs tmpl_inputs;
  579. tmpl_inputs.messages = messages;
  580. tmpl_inputs.tools = tools;
  581. tmpl_inputs.add_generation_prompt = add_generation_prompt;
  582. tmpl_inputs.extra_context = extra_context;
  583. // TODO: add flag to control date/time, if only for testing purposes.
  584. // tmpl_inputs.now = std::chrono::system_clock::now();
  585. minja::chat_template_options tmpl_opts;
  586. // To avoid double BOS / EOS tokens, we're manually removing begining / trailing tokens
  587. // instead of using `chat_template_options.use_bos_token = false`, since these tokens
  588. // may be needed inside the template / between messages too.
  589. auto result = tmpl.apply(tmpl_inputs, tmpl_opts);
  590. if (string_starts_with(result, tmpl.bos_token())) {
  591. result = result.substr(tmpl.bos_token().size());
  592. }
  593. if (string_ends_with(result, tmpl.eos_token())) {
  594. result = result.substr(0, result.size() - tmpl.eos_token().size());
  595. }
  596. return result;
  597. }
  598. static common_chat_params common_chat_params_init_generic(const common_chat_template & tmpl, const struct templates_params & inputs) {
  599. common_chat_params data;
  600. auto tool_call_schemas = json::array();
  601. foreach_function(inputs.tools, [&](const json & tool) {
  602. const auto & function = tool.at("function");
  603. auto tool_schema = json {
  604. {"type", "object"},
  605. {"properties", {
  606. {"name", {
  607. {"type", "string"},
  608. {"const", function.at("name")},
  609. }},
  610. {"arguments", function.at("parameters")},
  611. }},
  612. {"required", json::array({"name", "arguments"})},
  613. };
  614. if (function.contains("description")) {
  615. tool_schema["description"] = function.at("description");
  616. }
  617. if (inputs.parallel_tool_calls) {
  618. tool_schema.at("properties")["id"] = {
  619. {"type", "string"},
  620. {"minLength", 4},
  621. };
  622. tool_schema.at("required").push_back("id");
  623. }
  624. tool_call_schemas.emplace_back(tool_schema);
  625. });
  626. const auto tool_call =
  627. inputs.parallel_tool_calls
  628. ? json {
  629. {"type", "object"},
  630. {"properties", {
  631. {"tool_calls", {
  632. {"type", "array"},
  633. {"items", tool_call_schemas.size() == 1 ? tool_call_schemas[0] : json {
  634. {"anyOf", tool_call_schemas},
  635. }},
  636. {"minItems", 1},
  637. }},
  638. }},
  639. {"required", json::array({"tool_calls"})},
  640. }
  641. : json {
  642. {"type", "object"},
  643. {"properties", {
  644. {"tool_call", tool_call_schemas.size() == 1 ? tool_call_schemas[0] : json {
  645. {"anyOf", tool_call_schemas},
  646. }},
  647. }},
  648. {"required", json::array({"tool_call"})},
  649. };
  650. const auto schema =
  651. inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED
  652. ? json {
  653. {"anyOf", json::array({
  654. tool_call,
  655. {
  656. {"type", "object"},
  657. {"properties", {
  658. {"response", inputs.json_schema.is_null()
  659. ? json {{"type", "string"}}
  660. : inputs.json_schema
  661. },
  662. }},
  663. {"required", json::array({"response"})},
  664. },
  665. })}
  666. }
  667. : tool_call;
  668. data.grammar_lazy = false;
  669. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  670. builder.add_schema("root", schema);
  671. });
  672. auto tweaked_messages = common_chat_template::add_system(
  673. inputs.messages,
  674. "Respond in JSON format, either with `tool_call` (a request to call tools) or with `response` reply to the user's request");
  675. data.prompt = apply(tmpl, tweaked_messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  676. data.format = COMMON_CHAT_FORMAT_GENERIC;
  677. return data;
  678. }
  679. static common_chat_msg common_chat_parse_generic(const std::string & input) {
  680. json data = json::parse(input);
  681. common_chat_msg result;
  682. result.role = "assistant";
  683. if (data.contains("tool_calls")) {
  684. for (const auto & tool_call : data.at("tool_calls")) {
  685. result.tool_calls.push_back({
  686. tool_call.at("name"),
  687. tool_call.at("arguments").dump(),
  688. tool_call.contains("id") ? tool_call.at("id") : "",
  689. });
  690. }
  691. } else if (data.contains("tool_call")) {
  692. result.tool_calls.push_back({
  693. data.at("tool_call").at("name"),
  694. data.at("tool_call").at("arguments").dump(),
  695. /* id= */ "",
  696. });
  697. } else if (data.contains("response")) {
  698. const auto & response = data.at("response");
  699. result.content = response.is_string() ? response.get<std::string>() : response.dump(2);
  700. }
  701. return result;
  702. }
  703. static common_chat_params common_chat_params_init_mistral_nemo(const common_chat_template & tmpl, const struct templates_params & inputs) {
  704. common_chat_params data;
  705. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  706. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  707. auto schemas = json::array();
  708. foreach_function(inputs.tools, [&](const json & tool) {
  709. const auto & function = tool.at("function");
  710. schemas.push_back({
  711. {"type", "object"},
  712. {"properties", {
  713. // Important note: the model is probably trained to take a JSON stringified arguments value.
  714. // It's hard to constrain that for now (while reusing the JSON schema conversion), so we're just expecting a plain object.
  715. {"name", {
  716. {"type", "string"},
  717. {"const", function.at("name")},
  718. }},
  719. {"arguments", function.at("parameters")},
  720. {"id", {
  721. {"type", "string"},
  722. // Nemo's template expects a 9-character alphanumeric ID.
  723. {"pattern", "^[a-zA-Z0-9]{9}$"},
  724. }},
  725. }},
  726. {"required", json::array({"name", "arguments", "id"})},
  727. });
  728. });
  729. auto schema = json {
  730. {"type", "array"},
  731. {"items", schemas.size() == 1 ? schemas[0] : json {{"anyOf", schemas}}},
  732. {"minItems", 1},
  733. };
  734. if (!inputs.parallel_tool_calls) {
  735. schema["maxItems"] = 1;
  736. }
  737. builder.add_rule("root", "\"[TOOL_CALLS]\" " + builder.add_schema("tool_calls", schema));
  738. });
  739. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "[TOOL_CALLS]"});
  740. data.preserved_tokens = {
  741. "[TOOL_CALLS]",
  742. };
  743. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  744. data.format = COMMON_CHAT_FORMAT_MISTRAL_NEMO;
  745. return data;
  746. }
  747. static common_chat_msg common_chat_parse_mistral_nemo(const std::string & input) {
  748. return parse_prefixed_json_tool_call_array(input, "[TOOL_CALLS]");
  749. }
  750. static common_chat_params common_chat_params_init_command_r7b(const common_chat_template & tmpl, const struct templates_params & inputs) {
  751. common_chat_params data;
  752. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  753. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  754. auto schemas = json::array();
  755. foreach_function(inputs.tools, [&](const json & tool) {
  756. const auto & function = tool.at("function");
  757. schemas.push_back({
  758. {"type", "object"},
  759. {"properties", {
  760. {"tool_call_id", {
  761. {"type", "string"},
  762. // Command-R's template expects an integer string.
  763. {"pattern", "^[0-9]{1,10}$"},
  764. }},
  765. {"tool_name", {
  766. {"type", "string"},
  767. {"const", function.at("name")},
  768. }},
  769. {"parameters", function.at("parameters")},
  770. }},
  771. {"required", json::array({"tool_call_id", "tool_name", "parameters"})},
  772. });
  773. });
  774. auto schema = json {
  775. {"type", "array"},
  776. {"items", schemas.size() == 1 ? schemas[0] : json {{"anyOf", schemas}}},
  777. {"minItems", 1},
  778. };
  779. if (!inputs.parallel_tool_calls) {
  780. schema["maxItems"] = 1;
  781. }
  782. builder.add_rule("root", "\"<|START_ACTION|>\" " + builder.add_schema("tool_calls", schema) + " \"<|END_ACTION|>\"");
  783. });
  784. data.grammar_triggers.push_back({
  785. COMMON_GRAMMAR_TRIGGER_TYPE_WORD,
  786. "<|START_ACTION|>",
  787. });
  788. data.preserved_tokens = {
  789. "<|START_ACTION|>",
  790. "<|END_ACTION|>",
  791. "<|START_RESPONSE|>",
  792. "<|END_RESPONSE|>",
  793. "<|START_THINKING|>",
  794. "<|END_THINKING|>",
  795. };
  796. auto adjusted_messages = json::array();
  797. for (const auto & msg : inputs.messages) {
  798. auto has_reasoning_content = msg.contains("reasoning_content") && msg.at("reasoning_content").is_string();
  799. auto has_tool_calls = msg.contains("tool_calls") && msg.at("tool_calls").is_array();
  800. if (has_reasoning_content && has_tool_calls) {
  801. auto adjusted_message = msg;
  802. adjusted_message["tool_plan"] = msg.at("reasoning_content");
  803. adjusted_message.erase("reasoning_content");
  804. adjusted_messages.push_back(adjusted_message);
  805. } else {
  806. adjusted_messages.push_back(msg);
  807. }
  808. }
  809. data.prompt = apply(tmpl, adjusted_messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt, {});
  810. data.format = inputs.extract_reasoning ? COMMON_CHAT_FORMAT_COMMAND_R7B_EXTRACT_REASONING : COMMON_CHAT_FORMAT_COMMAND_R7B;
  811. return data;
  812. }
  813. static common_chat_msg common_chat_parse_command_r7b(const std::string & input, bool extract_reasoning) {
  814. static std::regex thought_regex("(<\\|START_THINKING\\|>([\\s\\S]*?)<\\|END_THINKING\\|>)([\\s\\S]*)");
  815. static std::regex action_regex("<\\|START_ACTION\\|>([\\s\\S]*?)<\\|END_ACTION\\|>");
  816. static std::regex response_regex("(?:<\\|START_RESPONSE\\|>)?([\\s\\S]*?)<\\|END_RESPONSE\\|>");
  817. std::smatch match;
  818. common_chat_msg result;
  819. result.role = "assistant";
  820. std::string rest = input;
  821. if (std::regex_match(rest, match, thought_regex)) {
  822. if (extract_reasoning) {
  823. result.reasoning_content = match[2].str();
  824. } else if (!match[2].str().empty()) {
  825. // Let the unparsed thinking tags through in content only if their insides aren't empty.
  826. result.content = match[1].str();
  827. }
  828. rest = match[3].str();
  829. }
  830. if (std::regex_match(rest, match, action_regex)) {
  831. auto actions_str = match[1].str();
  832. auto actions = json::parse(actions_str);
  833. for (const auto & action : actions) {
  834. result.tool_calls.push_back({
  835. /* .name = */ action.at("tool_name"),
  836. /* .arguments = */ action.at("parameters").dump(),
  837. /* .id = */ action.at("tool_call_id"),
  838. });
  839. }
  840. } else if (std::regex_match(rest, match, response_regex)) {
  841. auto response = match[1].str();
  842. result.content += response;
  843. } else {
  844. result.content += rest;
  845. }
  846. return result;
  847. }
  848. static void expect_tool_parameters(const std::string & name, const json & parameters, const std::vector<std::string> & expected_properties) {
  849. if (!parameters.is_object() || !parameters.contains("type") || parameters.at("type") != "object" || !parameters.contains("properties") || !parameters.contains("required")) {
  850. throw std::runtime_error("Parameters of tool " + name + " must be an object w/ required properties");
  851. }
  852. const auto & parameters_properties = parameters.at("properties");
  853. const auto & parameters_required = parameters.at("required");
  854. for (const auto & prop : expected_properties) {
  855. if (!parameters_properties.contains(prop)) {
  856. throw std::runtime_error("Parameters of tool " + name + " is missing property: " + prop); // NOLINT
  857. }
  858. if (std::find(parameters_required.begin(), parameters_required.end(), json(prop)) == parameters_required.end()) {
  859. throw std::runtime_error("Parameters of tool " + name + " must have property marked as required: " + prop); // NOLINT
  860. }
  861. }
  862. if (parameters_properties.size() != expected_properties.size()) {
  863. throw std::runtime_error("Parameters of tool " + name + " must only have these properties:" + string_join(expected_properties, ", "));
  864. }
  865. }
  866. 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) {
  867. auto builtin_tools = json::array();
  868. common_chat_params data;
  869. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  870. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  871. std::vector<std::string> tool_rules;
  872. auto handle_builtin_tool = [&](const std::string & name, const json & parameters) {
  873. if (name == "wolfram_alpha" || name == "web_search" || name == "brave_search") {
  874. // https://github.com/meta-llama/llama-stack/blob/main/llama_stack/providers/remote/tool_runtime/wolfram_alpha/wolfram_alpha.py
  875. // https://github.com/meta-llama/llama-stack/blob/main/llama_stack/providers/remote/tool_runtime/brave_search/brave_search.py
  876. expect_tool_parameters(name, parameters, {"query"});
  877. } else if (name == "python" || name == "code_interpreter") {
  878. // https://github.com/meta-llama/llama-stack/blob/main/llama_stack/providers/inline/tool_runtime/code_interpreter/code_interpreter.py
  879. expect_tool_parameters(name, parameters, {"code"});
  880. } else {
  881. return false;
  882. }
  883. std::vector<std::string> kvs;
  884. for (const auto & [key, value] : parameters.at("properties").items()) {
  885. kvs.push_back("\"" + key + "=\" " + builder.add_schema(name + "-args-" + key, value)); // NOLINT
  886. }
  887. tool_rules.push_back(
  888. builder.add_rule(
  889. name + "-call",
  890. "\"<|python_tag|>" + name + ".call(\" " + string_join(kvs, " \", \" ") + " \")\""));
  891. builtin_tools.push_back(name);
  892. return true;
  893. };
  894. foreach_function(inputs.tools, [&](const json & tool) {
  895. const auto & function = tool.at("function");
  896. std::string name = function.at("name");
  897. auto parameters = function.at("parameters");
  898. builder.resolve_refs(parameters);
  899. // https://github.com/meta-llama/llama-stack/tree/main/llama_stack/providers/remote/tool_runtime
  900. if (allow_python_tag_builtin_tools) {
  901. handle_builtin_tool(name, parameters);
  902. }
  903. tool_rules.push_back(
  904. builder.add_rule(
  905. name + "-call",
  906. "\"{\" space "
  907. "( \"\\\"type\\\"\" space \":\" space \"\\\"function\\\"\" space \",\" space )? "
  908. " \"\\\"name\\\"\" space \":\" space \"\\\"" + name + "\\\"\" space \",\" space "
  909. " \"\\\"parameters\\\"\" space \":\" space " + builder.add_schema(name + "-args", parameters) + " "
  910. "\"}\" space"));
  911. });
  912. // Small models may hallucinate function names so we match anything (*at the start*) that looks like the JSON of a function call, regardless of the name.
  913. data.grammar_triggers.push_back({
  914. COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_START,
  915. "\\{\\s*(?:\"type\"\\s*:\\s*\"function\"\\s*,\\s*)?\"name\"\\s*:\\s*\"", // + name + "\"[\\s\\S]*",
  916. });
  917. if (!builtin_tools.empty()) {
  918. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|python_tag|>"});
  919. data.preserved_tokens.push_back("<|python_tag|>");
  920. }
  921. // Allow a few empty lines on top of the usual constrained json schema space rule.
  922. builder.add_rule("root", string_join(tool_rules, " | "));
  923. });
  924. data.additional_stops.push_back("<|eom_id|>");
  925. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt, {
  926. {"tools_in_user_message", false},
  927. {"builtin_tools", builtin_tools.empty() ? json() : builtin_tools},
  928. });
  929. data.format = allow_python_tag_builtin_tools && !builtin_tools.empty()
  930. ? COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS
  931. : COMMON_CHAT_FORMAT_LLAMA_3_X;
  932. return data;
  933. }
  934. static common_chat_msg common_chat_parse_llama_3_1(const std::string & input, bool with_builtin_tools = false) {
  935. // TODO: tighten & simplify the parser, don't accept leading text context.
  936. static std::regex function_regex(
  937. "\\s*\\{\\s*(?:\"type\"\\s*:\\s*\"function\"\\s*,\\s*)?\"name\"\\s*:\\s*\"([^\"]+)\"\\s*,\\s*\"parameters\"\\s*: ");
  938. static std::regex close_regex("\\}\\s*");
  939. static std::regex builtin_call_regex("<\\|python_tag\\|>\\s*([^.(]+)\\s*\\.\\s*call\\s*\\(\\s*([\\w]+)\\s*=\\s*([\\s\\S]*?)\\)");
  940. if (with_builtin_tools) {
  941. std::smatch match;
  942. if (std::regex_match(input, match, builtin_call_regex)) {
  943. try {
  944. auto name = match[1].str();
  945. auto arg_name = match[2].str();
  946. auto arg_value_str = match[3].str();
  947. auto arg_value = json::parse(arg_value_str);
  948. common_chat_msg msg;
  949. msg.role = "assistant";
  950. msg.tool_calls.push_back({
  951. /* .name = */ name,
  952. /* .arguments = */ (json {
  953. {arg_name, arg_value},
  954. }).dump(),
  955. /* .id = */ "",
  956. });
  957. return msg;
  958. } catch (const std::exception & e) {
  959. LOG_WRN("Failed to parse builtin tool call arguments (%s): %s", e.what(), input.c_str());
  960. }
  961. }
  962. }
  963. return parse_json_tool_calls(input, std::nullopt, function_regex, close_regex);
  964. }
  965. static common_chat_params common_chat_params_init_deepseek_r1(const common_chat_template & tmpl, const struct templates_params & inputs) {
  966. common_chat_params data;
  967. if (inputs.tools.is_array() && !inputs.tools.empty()) {
  968. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED && inputs.json_schema.is_null();
  969. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  970. std::vector<std::string> tool_rules;
  971. foreach_function(inputs.tools, [&](const json & tool) {
  972. const auto & function = tool.at("function");
  973. std::string name = function.at("name");
  974. auto parameters = function.at("parameters");
  975. builder.resolve_refs(parameters);
  976. tool_rules.push_back(builder.add_rule(name + "-call",
  977. "\"<|tool▁call▁begin|>function<|tool▁sep|>" + name + "\\n"
  978. "```json\\n\" " + builder.add_schema(name + "-args", parameters) + " "
  979. "\"```<|tool▁call▁end|>\""));
  980. });
  981. // Distill Qwen 7B & 32B models seem confused re/ syntax of their tool call opening tag,
  982. // so we accept common variants (then it's all constrained)
  983. builder.add_rule("root",
  984. "( \"<|tool▁calls▁begin|>\" | \"<|tool_calls_begin|>\" | \"<|tool calls begin|>\" | \"<|tool\\\\_calls\\\\_begin|>\" ) "
  985. "(" + string_join(tool_rules, " | ") + ")" + (inputs.parallel_tool_calls ? "*" : "") + " "
  986. "\"<|tool▁calls▁end|>\""
  987. " space");
  988. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|tool▁calls▁begin|>"});
  989. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|tool_calls_begin|>"});
  990. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|tool calls begin|>"});
  991. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|tool\\_calls\\_begin|>"});
  992. data.preserved_tokens = {
  993. "<think>",
  994. "</think>",
  995. "<|tool▁calls▁begin|>",
  996. "<|tool▁call▁begin|>",
  997. "<|tool▁sep|>",
  998. "<|tool▁call▁end|>",
  999. "<|tool▁calls▁end|",
  1000. };
  1001. });
  1002. }
  1003. auto prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  1004. // Hacks to fix the official (broken) prompt.
  1005. // It is advisable to use --chat-template-file models/templates/llama-cpp-deepseek-r1.jinja instead,
  1006. // until the official template is fixed.
  1007. if (tmpl.source().find("{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}") != std::string::npos) {
  1008. // Don't leave the chat dangling after tool results
  1009. if (string_ends_with(prompt, "<|tool▁outputs▁end|>")) {
  1010. prompt += "<|end▁of▁sentence|>";
  1011. if (inputs.add_generation_prompt) {
  1012. prompt += "<|Assistant|>";
  1013. }
  1014. }
  1015. // Fix up tool call delta example added by Minja
  1016. prompt = std::regex_replace(
  1017. prompt,
  1018. std::regex("(<|tool▁call▁end|>)[\\s\\r\\n]*(<|tool▁outputs▁begin|>|<|User|>)"),
  1019. "$1<|tool▁calls▁end|><|end▁of▁sentence|>$2");
  1020. }
  1021. data.prompt = prompt;
  1022. data.format = inputs.extract_reasoning ? COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING : COMMON_CHAT_FORMAT_DEEPSEEK_R1;
  1023. return data;
  1024. }
  1025. static common_chat_msg common_chat_parse_deepseek_r1(const std::string & input, bool extract_reasoning) {
  1026. static std::regex function_regex("<|tool▁call▁begin|>function<|tool▁sep|>([^\n]+)\n```json\n");
  1027. static std::regex close_regex("```[\\s\\r\\n]*<|tool▁call▁end|>");
  1028. static std::regex reasoning_content_regex("((?:<think>)?([\\s\\S\\r\\n]*?)</think>)?([\\s\\S\\r\\n]*)");
  1029. 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|>");
  1030. common_chat_msg msg;
  1031. msg.role = "assistant";
  1032. std::smatch match;
  1033. if (std::regex_match(input, match, reasoning_content_regex)) {
  1034. std::string rest;
  1035. if (extract_reasoning) {
  1036. msg.reasoning_content = string_strip(match[2].str());
  1037. } else {
  1038. msg.content = match[1].str();
  1039. }
  1040. rest = match[3].str();
  1041. if (std::regex_search(rest, match, tool_calls_regex)) {
  1042. auto tool_calls = match[1].str();
  1043. auto msg2 = parse_json_tool_calls(tool_calls, std::nullopt, function_regex, close_regex);
  1044. msg.tool_calls = std::move(msg2.tool_calls);
  1045. } else {
  1046. msg.content += std::string(rest.begin() + rest.find_first_not_of(" \r\n"), rest.end());
  1047. }
  1048. } else {
  1049. msg.content = input;
  1050. }
  1051. return msg;
  1052. }
  1053. static common_chat_params common_chat_params_init_firefunction_v2(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1054. LOG_DBG("%s\n", __func__);
  1055. common_chat_params data;
  1056. data.prompt = apply(tmpl, inputs.messages, /* tools= */ nullptr, inputs.add_generation_prompt, {
  1057. {"datetime", "Jan 29 2025 13:00:00 GMT"},
  1058. {"functions", json(inputs.tools.empty() ? "" : inputs.tools.dump(2))},
  1059. });
  1060. if (inputs.tools.is_array() && !inputs.tools.empty()) {
  1061. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  1062. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  1063. auto schemas = json::array();
  1064. foreach_function(inputs.tools, [&](const json & tool) {
  1065. const auto & function = tool.at("function");
  1066. schemas.push_back({
  1067. {"type", "object"},
  1068. {"properties", {
  1069. {"name", {
  1070. {"type", "string"},
  1071. {"const", function.at("name")},
  1072. }},
  1073. {"arguments", function.at("parameters")},
  1074. }},
  1075. {"required", json::array({"name", "arguments", "id"})},
  1076. });
  1077. });
  1078. auto schema = json {
  1079. {"type", "array"},
  1080. {"items", schemas.size() == 1 ? schemas[0] : json {{"anyOf", schemas}}},
  1081. {"minItems", 1},
  1082. };
  1083. if (!inputs.parallel_tool_calls) {
  1084. schema["maxItems"] = 1;
  1085. }
  1086. builder.add_rule("root", "\" functools\"? " + builder.add_schema("tool_calls", schema));
  1087. });
  1088. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, " functools["});
  1089. data.preserved_tokens = {
  1090. " functools[",
  1091. };
  1092. data.format = COMMON_CHAT_FORMAT_FIREFUNCTION_V2;
  1093. } else {
  1094. data.format = COMMON_CHAT_FORMAT_CONTENT_ONLY;
  1095. }
  1096. return data;
  1097. }
  1098. static common_chat_msg common_chat_parse_firefunction_v2(const std::string & input) {
  1099. return parse_prefixed_json_tool_call_array(input, " functools[", /* rstrip_prefix= */ 1);
  1100. }
  1101. static common_chat_params common_chat_params_init_functionary_v3_2(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1102. // >>>all\nlet's call functions>>>fn1\n{"arg1": 1...}\n>>>fn2\n{"arg1": 1...}...
  1103. // Using ">>>f1\n", ">>>f2\n"... as trigger words for the grammar
  1104. common_chat_params data;
  1105. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  1106. data.format = COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2;
  1107. if (inputs.tools.is_array() && !inputs.tools.empty()) {
  1108. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  1109. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  1110. std::vector<std::string> first_tool_rules;
  1111. std::vector<std::string> subsequent_tool_rules;
  1112. foreach_function(inputs.tools, [&](const json & tool) {
  1113. const auto & function = tool.at("function");
  1114. std::string name = function.at("name");
  1115. auto parameters = function.at("parameters");
  1116. builder.resolve_refs(parameters);
  1117. auto args_rule = builder.add_schema(name + "-args", parameters);
  1118. first_tool_rules.push_back(builder.add_rule(name + "-call", "( \"assistant<|end_header_id|>\\n\" )? \"" + name + "\\n\" " + args_rule));
  1119. subsequent_tool_rules.push_back(builder.add_rule(name + "-call2", "\">>>" + name + "\\n\" " + args_rule));
  1120. data.grammar_triggers.push_back({
  1121. COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_START,
  1122. regex_escape(name + "\n"),
  1123. });
  1124. data.grammar_triggers.push_back({
  1125. COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_START,
  1126. regex_escape("assistant<|end_header_id|>\n" + name + "\n"),
  1127. });
  1128. data.grammar_triggers.push_back({
  1129. COMMON_GRAMMAR_TRIGGER_TYPE_WORD,
  1130. regex_escape(">>>" + name + "\n"),
  1131. });
  1132. data.grammar_triggers.push_back({
  1133. COMMON_GRAMMAR_TRIGGER_TYPE_WORD,
  1134. ">>>assistant<|end_header_id|>\n" + name,
  1135. });
  1136. });
  1137. data.preserved_tokens = {
  1138. "<|end_header_id|>",
  1139. };
  1140. auto first_rule = first_tool_rules.empty() ? "" : builder.add_rule("first_tool_call", string_join(first_tool_rules, " | ")) + " space";
  1141. if (inputs.parallel_tool_calls) {
  1142. auto subsequent_rule = builder.add_rule("subsequent_tool_call", string_join(subsequent_tool_rules, " | ")) + " space";
  1143. builder.add_rule("root", first_rule + " (" + subsequent_rule + ")*");
  1144. } else {
  1145. builder.add_rule("root", first_rule);
  1146. }
  1147. });
  1148. }
  1149. return data;
  1150. }
  1151. static common_chat_msg common_chat_parse_functionary_v3_2(const std::string & input) {
  1152. static std::regex function_regex(R"((?:>>>)?(?:assistant<|end_header_id|>\n)?(\w+)\n)");
  1153. static std::regex close_regex(R"($|(?=>>>))");
  1154. std::string content;
  1155. auto it = input.begin();
  1156. const auto end = input.end();
  1157. if (parse_literal(it, end, "all\n")) {
  1158. std::smatch match;
  1159. if (std::regex_search(it, end, match, function_regex)) {
  1160. auto fun_it = match.prefix().second;
  1161. content = std::string(it, fun_it);
  1162. it = fun_it;
  1163. } else {
  1164. common_chat_msg res;
  1165. res.role = "assistant";
  1166. res.content = std::string(it, end);
  1167. return res;
  1168. }
  1169. }
  1170. // TODO: tighten & simplify.
  1171. try {
  1172. auto res = parse_json_tool_calls(std::string(it, end), std::nullopt, function_regex, close_regex, /* allow_raw_python= */ true);
  1173. res.content = content + res.content;
  1174. return res;
  1175. } catch (const std::exception & e) {
  1176. LOG_ERR("Failed to parse functionary v3.2 input: %s\n", e.what());
  1177. common_chat_msg res;
  1178. res.role = "assistant";
  1179. res.content = input;
  1180. return res;
  1181. }
  1182. }
  1183. static common_chat_params common_chat_params_init_functionary_v3_1_llama_3_1(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1184. // https://github.com/MeetKai/functionary/blob/main/tests/prompt_test_v3-llama3.1.txt
  1185. common_chat_params data;
  1186. json tools = inputs.tools.is_null() ? inputs.tools : json::array();
  1187. std::string python_code_argument_name;
  1188. auto has_raw_python = false;
  1189. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  1190. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  1191. std::vector<std::string> tool_rules;
  1192. foreach_function(inputs.tools, [&](const json & tool) {
  1193. const auto & function = tool.at("function");
  1194. const auto & parameters = function.at("parameters");
  1195. std::string name = function.at("name");
  1196. if (name == "python" || name == "ipython") {
  1197. if (!parameters.contains("type")) {
  1198. throw std::runtime_error("Missing type in python tool");
  1199. }
  1200. has_raw_python = true;
  1201. const auto & type = parameters.at("type");
  1202. if (type == "object") {
  1203. auto properties = parameters.at("properties");
  1204. for (auto it = properties.begin(); it != properties.end(); ++it) {
  1205. if (it.value().at("type") == "string") {
  1206. if (!python_code_argument_name.empty()) {
  1207. throw std::runtime_error("Multiple string arguments found in python tool");
  1208. }
  1209. python_code_argument_name = it.key();
  1210. }
  1211. }
  1212. if (python_code_argument_name.empty()) {
  1213. throw std::runtime_error("No string argument found in python tool");
  1214. }
  1215. } else if (type != "string") {
  1216. throw std::runtime_error("Invalid type in python tool: " + type.dump());
  1217. }
  1218. }
  1219. tool_rules.push_back(builder.add_rule(name + "-call", "\"<function=" + name + ">\" " + builder.add_schema(name + "-args", parameters) + " \"</function>\" space"));
  1220. });
  1221. if (has_raw_python) {
  1222. tool_rules.push_back(builder.add_rule("python-call", "\"<|python_tag|>\" .*"));
  1223. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|python_tag|>"});
  1224. data.preserved_tokens.push_back("<|python_tag|>");
  1225. }
  1226. auto tool_call = builder.add_rule("tool_call", string_join(tool_rules, " | ")) + " space";
  1227. builder.add_rule("root", inputs.parallel_tool_calls ? "(" + tool_call + ")+" : tool_call);
  1228. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<function="});
  1229. });
  1230. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  1231. // TODO: if (has_raw_python)
  1232. data.format = COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1;
  1233. return data;
  1234. }
  1235. static common_chat_msg common_chat_parse_functionary_v3_1_llama_3_1(const std::string & input) {
  1236. // This version of Functionary still supports the llama 3.1 tool call format for the python tool.
  1237. static std::regex python_tag_regex(R"(<\|python_tag\|>([\s\S\n]*)$)");
  1238. std::smatch match;
  1239. if (std::regex_search(input, match, python_tag_regex)) {
  1240. auto code = match[1].str();
  1241. common_chat_msg msg;
  1242. msg.role = "assistant";
  1243. msg.content = match.prefix().str();
  1244. msg.tool_calls.push_back({
  1245. /* .name = */ "python",
  1246. /* .arguments = */ (json {{"code", code}}).dump(),
  1247. /* .id = */ "",
  1248. });
  1249. return msg;
  1250. }
  1251. static std::regex function_regex(R"(<function=(\w+)>)");
  1252. static std::regex close_regex(R"(</function>)");
  1253. // TODO: tighten & simplify.
  1254. return parse_json_tool_calls(input, std::nullopt, function_regex, close_regex);
  1255. }
  1256. static common_chat_params common_chat_params_init_hermes_2_pro(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1257. common_chat_params data;
  1258. // (content)?(<tool_call>{"name": "foo", "arguments": {"a": 1}}</tool_call>)*
  1259. data.grammar_lazy = inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
  1260. data.grammar = build_grammar([&](const common_grammar_builder & builder) {
  1261. std::vector<std::string> tool_rules;
  1262. std::vector<std::string> tool_call_alts;
  1263. foreach_function(inputs.tools, [&](const json & tool) {
  1264. const auto & function = tool.at("function");
  1265. std::string name = function.at("name");
  1266. auto parameters = function.at("parameters");
  1267. builder.resolve_refs(parameters);
  1268. tool_rules.push_back(builder.add_schema(name + "-call", {
  1269. {"type", "object"},
  1270. {"properties", json {
  1271. {"name", json {{"const", name}}},
  1272. {"arguments", parameters},
  1273. }},
  1274. {"required", json::array({"name", "arguments"})},
  1275. }));
  1276. tool_call_alts.push_back(builder.add_rule(
  1277. name + "-function-tag",
  1278. "\"<function\" ( \"=" + name + "\" | \" name=\\\"" + name + "\\\"\" ) \">\" space " +
  1279. builder.add_schema(name + "-args", parameters) + " "
  1280. "\"</function>\" space"));
  1281. data.grammar_triggers.push_back({
  1282. COMMON_GRAMMAR_TRIGGER_TYPE_WORD,
  1283. "<function=" + name + ">",
  1284. });
  1285. auto escaped_name = regex_escape(name);
  1286. data.grammar_triggers.push_back({
  1287. COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN,
  1288. "<function\\s+name\\s*=\\s*\"" + escaped_name + "\"",
  1289. });
  1290. });
  1291. auto any_tool_call = builder.add_rule("any_tool_call", "( " + string_join(tool_rules, " | ") + " ) space");
  1292. std::vector<std::string> alt_tags {
  1293. any_tool_call,
  1294. "\"<tool_call>\" space " + any_tool_call + " \"</tool_call>\"",
  1295. // The rest is just to accommodate common "good bad" outputs.
  1296. "\"<function_call>\" space " + any_tool_call + " \"</function_call>\"",
  1297. "\"<response>\" space " + any_tool_call + " \"</response>\"",
  1298. "\"<tools>\" space " + any_tool_call + " \"</tools>\"",
  1299. "\"<json>\" space " + any_tool_call + " \"</json>\"",
  1300. "\"<xml>\" space " + any_tool_call + " \"</xml>\"",
  1301. "\"<JSON>\" space " + any_tool_call + " \"</JSON>\"",
  1302. };
  1303. auto wrappable_tool_call = builder.add_rule("wrappable_tool_call", "( " + string_join(alt_tags, " | ") + " ) space");
  1304. tool_call_alts.push_back(wrappable_tool_call);
  1305. tool_call_alts.push_back(
  1306. "( \"```\\n\" | \"```json\\n\" | \"```xml\\n\" ) space " + wrappable_tool_call + " space \"```\" space ");
  1307. auto tool_call = builder.add_rule("tool_call", string_join(tool_call_alts, " | "));
  1308. builder.add_rule("root", inputs.parallel_tool_calls ? "(" + tool_call + ")+" : tool_call);
  1309. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<tool_call>"});
  1310. data.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<function"});
  1311. // Trigger on some common known "good bad" outputs (only from the start and with a json that's about a specific argument name to avoid false positives)
  1312. data.grammar_triggers.push_back({
  1313. COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_START,
  1314. "(?:```(?:json|xml)?\n\\s*)?(?:<function_call>|<tools>|<xml><json>|<response>)?\\s*\\{\\s*\"", //name\"\\s*:\\s*\"" + escaped_name + "\"",
  1315. });
  1316. data.preserved_tokens = {
  1317. "<tool_call>",
  1318. "</tool_call>",
  1319. "<function",
  1320. "<tools>",
  1321. "</tools>",
  1322. "<response>",
  1323. "</response>",
  1324. "<function_call>",
  1325. "</function_call>",
  1326. "<json>",
  1327. "</json>",
  1328. "<JSON>",
  1329. "</JSON>",
  1330. "```",
  1331. "```json",
  1332. "```xml",
  1333. };
  1334. });
  1335. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  1336. data.format = COMMON_CHAT_FORMAT_HERMES_2_PRO;
  1337. return data;
  1338. }
  1339. static common_chat_msg common_chat_parse_hermes_2_pro(const std::string& input) {
  1340. const static std::regex open_regex(
  1341. "(?:"
  1342. "(```(?:xml|json)?\\n\\s*)?" // match 1 (block_start)
  1343. "(<tool_call>" // match 2 (open_tag)
  1344. "|<function_call>"
  1345. "|<tool>"
  1346. "|<tools>"
  1347. "|<response>"
  1348. "|<json>"
  1349. "|<xml>"
  1350. "|<JSON>"
  1351. ")?"
  1352. "(\\s*\\{\\s*\"name\"\\s*:[\\s\\S]*)" // match 3 (named tool call + rest)
  1353. ")"
  1354. "|"
  1355. "(?:<function=([^>]+)>" // match 4 (function name)
  1356. "|<function name=\"([^\"]+)\">)" // match 5 (function name again)
  1357. "([\\s\\S]*)" // match 6 (function arguments + rest)})"
  1358. );
  1359. try {
  1360. common_chat_msg msg;
  1361. msg.role = "assistant";
  1362. std::string::const_iterator it = input.begin();
  1363. const std::string::const_iterator end = input.end();
  1364. std::smatch match;
  1365. while (it != end) {
  1366. if (std::regex_search(it, end, match, open_regex)) {
  1367. // Add content before the match
  1368. msg.content += std::string(it, match[0].first);
  1369. auto block_start = match[1].str();
  1370. std::string block_end = block_start.empty() ? "" : "```";
  1371. auto open_tag = match[2].str();
  1372. std::string close_tag;
  1373. if (match[3].matched) {
  1374. close_tag = open_tag.empty() ? "" : "</" + open_tag.substr(1);
  1375. auto json_it = match[3].first;
  1376. json tool_call;
  1377. if (parse_json(json_it, end, tool_call) && tool_call.contains("name") && tool_call.contains("arguments")) {
  1378. msg.tool_calls.emplace_back(process_tool_call(tool_call));
  1379. it = json_it; // Move iterator past parsed JSON
  1380. // Handle close tags
  1381. consume_spaces(it, end);
  1382. if (!close_tag.empty() && !parse_literal(it, end, close_tag)) {
  1383. throw std::runtime_error("Failed to parse closing tag");
  1384. }
  1385. consume_spaces(it, end);
  1386. if (!block_end.empty() && !parse_literal(it, end, block_end)) {
  1387. throw std::runtime_error("Failed to parse block end");
  1388. }
  1389. consume_spaces(it, end);
  1390. } else {
  1391. // Not a valid tool call, treat as content
  1392. msg.content += std::string(match[0].first, match[0].second);
  1393. it = match[0].second;
  1394. }
  1395. } else {
  1396. auto function_name = match[4].str();
  1397. if (function_name.empty()) {
  1398. function_name = match[5].str();
  1399. }
  1400. GGML_ASSERT(!function_name.empty());
  1401. close_tag = "</function>";
  1402. // Start parsing from after the opening tags
  1403. auto json_it = match[6].first;
  1404. json arguments;
  1405. if (parse_json(json_it, end, arguments)) {
  1406. msg.tool_calls.emplace_back(process_tool_call({
  1407. {"name", function_name},
  1408. {"arguments", arguments},
  1409. }));
  1410. it = json_it; // Move iterator past parsed JSON
  1411. // Handle close tags
  1412. consume_spaces(it, end);
  1413. if (!close_tag.empty() && !parse_literal(it, end, close_tag)) {
  1414. throw std::runtime_error("Failed to parse closing tag");
  1415. }
  1416. consume_spaces(it, end);
  1417. if (!block_end.empty() && !parse_literal(it, end, block_end)) {
  1418. throw std::runtime_error("Failed to parse block end");
  1419. }
  1420. consume_spaces(it, end);
  1421. } else {
  1422. // Not a valid tool call, treat as content
  1423. msg.content += std::string(match[0].first, match[0].second);
  1424. it = match[0].second;
  1425. }
  1426. }
  1427. } else {
  1428. // Add remaining content
  1429. msg.content += std::string(it, end);
  1430. break;
  1431. }
  1432. }
  1433. return msg;
  1434. } catch (const std::exception & e) {
  1435. LOG_ERR("Failed to parse hermes 2 pro input: %s\n", e.what());
  1436. common_chat_msg msg;
  1437. msg.role = "assistant";
  1438. msg.content = input;
  1439. return msg;
  1440. }
  1441. }
  1442. static common_chat_params common_chat_params_init_without_tools(const common_chat_template & tmpl, const struct templates_params & inputs) {
  1443. common_chat_params data;
  1444. data.prompt = apply(tmpl, inputs.messages, inputs.tools.empty() ? json() : inputs.tools, inputs.add_generation_prompt);
  1445. data.format = COMMON_CHAT_FORMAT_CONTENT_ONLY;
  1446. data.grammar_lazy = false;
  1447. if (!inputs.json_schema.is_null()) {
  1448. if (!inputs.grammar.empty()) {
  1449. throw std::runtime_error("Either \"json_schema\" or \"grammar\" can be specified, but not both");
  1450. }
  1451. data.grammar = json_schema_to_grammar(inputs.json_schema);
  1452. } else {
  1453. data.grammar = inputs.grammar;
  1454. }
  1455. return data;
  1456. }
  1457. static common_chat_params common_chat_templates_apply_jinja(
  1458. const struct common_chat_templates * tmpls,
  1459. const struct common_chat_templates_inputs & inputs)
  1460. {
  1461. templates_params params;
  1462. params.tools = common_chat_tools_to_json_oaicompat<json>(inputs.tools);
  1463. const auto & tmpl = params.tools.is_array() && tmpls->template_tool_use
  1464. ? *tmpls->template_tool_use
  1465. : *tmpls->template_default;
  1466. const auto & src = tmpl.source();
  1467. const auto & caps = tmpl.original_caps();
  1468. params.messages = common_chat_msgs_to_json_oaicompat<json>(inputs.messages, /* concat_text= */ !tmpl.original_caps().requires_typed_content);
  1469. params.add_generation_prompt = inputs.add_generation_prompt;
  1470. params.extract_reasoning = inputs.extract_reasoning;
  1471. params.tool_choice = inputs.tool_choice;
  1472. params.grammar = inputs.grammar;
  1473. if (!inputs.json_schema.empty()) {
  1474. params.json_schema = json::parse(inputs.json_schema);
  1475. }
  1476. if (inputs.parallel_tool_calls && !tmpl.original_caps().supports_parallel_tool_calls) {
  1477. LOG_DBG("Disabling parallel_tool_calls because the template does not support it\n");
  1478. params.parallel_tool_calls = false;
  1479. } else {
  1480. params.parallel_tool_calls = inputs.parallel_tool_calls;
  1481. }
  1482. if (params.tools.is_array()) {
  1483. if (params.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE && !params.grammar.empty()) {
  1484. throw std::runtime_error("Cannot specify grammar with tools");
  1485. }
  1486. if (caps.supports_tool_calls && !caps.supports_tools) {
  1487. 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");
  1488. }
  1489. }
  1490. // DeepSeek R1: use handler in all cases except json schema (thinking / tools).
  1491. if (src.find("<|tool▁calls▁begin|>") != std::string::npos && params.json_schema.is_null()) {
  1492. return common_chat_params_init_deepseek_r1(tmpl, params);
  1493. }
  1494. // Command R7B: : use handler in all cases except json schema (thinking / tools).
  1495. if (src.find("<|END_THINKING|><|START_ACTION|>") != std::string::npos && params.json_schema.is_null()) {
  1496. return common_chat_params_init_command_r7b(tmpl, params);
  1497. }
  1498. // Use generic handler when mixing tools + JSON schema.
  1499. // TODO: support that mix in handlers below.
  1500. if ((params.tools.is_array() && params.json_schema.is_object())) {
  1501. return common_chat_params_init_generic(tmpl, params);
  1502. }
  1503. // Functionary prepends "all\n" to plain content outputs, so we use its handler in all cases.
  1504. if (src.find(">>>all") != std::string::npos) {
  1505. return common_chat_params_init_functionary_v3_2(tmpl, params);
  1506. }
  1507. // Firefunction v2 requires datetime and functions in the context even w/o tools, so we also use its handler in all cases.
  1508. if (src.find(" functools[") != std::string::npos) {
  1509. return common_chat_params_init_firefunction_v2(tmpl, params);
  1510. }
  1511. // Plain handler (no tools)
  1512. if (params.tools.is_null() || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_NONE) {
  1513. return common_chat_params_init_without_tools(tmpl, params);
  1514. }
  1515. // Hermes 2/3 Pro, Qwen 2.5 Instruct (w/ tools)
  1516. if (src.find("<tool_call>") != std::string::npos) {
  1517. return common_chat_params_init_hermes_2_pro(tmpl, params);
  1518. }
  1519. // Functionary v3.1 (w/ tools)
  1520. if (src.find("<|start_header_id|>") != std::string::npos
  1521. && src.find("<function=") != std::string::npos) {
  1522. return common_chat_params_init_functionary_v3_1_llama_3_1(tmpl, params);
  1523. }
  1524. // Llama 3.1, 3.2, 3.3 (w/ tools)
  1525. if (src.find("<|start_header_id|>ipython<|end_header_id|>") != std::string::npos) {
  1526. auto allow_python_tag_builtin_tools = src.find("<|python_tag|>") != std::string::npos;
  1527. return common_chat_params_init_llama_3_1_tool_calls(tmpl, params, allow_python_tag_builtin_tools);
  1528. }
  1529. // Mistral Nemo (w/ tools)
  1530. if (src.find("[TOOL_CALLS]") != std::string::npos) {
  1531. return common_chat_params_init_mistral_nemo(tmpl, params);
  1532. }
  1533. // Generic fallback
  1534. return common_chat_params_init_generic(tmpl, params);
  1535. }
  1536. // Legacy template route (adhoc C++ implementation of known templates), forward to llama_chat_apply_template.
  1537. static common_chat_params common_chat_templates_apply_legacy(
  1538. const struct common_chat_templates * tmpls,
  1539. const struct common_chat_templates_inputs & inputs)
  1540. {
  1541. int alloc_size = 0;
  1542. std::vector<llama_chat_message> chat;
  1543. std::vector<std::string> contents;
  1544. for (const auto & msg : inputs.messages) {
  1545. auto content = msg.content;
  1546. for (const auto & part : msg.content_parts) {
  1547. if (part.type != "text") {
  1548. LOG_WRN("Ignoring non-text content part: %s\n", part.type.c_str());
  1549. continue;
  1550. }
  1551. if (!content.empty()) {
  1552. content += "\n";;
  1553. }
  1554. content += part.text;
  1555. }
  1556. contents.emplace_back(std::move(content));
  1557. }
  1558. for (size_t i = 0; i < contents.size(); ++i) {
  1559. const auto & msg = inputs.messages[i];
  1560. const auto & content = contents[i];
  1561. chat.push_back({msg.role.c_str(), content.c_str()});
  1562. alloc_size += (msg.role.size() + content.size()) * 1.25;
  1563. }
  1564. std::vector<char> buf(alloc_size);
  1565. // run the first time to get the total output length
  1566. const auto & src = tmpls->template_default->source();
  1567. int32_t res = llama_chat_apply_template(src.c_str(), chat.data(), chat.size(), inputs.add_generation_prompt, buf.data(), buf.size());
  1568. // error: chat template is not supported
  1569. if (res < 0) {
  1570. // if the custom "tmpl" is not supported, we throw an error
  1571. // this is a bit redundant (for good), since we're not sure if user validated the custom template with llama_chat_verify_template()
  1572. throw std::runtime_error("this custom template is not supported");
  1573. }
  1574. // if it turns out that our buffer is too small, we resize it
  1575. if ((size_t) res > buf.size()) {
  1576. buf.resize(res);
  1577. res = llama_chat_apply_template(src.c_str(), chat.data(), chat.size(), inputs.add_generation_prompt, buf.data(), buf.size());
  1578. }
  1579. common_chat_params params;
  1580. params.prompt = std::string(buf.data(), res);
  1581. if (!inputs.json_schema.empty()) {
  1582. params.grammar = json_schema_to_grammar(json::parse(inputs.json_schema));
  1583. } else {
  1584. params.grammar = inputs.grammar;
  1585. }
  1586. return params;
  1587. }
  1588. common_chat_params common_chat_templates_apply(
  1589. const struct common_chat_templates * tmpls,
  1590. const struct common_chat_templates_inputs & inputs)
  1591. {
  1592. GGML_ASSERT(tmpls != nullptr);
  1593. return inputs.use_jinja
  1594. ? common_chat_templates_apply_jinja(tmpls, inputs)
  1595. : common_chat_templates_apply_legacy(tmpls, inputs);
  1596. }
  1597. static common_chat_msg common_chat_parse_content_only(const std::string & input) {
  1598. common_chat_msg msg;
  1599. msg.role = "assistant";
  1600. msg.content = input;
  1601. return msg;
  1602. }
  1603. common_chat_msg common_chat_parse(const std::string & input, common_chat_format format) {
  1604. switch (format) {
  1605. case COMMON_CHAT_FORMAT_CONTENT_ONLY:
  1606. return common_chat_parse_content_only(input);
  1607. case COMMON_CHAT_FORMAT_GENERIC:
  1608. return common_chat_parse_generic(input);
  1609. case COMMON_CHAT_FORMAT_MISTRAL_NEMO:
  1610. return common_chat_parse_mistral_nemo(input);
  1611. case COMMON_CHAT_FORMAT_LLAMA_3_X:
  1612. return common_chat_parse_llama_3_1(input);
  1613. case COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS:
  1614. return common_chat_parse_llama_3_1(input, /* with_builtin_tools= */ true);
  1615. case COMMON_CHAT_FORMAT_DEEPSEEK_R1:
  1616. return common_chat_parse_deepseek_r1(input, /* extract_reasoning= */ false);
  1617. case COMMON_CHAT_FORMAT_DEEPSEEK_R1_EXTRACT_REASONING:
  1618. return common_chat_parse_deepseek_r1(input, /* extract_reasoning= */ true);
  1619. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2:
  1620. return common_chat_parse_functionary_v3_2(input);
  1621. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1:
  1622. return common_chat_parse_functionary_v3_1_llama_3_1(input);
  1623. case COMMON_CHAT_FORMAT_HERMES_2_PRO:
  1624. return common_chat_parse_hermes_2_pro(input);
  1625. case COMMON_CHAT_FORMAT_FIREFUNCTION_V2:
  1626. return common_chat_parse_firefunction_v2(input);
  1627. case COMMON_CHAT_FORMAT_COMMAND_R7B:
  1628. return common_chat_parse_command_r7b(input, /* extract_reasoning= */ false);
  1629. case COMMON_CHAT_FORMAT_COMMAND_R7B_EXTRACT_REASONING:
  1630. return common_chat_parse_command_r7b(input, /* extract_reasoning= */ true);
  1631. default:
  1632. throw std::runtime_error("Unsupported format: " + common_chat_format_name(format));
  1633. }
  1634. }