chat.cpp 76 KB

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