chat-parser.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. #include "chat-parser.h"
  2. #include "chat-peg-parser.h"
  3. #include "common.h"
  4. #include "log.h"
  5. #include "peg-parser.h"
  6. #include "regex-partial.h"
  7. #include <algorithm>
  8. #include <cctype>
  9. #include <optional>
  10. #include <stdexcept>
  11. #include <string>
  12. #include <string_view>
  13. #include <vector>
  14. using json = nlohmann::ordered_json;
  15. static void parse_prefixed_json_tool_call_array(common_chat_msg_parser & builder,
  16. const common_regex & prefix,
  17. size_t rstrip_prefix = 0) {
  18. static const std::vector<std::vector<std::string>> args_paths = { { "arguments" } };
  19. if (auto res = builder.try_find_regex(prefix)) {
  20. builder.move_back(rstrip_prefix);
  21. auto tool_calls = builder.consume_json_with_dumped_args(args_paths);
  22. if (!builder.add_tool_calls(tool_calls.value) || tool_calls.is_partial) {
  23. throw common_chat_msg_partial_exception("incomplete tool call array");
  24. }
  25. } else {
  26. builder.add_content(builder.consume_rest());
  27. }
  28. }
  29. static std::string wrap_code_as_arguments(common_chat_msg_parser & builder, const std::string & code) {
  30. std::string arguments;
  31. if (builder.is_partial()) {
  32. arguments = (json{
  33. { "code", code + builder.healing_marker() }
  34. })
  35. .dump();
  36. auto idx = arguments.find(builder.healing_marker());
  37. if (idx != std::string::npos) {
  38. arguments.resize(idx);
  39. }
  40. } else {
  41. arguments = (json{
  42. { "code", code }
  43. })
  44. .dump();
  45. }
  46. return arguments;
  47. }
  48. /**
  49. * Takes a prefix regex that must have 1 group to capture the function name, a closing suffix, and expects json parameters in between.
  50. * Aggregates the prefix, suffix and in-between text into the content.
  51. */
  52. static void parse_json_tool_calls(
  53. common_chat_msg_parser & builder,
  54. const std::optional<common_regex> & block_open,
  55. const std::optional<common_regex> & function_regex_start_only,
  56. const std::optional<common_regex> & function_regex,
  57. const common_regex & close_regex,
  58. const std::optional<common_regex> & block_close,
  59. bool allow_raw_python = false,
  60. const std::function<std::string(const common_chat_msg_parser::find_regex_result & fres)> & get_function_name =
  61. nullptr) {
  62. auto parse_tool_calls = [&]() {
  63. size_t from = std::string::npos;
  64. auto first = true;
  65. while (true) {
  66. auto start_pos = builder.pos();
  67. auto res = function_regex_start_only && first ? builder.try_consume_regex(*function_regex_start_only) :
  68. function_regex ? builder.try_find_regex(*function_regex, from) :
  69. std::nullopt;
  70. if (res) {
  71. std::string name;
  72. if (get_function_name) {
  73. name = get_function_name(*res);
  74. } else {
  75. GGML_ASSERT(res->groups.size() == 2);
  76. name = builder.str(res->groups[1]);
  77. }
  78. first = false;
  79. if (name.empty()) {
  80. // get_function_name signalled us that we should skip this match and treat it as content.
  81. from = res->groups[0].begin + 1;
  82. continue;
  83. }
  84. from = std::string::npos;
  85. auto maybe_raw_python = name == "python" && allow_raw_python;
  86. if (builder.input()[builder.pos()] == '{' || !maybe_raw_python) {
  87. if (auto arguments = builder.try_consume_json_with_dumped_args({ {} })) {
  88. if (!builder.add_tool_call(name, "", arguments->value) || arguments->is_partial) {
  89. throw common_chat_msg_partial_exception("incomplete tool call");
  90. }
  91. builder.consume_regex(close_regex);
  92. }
  93. continue;
  94. }
  95. if (maybe_raw_python) {
  96. auto arguments = wrap_code_as_arguments(builder, builder.consume_rest());
  97. if (!builder.add_tool_call(name, "", arguments)) {
  98. throw common_chat_msg_partial_exception("incomplete tool call");
  99. }
  100. return;
  101. }
  102. throw common_chat_msg_partial_exception("incomplete tool call");
  103. } else {
  104. builder.move_to(start_pos);
  105. }
  106. break;
  107. }
  108. if (block_close) {
  109. builder.consume_regex(*block_close);
  110. }
  111. builder.consume_spaces();
  112. builder.add_content(builder.consume_rest());
  113. };
  114. if (block_open) {
  115. if (auto res = builder.try_find_regex(*block_open)) {
  116. parse_tool_calls();
  117. } else {
  118. builder.add_content(builder.consume_rest());
  119. }
  120. } else {
  121. parse_tool_calls();
  122. }
  123. }
  124. common_chat_msg_parser::common_chat_msg_parser(const std::string & input, bool is_partial, const common_chat_syntax & syntax)
  125. : input_(input), is_partial_(is_partial), syntax_(syntax)
  126. {
  127. result_.role = "assistant";
  128. while (true) {
  129. std::string id = std::to_string(std::rand());
  130. if (input.find(id) == std::string::npos) {
  131. healing_marker_ = id;
  132. break;
  133. }
  134. }
  135. }
  136. std::string common_chat_msg_parser::str(const common_string_range & rng) const {
  137. GGML_ASSERT(rng.begin <= rng.end);
  138. return input_.substr(rng.begin, rng.end - rng.begin);
  139. }
  140. void common_chat_msg_parser::add_content(const std::string &content) {
  141. result_.content += content;
  142. }
  143. void common_chat_msg_parser::add_reasoning_content(const std::string &reasoning_content) {
  144. result_.reasoning_content += reasoning_content;
  145. }
  146. bool common_chat_msg_parser::add_tool_call(const std::string & name, const std::string & id, const std::string & arguments) {
  147. if (name.empty()) {
  148. return false;
  149. }
  150. common_chat_tool_call tool_call;
  151. tool_call.name = name;
  152. tool_call.arguments = arguments;
  153. tool_call.id = id;
  154. // LOG_DBG("Tool call arguments:\n\traw: %s\n\tresult: %s\n", arguments.c_str(), tool_call.arguments.c_str());
  155. result_.tool_calls.emplace_back(tool_call);
  156. return true;
  157. }
  158. bool common_chat_msg_parser::add_tool_call(const json & tool_call) {
  159. std::string name = tool_call.contains("name") ? tool_call.at("name") : "";
  160. std::string id = tool_call.contains("id") ? tool_call.at("id") : "";
  161. std::string arguments = "";
  162. if (tool_call.contains("arguments")) {
  163. if (tool_call.at("arguments").is_object()) {
  164. arguments = tool_call.at("arguments").dump();
  165. } else {
  166. arguments = tool_call.at("arguments");
  167. }
  168. }
  169. return add_tool_call(name, id, arguments);
  170. }
  171. bool common_chat_msg_parser::add_tool_calls(const json & arr) {
  172. for (const auto & item : arr) {
  173. if (!add_tool_call(item)) {
  174. return false;
  175. }
  176. }
  177. return true;
  178. }
  179. bool common_chat_msg_parser::add_tool_call_short_form(const json & tool_call) {
  180. if (!tool_call.is_object() || tool_call.size() != 1) {
  181. return false;
  182. }
  183. // Get the tool name (the single key in the object)
  184. auto it = tool_call.begin();
  185. std::string name = it.key();
  186. if (name.empty()) {
  187. return false;
  188. }
  189. // Get the arguments (the nested object)
  190. const json & args_json = it.value();
  191. std::string arguments = "";
  192. if (args_json.is_object()) {
  193. arguments = args_json.dump();
  194. } else if (args_json.is_string()) {
  195. arguments = args_json;
  196. } else if (!args_json.is_null()) {
  197. // For other types, convert to string representation
  198. arguments = args_json.dump();
  199. }
  200. return add_tool_call(name, "", arguments);
  201. }
  202. void common_chat_msg_parser::finish() {
  203. if (!is_partial_ && pos_ != input_.size()) {
  204. throw std::runtime_error("Unexpected content at end of input");// + input_.substr(pos_));
  205. }
  206. }
  207. bool common_chat_msg_parser::consume_spaces() {
  208. const auto length = input_.size();
  209. auto consumed = false;
  210. while (pos_ < length && std::isspace(input_[pos_])) {
  211. ++pos_;
  212. consumed = true;
  213. }
  214. return consumed;
  215. }
  216. bool common_chat_msg_parser::try_consume_literal(const std::string & literal) {
  217. auto pos = pos_;
  218. for (auto i = 0u; i < literal.size(); ++i) {
  219. if (pos >= input_.size()) {
  220. return false;
  221. }
  222. if (input_[pos] != literal[i]) {
  223. return false;
  224. }
  225. ++pos;
  226. }
  227. pos_ = pos;
  228. return true;
  229. }
  230. std::optional<common_chat_msg_parser::find_regex_result> common_chat_msg_parser::try_find_literal(const std::string & literal) {
  231. auto idx = input_.find(literal, pos_);
  232. if (idx != std::string::npos) {
  233. find_regex_result res;
  234. res.prelude = input_.substr(pos_, idx - pos_);
  235. auto end = idx + literal.size();
  236. res.groups.emplace_back(common_string_range{idx, end});
  237. move_to(end);
  238. return res;
  239. }
  240. if (is_partial_) {
  241. idx = string_find_partial_stop(input_, literal);
  242. if (idx != std::string::npos && idx >= pos_) {
  243. find_regex_result res;
  244. res.prelude = input_.substr(pos_, idx - pos_);
  245. auto end = input_.size();
  246. res.groups.emplace_back(common_string_range{idx, end});
  247. move_to(end);
  248. return res;
  249. }
  250. }
  251. return std::nullopt;
  252. }
  253. void common_chat_msg_parser::consume_literal(const std::string & literal) {
  254. if (!try_consume_literal(literal)) {
  255. throw common_chat_msg_partial_exception(literal);
  256. }
  257. }
  258. bool common_chat_msg_parser::try_parse_reasoning(const std::string & start_think, const std::string & end_think) {
  259. std::string pending_reasoning_prefix;
  260. if (syntax_.reasoning_format == COMMON_REASONING_FORMAT_NONE) {
  261. return false;
  262. }
  263. auto set_reasoning_prefix = [&](size_t prefix_pos) {
  264. if (!syntax_.thinking_forced_open || syntax_.reasoning_in_content) {
  265. return;
  266. }
  267. if (prefix_pos + start_think.size() > input_.size()) {
  268. pending_reasoning_prefix.clear();
  269. return;
  270. }
  271. // Capture the exact literal that opened the reasoning section so we can
  272. // surface it back to callers. This ensures formats that force the
  273. // reasoning tag open (e.g. DeepSeek R1) retain their original prefix
  274. // instead of dropping it during parsing.
  275. pending_reasoning_prefix = input_.substr(prefix_pos, start_think.size());
  276. };
  277. auto handle_reasoning = [&](const std::string & reasoning, bool closed) {
  278. auto stripped_reasoning = string_strip(reasoning);
  279. if (stripped_reasoning.empty()) {
  280. return;
  281. }
  282. if (syntax_.reasoning_in_content) {
  283. add_content(syntax_.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK ? "<think>" : start_think);
  284. add_content(stripped_reasoning);
  285. if (closed) {
  286. add_content(syntax_.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK ? "</think>" : end_think);
  287. }
  288. } else {
  289. if (!pending_reasoning_prefix.empty()) {
  290. add_reasoning_content(pending_reasoning_prefix);
  291. pending_reasoning_prefix.clear();
  292. }
  293. add_reasoning_content(stripped_reasoning);
  294. }
  295. };
  296. const size_t saved_pos = pos_;
  297. const size_t saved_content_size = result_.content.size();
  298. const size_t saved_reasoning_size = result_.reasoning_content.size();
  299. auto restore_state = [&]() {
  300. move_to(saved_pos);
  301. result_.content.resize(saved_content_size);
  302. result_.reasoning_content.resize(saved_reasoning_size);
  303. };
  304. // Allow leading whitespace to be preserved as content when reasoning is present at the start
  305. size_t cursor = pos_;
  306. size_t whitespace_end = cursor;
  307. while (whitespace_end < input_.size() && std::isspace(static_cast<unsigned char>(input_[whitespace_end]))) {
  308. ++whitespace_end;
  309. }
  310. if (whitespace_end >= input_.size()) {
  311. restore_state();
  312. if (syntax_.thinking_forced_open) {
  313. auto rest = input_.substr(saved_pos);
  314. if (!rest.empty()) {
  315. handle_reasoning(rest, /* closed */ !is_partial());
  316. }
  317. move_to(input_.size());
  318. return true;
  319. }
  320. return false;
  321. }
  322. cursor = whitespace_end;
  323. const size_t remaining = input_.size() - cursor;
  324. const size_t start_prefix = std::min(start_think.size(), remaining);
  325. const bool has_start_tag = input_.compare(cursor, start_prefix, start_think, 0, start_prefix) == 0;
  326. if (has_start_tag && start_prefix < start_think.size()) {
  327. move_to(input_.size());
  328. return true;
  329. }
  330. if (has_start_tag) {
  331. if (whitespace_end > pos_) {
  332. add_content(input_.substr(pos_, whitespace_end - pos_));
  333. }
  334. set_reasoning_prefix(cursor);
  335. cursor += start_think.size();
  336. } else if (syntax_.thinking_forced_open) {
  337. cursor = whitespace_end;
  338. } else {
  339. restore_state();
  340. return false;
  341. }
  342. while (true) {
  343. if (cursor >= input_.size()) {
  344. move_to(input_.size());
  345. return true;
  346. }
  347. size_t end_pos = input_.find(end_think, cursor);
  348. if (end_pos == std::string::npos) {
  349. std::string_view remaining_view(input_.data() + cursor, input_.size() - cursor);
  350. size_t partial_off = string_find_partial_stop(remaining_view, end_think);
  351. size_t reasoning_end = partial_off == std::string::npos ? input_.size() : cursor + partial_off;
  352. if (reasoning_end > cursor) {
  353. handle_reasoning(input_.substr(cursor, reasoning_end - cursor), /* closed */ partial_off == std::string::npos && !is_partial());
  354. }
  355. move_to(input_.size());
  356. return true;
  357. }
  358. if (end_pos > cursor) {
  359. handle_reasoning(input_.substr(cursor, end_pos - cursor), /* closed */ true);
  360. } else {
  361. handle_reasoning("", /* closed */ true);
  362. }
  363. cursor = end_pos + end_think.size();
  364. while (cursor < input_.size() && std::isspace(static_cast<unsigned char>(input_[cursor]))) {
  365. ++cursor;
  366. }
  367. const size_t next_remaining = input_.size() - cursor;
  368. if (next_remaining == 0) {
  369. move_to(cursor);
  370. return true;
  371. }
  372. const size_t next_prefix = std::min(start_think.size(), next_remaining);
  373. if (input_.compare(cursor, next_prefix, start_think, 0, next_prefix) == 0) {
  374. if (next_prefix < start_think.size()) {
  375. move_to(input_.size());
  376. return true;
  377. }
  378. set_reasoning_prefix(cursor);
  379. cursor += start_think.size();
  380. continue;
  381. }
  382. move_to(cursor);
  383. return true;
  384. }
  385. }
  386. std::string common_chat_msg_parser::consume_rest() {
  387. auto rest = input_.substr(pos_);
  388. pos_ = input_.size();
  389. return rest;
  390. }
  391. // Tries to find the regex, consumes it (pos right after it) and gives the prelude (right before it) and the groups to the callback.
  392. std::optional<common_chat_msg_parser::find_regex_result> common_chat_msg_parser::try_find_regex(const common_regex & regex, size_t from, bool add_prelude_to_content) {
  393. auto m = regex.search(input_, from == std::string::npos ? pos_ : from);
  394. if (m.type == COMMON_REGEX_MATCH_TYPE_NONE) {
  395. return std::nullopt;
  396. }
  397. auto prelude = input_.substr(pos_, m.groups[0].begin - pos_);
  398. pos_ = m.groups[0].end;
  399. if (add_prelude_to_content) {
  400. add_content(prelude);
  401. }
  402. if (m.type == COMMON_REGEX_MATCH_TYPE_PARTIAL) {
  403. if (is_partial()) {
  404. throw common_chat_msg_partial_exception(regex.str());
  405. }
  406. return std::nullopt;
  407. }
  408. return find_regex_result{prelude, m.groups};
  409. }
  410. common_chat_msg_parser::find_regex_result common_chat_msg_parser::consume_regex(const common_regex & regex) {
  411. if (auto result = try_consume_regex(regex)) {
  412. return *result;
  413. }
  414. throw common_chat_msg_partial_exception(regex.str());
  415. }
  416. std::optional<common_chat_msg_parser::find_regex_result> common_chat_msg_parser::try_consume_regex(const common_regex & regex) {
  417. auto m = regex.search(input_, pos_);
  418. if (m.type == COMMON_REGEX_MATCH_TYPE_NONE) {
  419. return std::nullopt;
  420. }
  421. if (m.type == COMMON_REGEX_MATCH_TYPE_PARTIAL) {
  422. if (is_partial()) {
  423. throw common_chat_msg_partial_exception(regex.str());
  424. }
  425. return std::nullopt;
  426. }
  427. if (m.groups[0].begin != pos_) {
  428. // Didn't match at the current position.
  429. return std::nullopt;
  430. }
  431. pos_ = m.groups[0].end;
  432. return find_regex_result {
  433. /* .prelude = */ "",
  434. m.groups,
  435. };
  436. }
  437. std::optional<common_json> common_chat_msg_parser::try_consume_json() {
  438. auto it = input_.cbegin() + pos_;
  439. const auto end = input_.cend();
  440. common_json result;
  441. if (!common_json_parse(it, end, healing_marker_, result)) {
  442. return std::nullopt;
  443. }
  444. pos_ = std::distance(input_.cbegin(), it);
  445. if (result.healing_marker.marker.empty()) {
  446. // No healing marker, just return the parsed json
  447. return result;
  448. }
  449. if (!is_partial()) {
  450. throw common_chat_msg_partial_exception("JSON");
  451. }
  452. return result;
  453. }
  454. common_json common_chat_msg_parser::consume_json() {
  455. if (auto result = try_consume_json()) {
  456. return *result;
  457. }
  458. throw common_chat_msg_partial_exception("JSON");
  459. }
  460. common_chat_msg_parser::consume_json_result common_chat_msg_parser::consume_json_with_dumped_args(
  461. const std::vector<std::vector<std::string>> & args_paths,
  462. const std::vector<std::vector<std::string>> & content_paths
  463. ) {
  464. if (auto result = try_consume_json_with_dumped_args(args_paths, content_paths)) {
  465. return *result;
  466. }
  467. throw common_chat_msg_partial_exception("JSON");
  468. }
  469. std::optional<common_chat_msg_parser::consume_json_result> common_chat_msg_parser::try_consume_json_with_dumped_args(
  470. const std::vector<std::vector<std::string>> & args_paths,
  471. const std::vector<std::vector<std::string>> & content_paths
  472. ) {
  473. auto partial = try_consume_json();
  474. if (!partial) {
  475. return std::nullopt;
  476. }
  477. auto is_arguments_path = [&](const std::vector<std::string> & path) {
  478. return std::find(args_paths.begin(), args_paths.end(), path) != args_paths.end();
  479. };
  480. auto is_content_path = [&](const std::vector<std::string> & path) {
  481. return std::find(content_paths.begin(), content_paths.end(), path) != content_paths.end();
  482. };
  483. if (partial->healing_marker.marker.empty()) {
  484. if (args_paths.empty()) {
  485. // No arguments to dump, and JSON was parsed fully.
  486. return consume_json_result {
  487. partial->json,
  488. /* .is_partial = */ false,
  489. };
  490. }
  491. if (is_arguments_path({})) {
  492. // Entire JSON is the arguments and was parsed fully.
  493. return consume_json_result {
  494. partial->json.dump(/* indent */ -1, /* indent_char */ ' ', /* ensure_ascii */ true),
  495. /* .is_partial = */ false,
  496. };
  497. }
  498. }
  499. LOG_DBG("Parsed partial JSON: %s (json_healing_marker: %s)\n", partial->json.dump().c_str(), partial->healing_marker.json_dump_marker.c_str());
  500. auto found_healing_marker = false;
  501. std::vector<std::string> path;
  502. std::function<json(const json &)> remove_unsupported_healings_and_dump_args = [&](const json & j) -> json {
  503. if (is_arguments_path(path)) {
  504. auto arguments = j.dump(/* indent */ -1, /* indent_char */ ' ', /* ensure_ascii */ true);
  505. if (is_partial() && !partial->healing_marker.marker.empty()) {
  506. auto idx = arguments.find(partial->healing_marker.json_dump_marker);
  507. if (idx != std::string::npos) {
  508. arguments.resize(idx);
  509. found_healing_marker = true;
  510. }
  511. if (arguments == "\"") {
  512. // This happens because of completing `:"$magic` after `"arguments"`
  513. arguments = "";
  514. }
  515. }
  516. return arguments;
  517. }
  518. if (is_content_path(path)) {
  519. if (!j.is_string()) {
  520. throw std::runtime_error("Content path must be a string");
  521. }
  522. std::string str = j;
  523. auto idx = str.find(partial->healing_marker.marker); // not using json_dump_marker as we're inside a string
  524. if (idx != std::string::npos) {
  525. str.resize(idx);
  526. found_healing_marker = true;
  527. }
  528. return str;
  529. }
  530. if (j.is_object()) {
  531. auto obj = json::object();
  532. for (const auto & p : j.items()) {
  533. const auto & key = p.key();
  534. const auto & value = p.value();
  535. const std::string key_str = key; // NOLINT
  536. auto idx = key_str.find(healing_marker_);
  537. if (idx != std::string::npos) {
  538. found_healing_marker = true;
  539. break;
  540. }
  541. path.push_back(key_str);
  542. if (value.is_string()) {
  543. const std::string value_str = value;
  544. if (value_str.find(healing_marker_) != std::string::npos) {
  545. found_healing_marker = true;
  546. if (is_content_path(path)) {
  547. if (partial->healing_marker.marker == partial->healing_marker.json_dump_marker) {
  548. // The healing occurred inside the string: good. Otherwise we just ditch the entire key/value pair.
  549. obj[key] = remove_unsupported_healings_and_dump_args(value);
  550. }
  551. }
  552. break;
  553. }
  554. obj[key] = value;
  555. } else {
  556. obj[key] = remove_unsupported_healings_and_dump_args(value);
  557. }
  558. path.pop_back();
  559. }
  560. return obj;
  561. }
  562. if (j.is_array()) {
  563. auto arr = json::array();
  564. for (const auto & value : j) {
  565. if (value.is_string()) {
  566. std::string str = value;
  567. auto idx = str.find(healing_marker_);
  568. if (idx != std::string::npos) {
  569. // Don't heal array values that aren't in the arguments.
  570. found_healing_marker = true;
  571. break;
  572. }
  573. }
  574. arr.push_back(remove_unsupported_healings_and_dump_args(value));
  575. }
  576. return arr;
  577. }
  578. return j;
  579. };
  580. auto cleaned = remove_unsupported_healings_and_dump_args(partial->json);
  581. LOG_DBG("Cleaned up JSON %s to %s (json_healing_marker : '%s')\n", partial->json.dump().c_str(), cleaned.dump().c_str(), partial->healing_marker.json_dump_marker.c_str());
  582. return consume_json_result {
  583. cleaned,
  584. /* .is_partial = */ found_healing_marker,
  585. };
  586. }
  587. void common_chat_msg_parser::clear_tools() {
  588. result_.tool_calls.clear();
  589. }
  590. /**
  591. * All common_chat_parse_* moved from chat.cpp to chat-parser.cpp below
  592. * to reduce incremental compile time for parser changes.
  593. */
  594. static void common_chat_parse_generic(common_chat_msg_parser & builder) {
  595. if (!builder.syntax().parse_tool_calls) {
  596. builder.add_content(builder.consume_rest());
  597. return;
  598. }
  599. static const std::vector<std::vector<std::string>> content_paths = {
  600. {"response"},
  601. };
  602. static const std::vector<std::vector<std::string>> args_paths = {
  603. {"tool_call", "arguments"},
  604. {"tool_calls", "arguments"},
  605. };
  606. auto data = builder.consume_json_with_dumped_args(args_paths, content_paths);
  607. if (data.value.contains("tool_calls")) {
  608. if (!builder.add_tool_calls(data.value.at("tool_calls")) || data.is_partial) {
  609. throw common_chat_msg_partial_exception("incomplete tool calls");
  610. }
  611. } else if (data.value.contains("tool_call")) {
  612. if (!builder.add_tool_call(data.value.at("tool_call")) || data.is_partial) {
  613. throw common_chat_msg_partial_exception("incomplete tool call");
  614. }
  615. } else if (data.value.contains("response")) {
  616. const auto & response = data.value.at("response");
  617. builder.add_content(response.is_string() ? response.template get<std::string>() : response.dump(2));
  618. if (data.is_partial) {
  619. throw common_chat_msg_partial_exception("incomplete response");
  620. }
  621. } else {
  622. throw common_chat_msg_partial_exception("Expected 'tool_call', 'tool_calls' or 'response' in JSON");
  623. }
  624. }
  625. static void common_chat_parse_mistral_nemo(common_chat_msg_parser & builder) {
  626. if (!builder.syntax().parse_tool_calls) {
  627. builder.add_content(builder.consume_rest());
  628. return;
  629. }
  630. static const common_regex prefix(regex_escape("[TOOL_CALLS]"));
  631. parse_prefixed_json_tool_call_array(builder, prefix);
  632. }
  633. static void common_chat_parse_magistral(common_chat_msg_parser & builder) {
  634. builder.try_parse_reasoning("[THINK]", "[/THINK]");
  635. if (!builder.syntax().parse_tool_calls) {
  636. builder.add_content(builder.consume_rest());
  637. return;
  638. }
  639. static const common_regex prefix(regex_escape("[TOOL_CALLS]"));
  640. parse_prefixed_json_tool_call_array(builder, prefix);
  641. }
  642. static void common_chat_parse_command_r7b(common_chat_msg_parser & builder) {
  643. builder.try_parse_reasoning("<|START_THINKING|>", "<|END_THINKING|>");
  644. static const common_regex start_action_regex("<\\|START_ACTION\\|>");
  645. static const common_regex end_action_regex("<\\|END_ACTION\\|>");
  646. static const common_regex start_response_regex("<\\|START_RESPONSE\\|>");
  647. static const common_regex end_response_regex("<\\|END_RESPONSE\\|>");
  648. if (auto res = builder.try_find_regex(start_action_regex)) {
  649. // If we didn't extract thoughts, prelude includes them.
  650. auto tool_calls = builder.consume_json_with_dumped_args({{"parameters"}});
  651. for (const auto & tool_call : tool_calls.value) {
  652. std::string name = tool_call.contains("tool_name") ? tool_call.at("tool_name") : "";
  653. std::string id = tool_call.contains("tool_call_id") ? tool_call.at("tool_call_id") : "";
  654. std::string arguments = tool_call.contains("parameters") ? tool_call.at("parameters") : "";
  655. if (!builder.add_tool_call(name, id, arguments) || tool_calls.is_partial) {
  656. throw common_chat_msg_partial_exception("incomplete tool call");
  657. }
  658. }
  659. if (tool_calls.is_partial) {
  660. throw common_chat_msg_partial_exception("incomplete tool call");
  661. }
  662. builder.consume_regex(end_action_regex);
  663. } else if (auto res = builder.try_find_regex(start_response_regex)) {
  664. if (!builder.try_find_regex(end_response_regex)) {
  665. builder.add_content(builder.consume_rest());
  666. throw common_chat_msg_partial_exception(end_response_regex.str());
  667. }
  668. } else {
  669. builder.add_content(builder.consume_rest());
  670. }
  671. }
  672. static void common_chat_parse_llama_3_1(common_chat_msg_parser & builder, bool with_builtin_tools = false) {
  673. builder.try_parse_reasoning("<think>", "</think>");
  674. if (!builder.syntax().parse_tool_calls) {
  675. builder.add_content(builder.consume_rest());
  676. return;
  677. }
  678. static const common_regex function_regex(
  679. "\\s*\\{\\s*(?:\"type\"\\s*:\\s*\"function\"\\s*,\\s*)?\"name\"\\s*:\\s*\"([^\"]+)\"\\s*,\\s*\"parameters\"\\s*: ");
  680. static const common_regex close_regex("\\}\\s*");
  681. static const common_regex function_name_regex("\\s*(\\w+)\\s*\\.\\s*call\\(");
  682. static const common_regex arg_name_regex("\\s*(\\w+)\\s*=\\s*");
  683. if (with_builtin_tools) {
  684. static const common_regex builtin_call_regex("<\\|python_tag\\|>");
  685. if (auto res = builder.try_find_regex(builtin_call_regex)) {
  686. auto fun_res = builder.consume_regex(function_name_regex);
  687. auto function_name = builder.str(fun_res.groups[1]);
  688. common_healing_marker healing_marker;
  689. json args = json::object();
  690. while (true) {
  691. if (auto arg_res = builder.try_consume_regex(arg_name_regex)) {
  692. auto arg_name = builder.str(arg_res->groups[1]);
  693. auto partial = builder.consume_json();
  694. args[arg_name] = partial.json;
  695. healing_marker.marker = partial.healing_marker.marker;
  696. healing_marker.json_dump_marker = partial.healing_marker.json_dump_marker;
  697. builder.consume_spaces();
  698. if (!builder.try_consume_literal(",")) {
  699. break;
  700. }
  701. } else {
  702. break;
  703. }
  704. }
  705. builder.consume_literal(")");
  706. builder.consume_spaces();
  707. auto arguments = args.dump();
  708. if (!builder.add_tool_call(function_name, "", arguments)) {
  709. throw common_chat_msg_partial_exception("Incomplete tool call");
  710. }
  711. return;
  712. }
  713. }
  714. parse_json_tool_calls(
  715. builder,
  716. /* block_open= */ std::nullopt,
  717. /* function_regex_start_only= */ function_regex,
  718. /* function_regex= */ std::nullopt,
  719. close_regex,
  720. std::nullopt);
  721. }
  722. static void common_chat_parse_deepseek_r1(common_chat_msg_parser & builder) {
  723. builder.try_parse_reasoning("<think>", "</think>");
  724. if (!builder.syntax().parse_tool_calls) {
  725. builder.add_content(builder.consume_rest());
  726. return;
  727. }
  728. static const common_regex tool_calls_begin("(?:<|tool▁calls▁begin|>|<|tool_calls_begin|>|<|tool calls begin|>|<|tool\\\\_calls\\\\_begin|>|<|tool▁calls|>)");
  729. static const common_regex tool_calls_end("<|tool▁calls▁end|>");
  730. static const common_regex function_regex("(?:<|tool▁call▁begin|>)?function<|tool▁sep|>([^\n]+)\n```json\n");
  731. static const common_regex close_regex("```[\\s\\r\\n]*<|tool▁call▁end|>");
  732. parse_json_tool_calls(
  733. builder,
  734. /* block_open= */ tool_calls_begin,
  735. /* function_regex_start_only= */ std::nullopt,
  736. function_regex,
  737. close_regex,
  738. tool_calls_end);
  739. }
  740. static void common_chat_parse_deepseek_v3_1_content(common_chat_msg_parser & builder) {
  741. static const common_regex function_regex("(?:<|tool▁call▁begin|>)?([^\\n<]+)(?:<|tool▁sep|>)");
  742. static const common_regex close_regex("(?:[\\s]*)?<|tool▁call▁end|>");
  743. static const common_regex tool_calls_begin("(?:<|tool▁calls▁begin|>|<|tool_calls_begin|>|<|tool calls begin|>|<|tool\\\\_calls\\\\_begin|>|<|tool▁calls|>)");
  744. static const common_regex tool_calls_end("<|tool▁calls▁end|>");
  745. if (!builder.syntax().parse_tool_calls) {
  746. LOG_DBG("%s: not parse_tool_calls\n", __func__);
  747. builder.add_content(builder.consume_rest());
  748. return;
  749. }
  750. LOG_DBG("%s: parse_tool_calls\n", __func__);
  751. parse_json_tool_calls(
  752. builder,
  753. /* block_open= */ tool_calls_begin,
  754. /* function_regex_start_only= */ std::nullopt,
  755. function_regex,
  756. close_regex,
  757. tool_calls_end);
  758. }
  759. static void common_chat_parse_deepseek_v3_1(common_chat_msg_parser & builder) {
  760. // DeepSeek V3.1 outputs reasoning content between "<think>" and "</think>" tags, followed by regular content
  761. // First try to parse using the standard reasoning parsing method
  762. LOG_DBG("%s: thinking_forced_open: %s\n", __func__, std::to_string(builder.syntax().thinking_forced_open).c_str());
  763. auto start_pos = builder.pos();
  764. auto found_end_think = builder.try_find_literal("</think>");
  765. builder.move_to(start_pos);
  766. if (builder.syntax().thinking_forced_open && !builder.is_partial() && !found_end_think) {
  767. LOG_DBG("%s: no end_think, not partial, adding content\n", __func__);
  768. common_chat_parse_deepseek_v3_1_content(builder);
  769. } else if (builder.try_parse_reasoning("<think>", "</think>")) {
  770. // If reasoning was parsed successfully, the remaining content is regular content
  771. LOG_DBG("%s: parsed reasoning, adding content\n", __func__);
  772. // </think><|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>NAME\n```json\nJSON\n```<|tool▁call▁end|><|tool▁calls▁end|>
  773. common_chat_parse_deepseek_v3_1_content(builder);
  774. } else {
  775. if (builder.syntax().reasoning_format == COMMON_REASONING_FORMAT_NONE) {
  776. LOG_DBG("%s: reasoning_format none, adding content\n", __func__);
  777. common_chat_parse_deepseek_v3_1_content(builder);
  778. return;
  779. }
  780. // If no reasoning tags found, check if we should treat everything as reasoning
  781. if (builder.syntax().thinking_forced_open) {
  782. // If thinking is forced open but no tags found, treat everything as reasoning
  783. LOG_DBG("%s: thinking_forced_open, adding reasoning content\n", __func__);
  784. builder.add_reasoning_content(builder.consume_rest());
  785. } else {
  786. LOG_DBG("%s: no thinking_forced_open, adding content\n", __func__);
  787. // <|tool▁call▁begin|>NAME<|tool▁sep|>JSON<|tool▁call▁end|>
  788. common_chat_parse_deepseek_v3_1_content(builder);
  789. }
  790. }
  791. }
  792. static void common_chat_parse_minimax_m2(common_chat_msg_parser & builder) {
  793. static const xml_tool_call_format form {
  794. /* form.scope_start = */ "<minimax:tool_call>",
  795. /* form.tool_start = */ "<invoke name=\"",
  796. /* form.tool_sep = */ "\">",
  797. /* form.key_start = */ "<parameter name=\"",
  798. /* form.key_val_sep = */ "\">",
  799. /* form.val_end = */ "</parameter>",
  800. /* form.tool_end = */ "</invoke>",
  801. /* form.scope_end = */ "</minimax:tool_call>",
  802. };
  803. builder.consume_reasoning_with_xml_tool_calls(form, "<think>", "</think>");
  804. }
  805. static void common_chat_parse_qwen3_coder_xml(common_chat_msg_parser & builder) {
  806. static const xml_tool_call_format form = ([]() {
  807. xml_tool_call_format form {};
  808. form.scope_start = "<tool_call>";
  809. form.tool_start = "<function=";
  810. form.tool_sep = ">";
  811. form.key_start = "<parameter=";
  812. form.key_val_sep = ">";
  813. form.val_end = "</parameter>";
  814. form.tool_end = "</function>";
  815. form.scope_end = "</tool_call>";
  816. form.trim_raw_argval = true;
  817. return form;
  818. })();
  819. builder.consume_reasoning_with_xml_tool_calls(form);
  820. }
  821. static void common_chat_parse_kimi_k2(common_chat_msg_parser & builder) {
  822. static const xml_tool_call_format form = ([]() {
  823. xml_tool_call_format form {};
  824. form.scope_start = "<|tool_calls_section_begin|>";
  825. form.tool_start = "<|tool_call_begin|>";
  826. form.tool_sep = "<|tool_call_argument_begin|>{";
  827. form.key_start = "\"";
  828. form.key_val_sep = "\":";
  829. form.val_end = ",";
  830. form.tool_end = "}<|tool_call_end|>";
  831. form.scope_end = "<|tool_calls_section_end|>";
  832. form.raw_argval = false;
  833. form.last_val_end = "";
  834. form.allow_toolcall_in_think = true;
  835. return form;
  836. })();
  837. builder.consume_reasoning_with_xml_tool_calls(form, "<think>", "</think>");
  838. }
  839. static void common_chat_parse_apriel_1_5(common_chat_msg_parser & builder) {
  840. static const xml_tool_call_format form = ([]() {
  841. xml_tool_call_format form {};
  842. form.scope_start = "<tool_calls>[";
  843. form.tool_start = "{\"name\": \"";
  844. form.tool_sep = "\", \"arguments\": {";
  845. form.key_start = "\"";
  846. form.key_val_sep = "\": ";
  847. form.val_end = ", ";
  848. form.tool_end = "}, ";
  849. form.scope_end = "]</tool_calls>";
  850. form.raw_argval = false;
  851. form.last_val_end = "";
  852. form.last_tool_end = "}";
  853. return form;
  854. })();
  855. builder.consume_reasoning_with_xml_tool_calls(form, "<thinking>", "</thinking>");
  856. }
  857. static void common_chat_parse_xiaomi_mimo(common_chat_msg_parser & builder) {
  858. static const xml_tool_call_format form = ([]() {
  859. xml_tool_call_format form {};
  860. form.scope_start = "";
  861. form.tool_start = "<tool_call>\n{\"name\": \"";
  862. form.tool_sep = "\", \"arguments\": {";
  863. form.key_start = "\"";
  864. form.key_val_sep = "\": ";
  865. form.val_end = ", ";
  866. form.tool_end = "}\n</tool_call>";
  867. form.scope_end = "";
  868. form.raw_argval = false;
  869. form.last_val_end = "";
  870. return form;
  871. })();
  872. builder.consume_reasoning_with_xml_tool_calls(form);
  873. }
  874. static void common_chat_parse_gpt_oss(common_chat_msg_parser & builder) {
  875. static const std::string constraint = "(?: (<\\|constrain\\|>)?([a-zA-Z0-9_-]+))";
  876. static const std::string recipient("(?: to=functions\\.([^<\\s]+))");
  877. static const common_regex start_regex("<\\|start\\|>assistant");
  878. static const common_regex analysis_regex("<\\|channel\\|>analysis");
  879. static const common_regex final_regex("<\\|channel\\|>final" + constraint + "?");
  880. static const common_regex preamble_regex("<\\|channel\\|>commentary");
  881. static const common_regex tool_call1_regex(recipient + "<\\|channel\\|>(analysis|commentary)" + constraint + "?");
  882. static const common_regex tool_call2_regex("<\\|channel\\|>(analysis|commentary)" + recipient + constraint + "?");
  883. auto consume_end = [&](bool include_end = false) {
  884. if (auto res = builder.try_find_literal("<|end|>")) {
  885. return res->prelude + (include_end ? builder.str(res->groups[0]) : "");
  886. }
  887. return builder.consume_rest();
  888. };
  889. auto handle_tool_call = [&](const std::string & name) {
  890. if (auto args = builder.try_consume_json_with_dumped_args({{}})) {
  891. if (builder.syntax().parse_tool_calls) {
  892. if (!builder.add_tool_call(name, "", args->value) || args->is_partial) {
  893. throw common_chat_msg_partial_exception("incomplete tool call");
  894. }
  895. } else if (args->is_partial) {
  896. throw common_chat_msg_partial_exception("incomplete tool call");
  897. }
  898. }
  899. };
  900. auto regex_match = [](const common_regex & regex, const std::string & input) -> std::optional<common_regex_match> {
  901. auto match = regex.search(input, 0, true);
  902. if (match.type == COMMON_REGEX_MATCH_TYPE_FULL) {
  903. return match;
  904. }
  905. return std::nullopt;
  906. };
  907. do {
  908. auto header_start_pos = builder.pos();
  909. auto content_start = builder.try_find_literal("<|message|>");
  910. if (!content_start) {
  911. throw common_chat_msg_partial_exception("incomplete header");
  912. }
  913. auto header = content_start->prelude;
  914. if (auto match = regex_match(tool_call1_regex, header)) {
  915. auto group = match->groups[1];
  916. auto name = header.substr(group.begin, group.end - group.begin);
  917. handle_tool_call(name);
  918. continue;
  919. }
  920. if (auto match = regex_match(tool_call2_regex, header)) {
  921. auto group = match->groups[2];
  922. auto name = header.substr(group.begin, group.end - group.begin);
  923. handle_tool_call(name);
  924. continue;
  925. }
  926. if (regex_match(analysis_regex, header)) {
  927. builder.move_to(header_start_pos);
  928. if (builder.syntax().reasoning_format == COMMON_REASONING_FORMAT_NONE || builder.syntax().reasoning_in_content) {
  929. builder.add_content(consume_end(true));
  930. } else {
  931. builder.try_parse_reasoning("<|channel|>analysis<|message|>", "<|end|>");
  932. }
  933. continue;
  934. }
  935. if(regex_match(final_regex, header) || regex_match(preamble_regex, header)) {
  936. builder.add_content(consume_end());
  937. continue;
  938. }
  939. // Possibly a malformed message, attempt to recover by rolling
  940. // back to pick up the next <|start|>
  941. LOG_DBG("%s: unknown header from message: %s\n", __func__, header.c_str());
  942. builder.move_to(header_start_pos);
  943. } while (builder.try_find_regex(start_regex, std::string::npos, false));
  944. auto remaining = builder.consume_rest();
  945. if (!remaining.empty()) {
  946. LOG_DBG("%s: content after last message: %s\n", __func__, remaining.c_str());
  947. }
  948. }
  949. static void common_chat_parse_glm_4_5(common_chat_msg_parser & builder) {
  950. static const xml_tool_call_format form {
  951. /* form.scope_start = */ "",
  952. /* form.tool_start = */ "<tool_call>",
  953. /* form.tool_sep = */ "",
  954. /* form.key_start = */ "<arg_key>",
  955. /* form.key_val_sep = */ "</arg_key>",
  956. /* form.val_end = */ "</arg_value>",
  957. /* form.tool_end = */ "</tool_call>",
  958. /* form.scope_end = */ "",
  959. /* form.key_val_sep2 = */ "<arg_value>",
  960. };
  961. builder.consume_reasoning_with_xml_tool_calls(form, "<think>", "</think>");
  962. }
  963. static void common_chat_parse_firefunction_v2(common_chat_msg_parser & builder) {
  964. if (!builder.syntax().parse_tool_calls) {
  965. builder.add_content(builder.consume_rest());
  966. return;
  967. }
  968. static const common_regex prefix(regex_escape(" functools["));
  969. parse_prefixed_json_tool_call_array(builder, prefix, /* rstrip_prefix= */ 1);
  970. }
  971. static void common_chat_parse_functionary_v3_2(common_chat_msg_parser & builder) {
  972. static const common_regex function_regex_start_only(R"((\w+\n\{|python\n|all\n))");
  973. static const common_regex function_regex(R"(>>>(\w+\n\{|python\n|all\n))");
  974. static const common_regex close_regex(R"(\s*)");
  975. parse_json_tool_calls(
  976. builder,
  977. std::nullopt,
  978. function_regex_start_only,
  979. function_regex,
  980. close_regex,
  981. std::nullopt,
  982. /* allow_raw_python= */ true,
  983. /* get_function_name= */ [&](const auto & res) -> std::string {
  984. auto at_start = res.groups[0].begin == 0;
  985. auto name = builder.str(res.groups[1]);
  986. if (!name.empty() && name.back() == '{') {
  987. // Unconsume the opening brace '{' to ensure the JSON parsing goes well.
  988. builder.move_back(1);
  989. }
  990. auto idx = name.find_last_not_of("\n{");
  991. name = name.substr(0, idx + 1);
  992. if (at_start && name == "all") {
  993. return "";
  994. }
  995. return name;
  996. });
  997. }
  998. static void common_chat_parse_functionary_v3_1_llama_3_1(common_chat_msg_parser & builder) {
  999. if (!builder.syntax().parse_tool_calls) {
  1000. builder.add_content(builder.consume_rest());
  1001. return;
  1002. }
  1003. // This version of Functionary still supports the llama 3.1 tool call format for the python tool.
  1004. static const common_regex python_tag_regex(regex_escape("<|python_tag|>"));
  1005. static const common_regex function_regex(R"(<function=(\w+)>)");
  1006. static const common_regex close_regex(R"(</function>)");
  1007. parse_json_tool_calls(
  1008. builder,
  1009. /* block_open= */ std::nullopt,
  1010. /* function_regex_start_only= */ std::nullopt,
  1011. function_regex,
  1012. close_regex,
  1013. std::nullopt);
  1014. if (auto res = builder.try_find_regex(python_tag_regex)) {
  1015. auto arguments = wrap_code_as_arguments(builder, builder.consume_rest());
  1016. builder.add_tool_call("python", "", arguments);
  1017. return;
  1018. }
  1019. }
  1020. static void common_chat_parse_hermes_2_pro(common_chat_msg_parser & builder) {
  1021. builder.try_parse_reasoning("<think>", "</think>");
  1022. if (!builder.syntax().parse_tool_calls) {
  1023. builder.add_content(builder.consume_rest());
  1024. return;
  1025. }
  1026. static const common_regex open_regex(
  1027. "(?:"
  1028. "(```(?:xml|json)?\\n\\s*)?" // match 1 (block_start)
  1029. "(" // match 2 (open_tag)
  1030. "<tool_call>"
  1031. "|<function_call>"
  1032. "|<tool>"
  1033. "|<tools>"
  1034. "|<response>"
  1035. "|<json>"
  1036. "|<xml>"
  1037. "|<JSON>"
  1038. ")?"
  1039. "(\\s*\\{\\s*\"name\")" // match 3 (named tool call)
  1040. ")"
  1041. "|<function=([^>]+)>" // match 4 (function name)
  1042. "|<function name=\"([^\"]+)\">" // match 5 (function name again)
  1043. );
  1044. while (auto res = builder.try_find_regex(open_regex)) {
  1045. const auto & block_start = res->groups[1];
  1046. std::string block_end = block_start.empty() ? "" : "```";
  1047. const auto & open_tag = res->groups[2];
  1048. std::string close_tag;
  1049. if (!res->groups[3].empty()) {
  1050. builder.move_to(res->groups[3].begin);
  1051. close_tag = open_tag.empty() ? "" : "</" + builder.str(open_tag).substr(1);
  1052. if (auto tool_call = builder.try_consume_json_with_dumped_args({{"arguments"}})) {
  1053. if (!builder.add_tool_call(tool_call->value) || tool_call->is_partial) {
  1054. throw common_chat_msg_partial_exception("incomplete tool call");
  1055. }
  1056. builder.consume_spaces();
  1057. builder.consume_literal(close_tag);
  1058. builder.consume_spaces();
  1059. if (!block_end.empty()) {
  1060. builder.consume_literal(block_end);
  1061. builder.consume_spaces();
  1062. }
  1063. } else {
  1064. throw common_chat_msg_partial_exception("failed to parse tool call");
  1065. }
  1066. } else {
  1067. auto function_name = builder.str(res->groups[4]);
  1068. if (function_name.empty()) {
  1069. function_name = builder.str(res->groups[5]);
  1070. }
  1071. GGML_ASSERT(!function_name.empty());
  1072. close_tag = "</function>";
  1073. if (auto arguments = builder.try_consume_json_with_dumped_args({{}})) {
  1074. if (!builder.add_tool_call(function_name, "", arguments->value) || arguments->is_partial) {
  1075. throw common_chat_msg_partial_exception("incomplete tool call");
  1076. }
  1077. builder.consume_spaces();
  1078. builder.consume_literal(close_tag);
  1079. builder.consume_spaces();
  1080. if (!block_end.empty()) {
  1081. builder.consume_literal(block_end);
  1082. builder.consume_spaces();
  1083. }
  1084. }
  1085. }
  1086. }
  1087. builder.add_content(builder.consume_rest());
  1088. }
  1089. static void common_chat_parse_granite(common_chat_msg_parser & builder) {
  1090. // Parse thinking tags
  1091. static const common_regex start_think_regex(regex_escape("<think>"));
  1092. static const common_regex end_think_regex(regex_escape("</think>"));
  1093. // Granite models output partial tokens such as "<" and "<think".
  1094. // By leveraging try_consume_regex()/try_find_regex() throwing
  1095. // common_chat_msg_partial_exception for these partial tokens,
  1096. // processing is interrupted and the tokens are not passed to add_content().
  1097. if (auto res = builder.try_consume_regex(start_think_regex)) {
  1098. // Restore position for try_parse_reasoning()
  1099. builder.move_to(res->groups[0].begin);
  1100. builder.try_find_regex(end_think_regex, std::string::npos, false);
  1101. // Restore position for try_parse_reasoning()
  1102. builder.move_to(res->groups[0].begin);
  1103. }
  1104. builder.try_parse_reasoning("<think>", "</think>");
  1105. // Parse response tags
  1106. static const common_regex start_response_regex(regex_escape("<response>"));
  1107. static const common_regex end_response_regex(regex_escape("</response>"));
  1108. // Granite models output partial tokens such as "<" and "<response".
  1109. // Same hack as reasoning parsing.
  1110. if (builder.try_consume_regex(start_response_regex)) {
  1111. builder.try_find_regex(end_response_regex);
  1112. }
  1113. if (!builder.syntax().parse_tool_calls) {
  1114. builder.add_content(builder.consume_rest());
  1115. return;
  1116. }
  1117. // Look for tool calls
  1118. static const common_regex tool_call_regex(regex_escape("<|tool_call|>"));
  1119. if (auto res = builder.try_find_regex(tool_call_regex)) {
  1120. builder.move_to(res->groups[0].end);
  1121. // Expect JSON array of tool calls
  1122. if (auto tool_call = builder.try_consume_json_with_dumped_args({{{"arguments"}}})) {
  1123. if (!builder.add_tool_calls(tool_call->value) || tool_call->is_partial) {
  1124. throw common_chat_msg_partial_exception("incomplete tool call");
  1125. }
  1126. }
  1127. } else {
  1128. builder.add_content(builder.consume_rest());
  1129. }
  1130. }
  1131. static void common_chat_parse_nemotron_v2(common_chat_msg_parser & builder) {
  1132. // Parse thinking tags
  1133. builder.try_parse_reasoning("<think>", "</think>");
  1134. if (!builder.syntax().parse_tool_calls) {
  1135. builder.add_content(builder.consume_rest());
  1136. return;
  1137. }
  1138. // Look for tool calls
  1139. static const common_regex tool_call_regex(regex_escape("<TOOLCALL>"));
  1140. if (auto res = builder.try_find_regex(tool_call_regex)) {
  1141. builder.move_to(res->groups[0].end);
  1142. // Expect JSON array of tool calls
  1143. auto tool_calls_data = builder.consume_json();
  1144. if (tool_calls_data.json.is_array()) {
  1145. if (!builder.try_consume_literal("</TOOLCALL>")) {
  1146. throw common_chat_msg_partial_exception("Incomplete tool call");
  1147. }
  1148. builder.add_tool_calls(tool_calls_data.json);
  1149. } else {
  1150. throw common_chat_msg_partial_exception("Incomplete tool call");
  1151. }
  1152. }
  1153. builder.add_content(builder.consume_rest());
  1154. }
  1155. static void common_chat_parse_apertus(common_chat_msg_parser & builder) {
  1156. // Parse thinking tags
  1157. builder.try_parse_reasoning("<|inner_prefix|>", "<|inner_suffix|>");
  1158. if (!builder.syntax().parse_tool_calls) {
  1159. builder.add_content(builder.consume_rest());
  1160. return;
  1161. }
  1162. // Look for tool calls
  1163. static const common_regex tool_call_regex(regex_escape("<|tools_prefix|>"));
  1164. if (auto res = builder.try_find_regex(tool_call_regex)) {
  1165. builder.move_to(res->groups[0].end);
  1166. auto tool_calls_data = builder.consume_json();
  1167. if (tool_calls_data.json.is_array()) {
  1168. builder.consume_spaces();
  1169. if (!builder.try_consume_literal("<|tools_suffix|>")) {
  1170. throw common_chat_msg_partial_exception("Incomplete tool call");
  1171. }
  1172. for (const auto & value : tool_calls_data.json) {
  1173. if (value.is_object()) {
  1174. builder.add_tool_call_short_form(value);
  1175. }
  1176. }
  1177. } else {
  1178. throw common_chat_msg_partial_exception("Incomplete tool call");
  1179. }
  1180. }
  1181. builder.add_content(builder.consume_rest());
  1182. }
  1183. static void common_chat_parse_lfm2(common_chat_msg_parser & builder) {
  1184. if (!builder.syntax().parse_tool_calls) {
  1185. builder.add_content(builder.consume_rest());
  1186. return;
  1187. }
  1188. // LFM2 format: <|tool_call_start|>[{"name": "get_current_time", "arguments": {"location": "Paris"}}]<|tool_call_end|>
  1189. static const common_regex tool_call_start_regex(regex_escape("<|tool_call_start|>"));
  1190. static const common_regex tool_call_end_regex(regex_escape("<|tool_call_end|>"));
  1191. // Loop through all tool calls
  1192. while (auto res = builder.try_find_regex(tool_call_start_regex, std::string::npos, /* add_prelude_to_content= */ true)) {
  1193. builder.move_to(res->groups[0].end);
  1194. // Parse JSON array format: [{"name": "...", "arguments": {...}}]
  1195. auto tool_calls_data = builder.consume_json();
  1196. // Consume end marker
  1197. builder.consume_spaces();
  1198. if (!builder.try_consume_regex(tool_call_end_regex)) {
  1199. throw common_chat_msg_partial_exception("Expected <|tool_call_end|>");
  1200. }
  1201. // Process each tool call in the array
  1202. if (tool_calls_data.json.is_array()) {
  1203. for (const auto & tool_call : tool_calls_data.json) {
  1204. if (!tool_call.is_object()) {
  1205. throw common_chat_msg_partial_exception("Tool call must be an object");
  1206. }
  1207. if (!tool_call.contains("name")) {
  1208. throw common_chat_msg_partial_exception("Tool call missing 'name' field");
  1209. }
  1210. std::string function_name = tool_call.at("name");
  1211. std::string arguments = "{}";
  1212. if (tool_call.contains("arguments")) {
  1213. if (tool_call.at("arguments").is_object()) {
  1214. arguments = tool_call.at("arguments").dump();
  1215. } else if (tool_call.at("arguments").is_string()) {
  1216. arguments = tool_call.at("arguments");
  1217. }
  1218. }
  1219. if (!builder.add_tool_call(function_name, "", arguments)) {
  1220. throw common_chat_msg_partial_exception("Incomplete tool call");
  1221. }
  1222. }
  1223. } else {
  1224. throw common_chat_msg_partial_exception("Expected JSON array for tool calls");
  1225. }
  1226. // Consume any trailing whitespace after this tool call
  1227. builder.consume_spaces();
  1228. }
  1229. // Consume any remaining content after all tool calls
  1230. auto remaining = builder.consume_rest();
  1231. if (!string_strip(remaining).empty()) {
  1232. builder.add_content(remaining);
  1233. }
  1234. }
  1235. static void common_chat_parse_seed_oss(common_chat_msg_parser & builder) {
  1236. static const xml_tool_call_format form {
  1237. /* form.scope_start = */ "<seed:tool_call>",
  1238. /* form.tool_start = */ "<function=",
  1239. /* form.tool_sep = */ ">",
  1240. /* form.key_start = */ "<parameter=",
  1241. /* form.key_val_sep = */ ">",
  1242. /* form.val_end = */ "</parameter>",
  1243. /* form.tool_end = */ "</function>",
  1244. /* form.scope_end = */ "</seed:tool_call>",
  1245. };
  1246. builder.consume_reasoning_with_xml_tool_calls(form, "<seed:think>", "</seed:think>");
  1247. }
  1248. static void common_chat_parse_content_only(common_chat_msg_parser & builder) {
  1249. builder.try_parse_reasoning("<think>", "</think>");
  1250. builder.add_content(builder.consume_rest());
  1251. }
  1252. static void common_chat_parse(common_chat_msg_parser & builder) {
  1253. LOG_DBG("Parsing input with format %s: %s\n", common_chat_format_name(builder.syntax().format), builder.input().c_str());
  1254. switch (builder.syntax().format) {
  1255. case COMMON_CHAT_FORMAT_CONTENT_ONLY:
  1256. common_chat_parse_content_only(builder);
  1257. break;
  1258. case COMMON_CHAT_FORMAT_GENERIC:
  1259. common_chat_parse_generic(builder);
  1260. break;
  1261. case COMMON_CHAT_FORMAT_MISTRAL_NEMO:
  1262. common_chat_parse_mistral_nemo(builder);
  1263. break;
  1264. case COMMON_CHAT_FORMAT_MAGISTRAL:
  1265. common_chat_parse_magistral(builder);
  1266. break;
  1267. case COMMON_CHAT_FORMAT_LLAMA_3_X:
  1268. common_chat_parse_llama_3_1(builder);
  1269. break;
  1270. case COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS:
  1271. common_chat_parse_llama_3_1(builder, /* with_builtin_tools= */ true);
  1272. break;
  1273. case COMMON_CHAT_FORMAT_DEEPSEEK_R1:
  1274. common_chat_parse_deepseek_r1(builder);
  1275. break;
  1276. case COMMON_CHAT_FORMAT_DEEPSEEK_V3_1:
  1277. common_chat_parse_deepseek_v3_1(builder);
  1278. break;
  1279. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2:
  1280. common_chat_parse_functionary_v3_2(builder);
  1281. break;
  1282. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1:
  1283. common_chat_parse_functionary_v3_1_llama_3_1(builder);
  1284. break;
  1285. case COMMON_CHAT_FORMAT_HERMES_2_PRO:
  1286. common_chat_parse_hermes_2_pro(builder);
  1287. break;
  1288. case COMMON_CHAT_FORMAT_FIREFUNCTION_V2:
  1289. common_chat_parse_firefunction_v2(builder);
  1290. break;
  1291. case COMMON_CHAT_FORMAT_COMMAND_R7B:
  1292. common_chat_parse_command_r7b(builder);
  1293. break;
  1294. case COMMON_CHAT_FORMAT_GRANITE:
  1295. common_chat_parse_granite(builder);
  1296. break;
  1297. case COMMON_CHAT_FORMAT_GPT_OSS:
  1298. common_chat_parse_gpt_oss(builder);
  1299. break;
  1300. case COMMON_CHAT_FORMAT_SEED_OSS:
  1301. common_chat_parse_seed_oss(builder);
  1302. break;
  1303. case COMMON_CHAT_FORMAT_NEMOTRON_V2:
  1304. common_chat_parse_nemotron_v2(builder);
  1305. break;
  1306. case COMMON_CHAT_FORMAT_APERTUS:
  1307. common_chat_parse_apertus(builder);
  1308. break;
  1309. case COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS:
  1310. common_chat_parse_lfm2(builder);
  1311. break;
  1312. case COMMON_CHAT_FORMAT_MINIMAX_M2:
  1313. common_chat_parse_minimax_m2(builder);
  1314. break;
  1315. case COMMON_CHAT_FORMAT_GLM_4_5:
  1316. common_chat_parse_glm_4_5(builder);
  1317. break;
  1318. case COMMON_CHAT_FORMAT_KIMI_K2:
  1319. common_chat_parse_kimi_k2(builder);
  1320. break;
  1321. case COMMON_CHAT_FORMAT_QWEN3_CODER_XML:
  1322. common_chat_parse_qwen3_coder_xml(builder);
  1323. break;
  1324. case COMMON_CHAT_FORMAT_APRIEL_1_5:
  1325. common_chat_parse_apriel_1_5(builder);
  1326. break;
  1327. case COMMON_CHAT_FORMAT_XIAOMI_MIMO:
  1328. common_chat_parse_xiaomi_mimo(builder);
  1329. break;
  1330. default:
  1331. throw std::runtime_error(std::string("Unsupported format: ") + common_chat_format_name(builder.syntax().format));
  1332. }
  1333. builder.finish();
  1334. }
  1335. common_chat_msg common_chat_parse(const std::string & input, bool is_partial, const common_chat_syntax & syntax) {
  1336. if (syntax.format == COMMON_CHAT_FORMAT_PEG_SIMPLE ||
  1337. syntax.format == COMMON_CHAT_FORMAT_PEG_NATIVE ||
  1338. syntax.format == COMMON_CHAT_FORMAT_PEG_CONSTRUCTED) {
  1339. return common_chat_peg_parse(syntax.parser, input, is_partial, syntax);
  1340. }
  1341. common_chat_msg_parser builder(input, is_partial, syntax);
  1342. try {
  1343. common_chat_parse(builder);
  1344. } catch (const common_chat_msg_partial_exception & ex) {
  1345. LOG_DBG("Partial parse: %s\n", ex.what());
  1346. if (!is_partial) {
  1347. builder.clear_tools();
  1348. builder.move_to(0);
  1349. common_chat_parse_content_only(builder);
  1350. }
  1351. }
  1352. auto msg = builder.result();
  1353. if (!is_partial) {
  1354. LOG_DBG("Parsed message: %s\n", common_chat_msgs_to_json_oaicompat<json>({msg}).at(0).dump().c_str());
  1355. }
  1356. return msg;
  1357. }
  1358. common_chat_msg common_chat_peg_parse(const common_peg_arena & parser, const std::string & input, bool is_partial, const common_chat_syntax & syntax) {
  1359. if (parser.empty()) {
  1360. throw std::runtime_error("Failed to parse due to missing parser definition.");
  1361. }
  1362. LOG_DBG("Parsing input with format %s: %s\n", common_chat_format_name(syntax.format), input.c_str());
  1363. common_peg_parse_context ctx(input, is_partial);
  1364. auto result = parser.parse(ctx);
  1365. if (result.fail()) {
  1366. throw std::runtime_error(std::string("Failed to parse input at pos ") + std::to_string(result.end));
  1367. }
  1368. common_chat_msg msg;
  1369. msg.role = "assistant";
  1370. if (syntax.format == COMMON_CHAT_FORMAT_PEG_NATIVE) {
  1371. auto mapper = common_chat_peg_native_mapper(msg);
  1372. mapper.from_ast(ctx.ast, result);
  1373. } else if (syntax.format == COMMON_CHAT_FORMAT_PEG_CONSTRUCTED) {
  1374. auto mapper = common_chat_peg_constructed_mapper(msg);
  1375. mapper.from_ast(ctx.ast, result);
  1376. } else {
  1377. // Generic mapper
  1378. auto mapper = common_chat_peg_mapper(msg);
  1379. mapper.from_ast(ctx.ast, result);
  1380. }
  1381. if (!is_partial) {
  1382. LOG_DBG("Parsed message: %s\n", common_chat_msgs_to_json_oaicompat<json>({msg}).at(0).dump().c_str());
  1383. }
  1384. return msg;
  1385. }