chat.cpp 79 KB

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