chat.cpp 78 KB

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