chat-parser.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  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. return form;
  835. })();
  836. builder.consume_reasoning_with_xml_tool_calls(form, "<think>", "</think>");
  837. }
  838. static void common_chat_parse_apriel_1_5(common_chat_msg_parser & builder) {
  839. static const xml_tool_call_format form = ([]() {
  840. xml_tool_call_format form {};
  841. form.scope_start = "<tool_calls>[";
  842. form.tool_start = "{\"name\": \"";
  843. form.tool_sep = "\", \"arguments\": {";
  844. form.key_start = "\"";
  845. form.key_val_sep = "\": ";
  846. form.val_end = ", ";
  847. form.tool_end = "}, ";
  848. form.scope_end = "]</tool_calls>";
  849. form.raw_argval = false;
  850. form.last_val_end = "";
  851. form.last_tool_end = "}";
  852. return form;
  853. })();
  854. builder.consume_reasoning_with_xml_tool_calls(form, "<thinking>", "</thinking>");
  855. }
  856. static void common_chat_parse_xiaomi_mimo(common_chat_msg_parser & builder) {
  857. static const xml_tool_call_format form = ([]() {
  858. xml_tool_call_format form {};
  859. form.scope_start = "";
  860. form.tool_start = "<tool_call>\n{\"name\": \"";
  861. form.tool_sep = "\", \"arguments\": {";
  862. form.key_start = "\"";
  863. form.key_val_sep = "\": ";
  864. form.val_end = ", ";
  865. form.tool_end = "}\n</tool_call>";
  866. form.scope_end = "";
  867. form.raw_argval = false;
  868. form.last_val_end = "";
  869. return form;
  870. })();
  871. builder.consume_reasoning_with_xml_tool_calls(form);
  872. }
  873. static void common_chat_parse_gpt_oss(common_chat_msg_parser & builder) {
  874. static const std::string constraint = "(?: (<\\|constrain\\|>)?([a-zA-Z0-9_-]+))";
  875. static const std::string recipient("(?: to=functions\\.([^<\\s]+))");
  876. static const common_regex start_regex("<\\|start\\|>assistant");
  877. static const common_regex analysis_regex("<\\|channel\\|>analysis");
  878. static const common_regex final_regex("<\\|channel\\|>final" + constraint + "?");
  879. static const common_regex preamble_regex("<\\|channel\\|>commentary");
  880. static const common_regex tool_call1_regex(recipient + "<\\|channel\\|>(analysis|commentary)" + constraint + "?");
  881. static const common_regex tool_call2_regex("<\\|channel\\|>(analysis|commentary)" + recipient + constraint + "?");
  882. auto consume_end = [&](bool include_end = false) {
  883. if (auto res = builder.try_find_literal("<|end|>")) {
  884. return res->prelude + (include_end ? builder.str(res->groups[0]) : "");
  885. }
  886. return builder.consume_rest();
  887. };
  888. auto handle_tool_call = [&](const std::string & name) {
  889. if (auto args = builder.try_consume_json_with_dumped_args({{}})) {
  890. if (builder.syntax().parse_tool_calls) {
  891. if (!builder.add_tool_call(name, "", args->value) || args->is_partial) {
  892. throw common_chat_msg_partial_exception("incomplete tool call");
  893. }
  894. } else if (args->is_partial) {
  895. throw common_chat_msg_partial_exception("incomplete tool call");
  896. }
  897. }
  898. };
  899. auto regex_match = [](const common_regex & regex, const std::string & input) -> std::optional<common_regex_match> {
  900. auto match = regex.search(input, 0, true);
  901. if (match.type == COMMON_REGEX_MATCH_TYPE_FULL) {
  902. return match;
  903. }
  904. return std::nullopt;
  905. };
  906. do {
  907. auto header_start_pos = builder.pos();
  908. auto content_start = builder.try_find_literal("<|message|>");
  909. if (!content_start) {
  910. throw common_chat_msg_partial_exception("incomplete header");
  911. }
  912. auto header = content_start->prelude;
  913. if (auto match = regex_match(tool_call1_regex, header)) {
  914. auto group = match->groups[1];
  915. auto name = header.substr(group.begin, group.end - group.begin);
  916. handle_tool_call(name);
  917. continue;
  918. }
  919. if (auto match = regex_match(tool_call2_regex, header)) {
  920. auto group = match->groups[2];
  921. auto name = header.substr(group.begin, group.end - group.begin);
  922. handle_tool_call(name);
  923. continue;
  924. }
  925. if (regex_match(analysis_regex, header)) {
  926. builder.move_to(header_start_pos);
  927. if (builder.syntax().reasoning_format == COMMON_REASONING_FORMAT_NONE || builder.syntax().reasoning_in_content) {
  928. builder.add_content(consume_end(true));
  929. } else {
  930. builder.try_parse_reasoning("<|channel|>analysis<|message|>", "<|end|>");
  931. }
  932. continue;
  933. }
  934. if(regex_match(final_regex, header) || regex_match(preamble_regex, header)) {
  935. builder.add_content(consume_end());
  936. continue;
  937. }
  938. // Possibly a malformed message, attempt to recover by rolling
  939. // back to pick up the next <|start|>
  940. LOG_DBG("%s: unknown header from message: %s\n", __func__, header.c_str());
  941. builder.move_to(header_start_pos);
  942. } while (builder.try_find_regex(start_regex, std::string::npos, false));
  943. auto remaining = builder.consume_rest();
  944. if (!remaining.empty()) {
  945. LOG_DBG("%s: content after last message: %s\n", __func__, remaining.c_str());
  946. }
  947. }
  948. static void common_chat_parse_glm_4_5(common_chat_msg_parser & builder) {
  949. static const xml_tool_call_format form {
  950. /* form.scope_start = */ "",
  951. /* form.tool_start = */ "<tool_call>",
  952. /* form.tool_sep = */ "",
  953. /* form.key_start = */ "<arg_key>",
  954. /* form.key_val_sep = */ "</arg_key>",
  955. /* form.val_end = */ "</arg_value>",
  956. /* form.tool_end = */ "</tool_call>",
  957. /* form.scope_end = */ "",
  958. /* form.key_val_sep2 = */ "<arg_value>",
  959. };
  960. builder.consume_reasoning_with_xml_tool_calls(form, "<think>", "</think>");
  961. }
  962. static void common_chat_parse_firefunction_v2(common_chat_msg_parser & builder) {
  963. if (!builder.syntax().parse_tool_calls) {
  964. builder.add_content(builder.consume_rest());
  965. return;
  966. }
  967. static const common_regex prefix(regex_escape(" functools["));
  968. parse_prefixed_json_tool_call_array(builder, prefix, /* rstrip_prefix= */ 1);
  969. }
  970. static void common_chat_parse_functionary_v3_2(common_chat_msg_parser & builder) {
  971. static const common_regex function_regex_start_only(R"((\w+\n\{|python\n|all\n))");
  972. static const common_regex function_regex(R"(>>>(\w+\n\{|python\n|all\n))");
  973. static const common_regex close_regex(R"(\s*)");
  974. parse_json_tool_calls(
  975. builder,
  976. std::nullopt,
  977. function_regex_start_only,
  978. function_regex,
  979. close_regex,
  980. std::nullopt,
  981. /* allow_raw_python= */ true,
  982. /* get_function_name= */ [&](const auto & res) -> std::string {
  983. auto at_start = res.groups[0].begin == 0;
  984. auto name = builder.str(res.groups[1]);
  985. if (!name.empty() && name.back() == '{') {
  986. // Unconsume the opening brace '{' to ensure the JSON parsing goes well.
  987. builder.move_back(1);
  988. }
  989. auto idx = name.find_last_not_of("\n{");
  990. name = name.substr(0, idx + 1);
  991. if (at_start && name == "all") {
  992. return "";
  993. }
  994. return name;
  995. });
  996. }
  997. static void common_chat_parse_functionary_v3_1_llama_3_1(common_chat_msg_parser & builder) {
  998. if (!builder.syntax().parse_tool_calls) {
  999. builder.add_content(builder.consume_rest());
  1000. return;
  1001. }
  1002. // This version of Functionary still supports the llama 3.1 tool call format for the python tool.
  1003. static const common_regex python_tag_regex(regex_escape("<|python_tag|>"));
  1004. static const common_regex function_regex(R"(<function=(\w+)>)");
  1005. static const common_regex close_regex(R"(</function>)");
  1006. parse_json_tool_calls(
  1007. builder,
  1008. /* block_open= */ std::nullopt,
  1009. /* function_regex_start_only= */ std::nullopt,
  1010. function_regex,
  1011. close_regex,
  1012. std::nullopt);
  1013. if (auto res = builder.try_find_regex(python_tag_regex)) {
  1014. auto arguments = wrap_code_as_arguments(builder, builder.consume_rest());
  1015. builder.add_tool_call("python", "", arguments);
  1016. return;
  1017. }
  1018. }
  1019. static void common_chat_parse_hermes_2_pro(common_chat_msg_parser & builder) {
  1020. builder.try_parse_reasoning("<think>", "</think>");
  1021. if (!builder.syntax().parse_tool_calls) {
  1022. builder.add_content(builder.consume_rest());
  1023. return;
  1024. }
  1025. static const common_regex open_regex(
  1026. "(?:"
  1027. "(```(?:xml|json)?\\n\\s*)?" // match 1 (block_start)
  1028. "(" // match 2 (open_tag)
  1029. "<tool_call>"
  1030. "|<function_call>"
  1031. "|<tool>"
  1032. "|<tools>"
  1033. "|<response>"
  1034. "|<json>"
  1035. "|<xml>"
  1036. "|<JSON>"
  1037. ")?"
  1038. "(\\s*\\{\\s*\"name\")" // match 3 (named tool call)
  1039. ")"
  1040. "|<function=([^>]+)>" // match 4 (function name)
  1041. "|<function name=\"([^\"]+)\">" // match 5 (function name again)
  1042. );
  1043. while (auto res = builder.try_find_regex(open_regex)) {
  1044. const auto & block_start = res->groups[1];
  1045. std::string block_end = block_start.empty() ? "" : "```";
  1046. const auto & open_tag = res->groups[2];
  1047. std::string close_tag;
  1048. if (!res->groups[3].empty()) {
  1049. builder.move_to(res->groups[3].begin);
  1050. close_tag = open_tag.empty() ? "" : "</" + builder.str(open_tag).substr(1);
  1051. if (auto tool_call = builder.try_consume_json_with_dumped_args({{"arguments"}})) {
  1052. if (!builder.add_tool_call(tool_call->value) || tool_call->is_partial) {
  1053. throw common_chat_msg_partial_exception("incomplete tool call");
  1054. }
  1055. builder.consume_spaces();
  1056. builder.consume_literal(close_tag);
  1057. builder.consume_spaces();
  1058. if (!block_end.empty()) {
  1059. builder.consume_literal(block_end);
  1060. builder.consume_spaces();
  1061. }
  1062. } else {
  1063. throw common_chat_msg_partial_exception("failed to parse tool call");
  1064. }
  1065. } else {
  1066. auto function_name = builder.str(res->groups[4]);
  1067. if (function_name.empty()) {
  1068. function_name = builder.str(res->groups[5]);
  1069. }
  1070. GGML_ASSERT(!function_name.empty());
  1071. close_tag = "</function>";
  1072. if (auto arguments = builder.try_consume_json_with_dumped_args({{}})) {
  1073. if (!builder.add_tool_call(function_name, "", arguments->value) || arguments->is_partial) {
  1074. throw common_chat_msg_partial_exception("incomplete tool call");
  1075. }
  1076. builder.consume_spaces();
  1077. builder.consume_literal(close_tag);
  1078. builder.consume_spaces();
  1079. if (!block_end.empty()) {
  1080. builder.consume_literal(block_end);
  1081. builder.consume_spaces();
  1082. }
  1083. }
  1084. }
  1085. }
  1086. builder.add_content(builder.consume_rest());
  1087. }
  1088. static void common_chat_parse_granite(common_chat_msg_parser & builder) {
  1089. // Parse thinking tags
  1090. static const common_regex start_think_regex(regex_escape("<think>"));
  1091. static const common_regex end_think_regex(regex_escape("</think>"));
  1092. // Granite models output partial tokens such as "<" and "<think".
  1093. // By leveraging try_consume_regex()/try_find_regex() throwing
  1094. // common_chat_msg_partial_exception for these partial tokens,
  1095. // processing is interrupted and the tokens are not passed to add_content().
  1096. if (auto res = builder.try_consume_regex(start_think_regex)) {
  1097. // Restore position for try_parse_reasoning()
  1098. builder.move_to(res->groups[0].begin);
  1099. builder.try_find_regex(end_think_regex, std::string::npos, false);
  1100. // Restore position for try_parse_reasoning()
  1101. builder.move_to(res->groups[0].begin);
  1102. }
  1103. builder.try_parse_reasoning("<think>", "</think>");
  1104. // Parse response tags
  1105. static const common_regex start_response_regex(regex_escape("<response>"));
  1106. static const common_regex end_response_regex(regex_escape("</response>"));
  1107. // Granite models output partial tokens such as "<" and "<response".
  1108. // Same hack as reasoning parsing.
  1109. if (builder.try_consume_regex(start_response_regex)) {
  1110. builder.try_find_regex(end_response_regex);
  1111. }
  1112. if (!builder.syntax().parse_tool_calls) {
  1113. builder.add_content(builder.consume_rest());
  1114. return;
  1115. }
  1116. // Look for tool calls
  1117. static const common_regex tool_call_regex(regex_escape("<|tool_call|>"));
  1118. if (auto res = builder.try_find_regex(tool_call_regex)) {
  1119. builder.move_to(res->groups[0].end);
  1120. // Expect JSON array of tool calls
  1121. if (auto tool_call = builder.try_consume_json_with_dumped_args({{{"arguments"}}})) {
  1122. if (!builder.add_tool_calls(tool_call->value) || tool_call->is_partial) {
  1123. throw common_chat_msg_partial_exception("incomplete tool call");
  1124. }
  1125. }
  1126. } else {
  1127. builder.add_content(builder.consume_rest());
  1128. }
  1129. }
  1130. static void common_chat_parse_nemotron_v2(common_chat_msg_parser & builder) {
  1131. // Parse thinking tags
  1132. builder.try_parse_reasoning("<think>", "</think>");
  1133. if (!builder.syntax().parse_tool_calls) {
  1134. builder.add_content(builder.consume_rest());
  1135. return;
  1136. }
  1137. // Look for tool calls
  1138. static const common_regex tool_call_regex(regex_escape("<TOOLCALL>"));
  1139. if (auto res = builder.try_find_regex(tool_call_regex)) {
  1140. builder.move_to(res->groups[0].end);
  1141. // Expect JSON array of tool calls
  1142. auto tool_calls_data = builder.consume_json();
  1143. if (tool_calls_data.json.is_array()) {
  1144. if (!builder.try_consume_literal("</TOOLCALL>")) {
  1145. throw common_chat_msg_partial_exception("Incomplete tool call");
  1146. }
  1147. builder.add_tool_calls(tool_calls_data.json);
  1148. } else {
  1149. throw common_chat_msg_partial_exception("Incomplete tool call");
  1150. }
  1151. }
  1152. builder.add_content(builder.consume_rest());
  1153. }
  1154. static void common_chat_parse_apertus(common_chat_msg_parser & builder) {
  1155. // Parse thinking tags
  1156. builder.try_parse_reasoning("<|inner_prefix|>", "<|inner_suffix|>");
  1157. if (!builder.syntax().parse_tool_calls) {
  1158. builder.add_content(builder.consume_rest());
  1159. return;
  1160. }
  1161. // Look for tool calls
  1162. static const common_regex tool_call_regex(regex_escape("<|tools_prefix|>"));
  1163. if (auto res = builder.try_find_regex(tool_call_regex)) {
  1164. builder.move_to(res->groups[0].end);
  1165. auto tool_calls_data = builder.consume_json();
  1166. if (tool_calls_data.json.is_array()) {
  1167. builder.consume_spaces();
  1168. if (!builder.try_consume_literal("<|tools_suffix|>")) {
  1169. throw common_chat_msg_partial_exception("Incomplete tool call");
  1170. }
  1171. for (const auto & value : tool_calls_data.json) {
  1172. if (value.is_object()) {
  1173. builder.add_tool_call_short_form(value);
  1174. }
  1175. }
  1176. } else {
  1177. throw common_chat_msg_partial_exception("Incomplete tool call");
  1178. }
  1179. }
  1180. builder.add_content(builder.consume_rest());
  1181. }
  1182. static void common_chat_parse_lfm2(common_chat_msg_parser & builder) {
  1183. if (!builder.syntax().parse_tool_calls) {
  1184. builder.add_content(builder.consume_rest());
  1185. return;
  1186. }
  1187. // LFM2 format: <|tool_call_start|>[{"name": "get_current_time", "arguments": {"location": "Paris"}}]<|tool_call_end|>
  1188. static const common_regex tool_call_start_regex(regex_escape("<|tool_call_start|>"));
  1189. static const common_regex tool_call_end_regex(regex_escape("<|tool_call_end|>"));
  1190. // Loop through all tool calls
  1191. while (auto res = builder.try_find_regex(tool_call_start_regex, std::string::npos, /* add_prelude_to_content= */ true)) {
  1192. builder.move_to(res->groups[0].end);
  1193. // Parse JSON array format: [{"name": "...", "arguments": {...}}]
  1194. auto tool_calls_data = builder.consume_json();
  1195. // Consume end marker
  1196. builder.consume_spaces();
  1197. if (!builder.try_consume_regex(tool_call_end_regex)) {
  1198. throw common_chat_msg_partial_exception("Expected <|tool_call_end|>");
  1199. }
  1200. // Process each tool call in the array
  1201. if (tool_calls_data.json.is_array()) {
  1202. for (const auto & tool_call : tool_calls_data.json) {
  1203. if (!tool_call.is_object()) {
  1204. throw common_chat_msg_partial_exception("Tool call must be an object");
  1205. }
  1206. if (!tool_call.contains("name")) {
  1207. throw common_chat_msg_partial_exception("Tool call missing 'name' field");
  1208. }
  1209. std::string function_name = tool_call.at("name");
  1210. std::string arguments = "{}";
  1211. if (tool_call.contains("arguments")) {
  1212. if (tool_call.at("arguments").is_object()) {
  1213. arguments = tool_call.at("arguments").dump();
  1214. } else if (tool_call.at("arguments").is_string()) {
  1215. arguments = tool_call.at("arguments");
  1216. }
  1217. }
  1218. if (!builder.add_tool_call(function_name, "", arguments)) {
  1219. throw common_chat_msg_partial_exception("Incomplete tool call");
  1220. }
  1221. }
  1222. } else {
  1223. throw common_chat_msg_partial_exception("Expected JSON array for tool calls");
  1224. }
  1225. // Consume any trailing whitespace after this tool call
  1226. builder.consume_spaces();
  1227. }
  1228. // Consume any remaining content after all tool calls
  1229. auto remaining = builder.consume_rest();
  1230. if (!string_strip(remaining).empty()) {
  1231. builder.add_content(remaining);
  1232. }
  1233. }
  1234. static void common_chat_parse_seed_oss(common_chat_msg_parser & builder) {
  1235. static const xml_tool_call_format form {
  1236. /* form.scope_start = */ "<seed:tool_call>",
  1237. /* form.tool_start = */ "<function=",
  1238. /* form.tool_sep = */ ">",
  1239. /* form.key_start = */ "<parameter=",
  1240. /* form.key_val_sep = */ ">",
  1241. /* form.val_end = */ "</parameter>",
  1242. /* form.tool_end = */ "</function>",
  1243. /* form.scope_end = */ "</seed:tool_call>",
  1244. };
  1245. builder.consume_reasoning_with_xml_tool_calls(form, "<seed:think>", "</seed:think>");
  1246. }
  1247. static void common_chat_parse_content_only(common_chat_msg_parser & builder) {
  1248. builder.try_parse_reasoning("<think>", "</think>");
  1249. builder.add_content(builder.consume_rest());
  1250. }
  1251. static void common_chat_parse(common_chat_msg_parser & builder) {
  1252. LOG_DBG("Parsing input with format %s: %s\n", common_chat_format_name(builder.syntax().format), builder.input().c_str());
  1253. switch (builder.syntax().format) {
  1254. case COMMON_CHAT_FORMAT_CONTENT_ONLY:
  1255. common_chat_parse_content_only(builder);
  1256. break;
  1257. case COMMON_CHAT_FORMAT_GENERIC:
  1258. common_chat_parse_generic(builder);
  1259. break;
  1260. case COMMON_CHAT_FORMAT_MISTRAL_NEMO:
  1261. common_chat_parse_mistral_nemo(builder);
  1262. break;
  1263. case COMMON_CHAT_FORMAT_MAGISTRAL:
  1264. common_chat_parse_magistral(builder);
  1265. break;
  1266. case COMMON_CHAT_FORMAT_LLAMA_3_X:
  1267. common_chat_parse_llama_3_1(builder);
  1268. break;
  1269. case COMMON_CHAT_FORMAT_LLAMA_3_X_WITH_BUILTIN_TOOLS:
  1270. common_chat_parse_llama_3_1(builder, /* with_builtin_tools= */ true);
  1271. break;
  1272. case COMMON_CHAT_FORMAT_DEEPSEEK_R1:
  1273. common_chat_parse_deepseek_r1(builder);
  1274. break;
  1275. case COMMON_CHAT_FORMAT_DEEPSEEK_V3_1:
  1276. common_chat_parse_deepseek_v3_1(builder);
  1277. break;
  1278. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_2:
  1279. common_chat_parse_functionary_v3_2(builder);
  1280. break;
  1281. case COMMON_CHAT_FORMAT_FUNCTIONARY_V3_1_LLAMA_3_1:
  1282. common_chat_parse_functionary_v3_1_llama_3_1(builder);
  1283. break;
  1284. case COMMON_CHAT_FORMAT_HERMES_2_PRO:
  1285. common_chat_parse_hermes_2_pro(builder);
  1286. break;
  1287. case COMMON_CHAT_FORMAT_FIREFUNCTION_V2:
  1288. common_chat_parse_firefunction_v2(builder);
  1289. break;
  1290. case COMMON_CHAT_FORMAT_COMMAND_R7B:
  1291. common_chat_parse_command_r7b(builder);
  1292. break;
  1293. case COMMON_CHAT_FORMAT_GRANITE:
  1294. common_chat_parse_granite(builder);
  1295. break;
  1296. case COMMON_CHAT_FORMAT_GPT_OSS:
  1297. common_chat_parse_gpt_oss(builder);
  1298. break;
  1299. case COMMON_CHAT_FORMAT_SEED_OSS:
  1300. common_chat_parse_seed_oss(builder);
  1301. break;
  1302. case COMMON_CHAT_FORMAT_NEMOTRON_V2:
  1303. common_chat_parse_nemotron_v2(builder);
  1304. break;
  1305. case COMMON_CHAT_FORMAT_APERTUS:
  1306. common_chat_parse_apertus(builder);
  1307. break;
  1308. case COMMON_CHAT_FORMAT_LFM2_WITH_JSON_TOOLS:
  1309. common_chat_parse_lfm2(builder);
  1310. break;
  1311. case COMMON_CHAT_FORMAT_MINIMAX_M2:
  1312. common_chat_parse_minimax_m2(builder);
  1313. break;
  1314. case COMMON_CHAT_FORMAT_GLM_4_5:
  1315. common_chat_parse_glm_4_5(builder);
  1316. break;
  1317. case COMMON_CHAT_FORMAT_KIMI_K2:
  1318. common_chat_parse_kimi_k2(builder);
  1319. break;
  1320. case COMMON_CHAT_FORMAT_QWEN3_CODER_XML:
  1321. common_chat_parse_qwen3_coder_xml(builder);
  1322. break;
  1323. case COMMON_CHAT_FORMAT_APRIEL_1_5:
  1324. common_chat_parse_apriel_1_5(builder);
  1325. break;
  1326. case COMMON_CHAT_FORMAT_XIAOMI_MIMO:
  1327. common_chat_parse_xiaomi_mimo(builder);
  1328. break;
  1329. default:
  1330. throw std::runtime_error(std::string("Unsupported format: ") + common_chat_format_name(builder.syntax().format));
  1331. }
  1332. builder.finish();
  1333. }
  1334. common_chat_msg common_chat_parse(const std::string & input, bool is_partial, const common_chat_syntax & syntax) {
  1335. if (syntax.format == COMMON_CHAT_FORMAT_PEG_SIMPLE ||
  1336. syntax.format == COMMON_CHAT_FORMAT_PEG_NATIVE ||
  1337. syntax.format == COMMON_CHAT_FORMAT_PEG_CONSTRUCTED) {
  1338. return common_chat_peg_parse(syntax.parser, input, is_partial, syntax);
  1339. }
  1340. common_chat_msg_parser builder(input, is_partial, syntax);
  1341. try {
  1342. common_chat_parse(builder);
  1343. } catch (const common_chat_msg_partial_exception & ex) {
  1344. LOG_DBG("Partial parse: %s\n", ex.what());
  1345. if (!is_partial) {
  1346. builder.clear_tools();
  1347. builder.move_to(0);
  1348. common_chat_parse_content_only(builder);
  1349. }
  1350. }
  1351. auto msg = builder.result();
  1352. if (!is_partial) {
  1353. LOG_DBG("Parsed message: %s\n", common_chat_msgs_to_json_oaicompat<json>({msg}).at(0).dump().c_str());
  1354. }
  1355. return msg;
  1356. }
  1357. common_chat_msg common_chat_peg_parse(const common_peg_arena & parser, const std::string & input, bool is_partial, const common_chat_syntax & syntax) {
  1358. if (parser.empty()) {
  1359. throw std::runtime_error("Failed to parse due to missing parser definition.");
  1360. }
  1361. LOG_DBG("Parsing input with format %s: %s\n", common_chat_format_name(syntax.format), input.c_str());
  1362. common_peg_parse_context ctx(input, is_partial);
  1363. auto result = parser.parse(ctx);
  1364. if (result.fail()) {
  1365. throw std::runtime_error(std::string("Failed to parse input at pos ") + std::to_string(result.end));
  1366. }
  1367. common_chat_msg msg;
  1368. msg.role = "assistant";
  1369. if (syntax.format == COMMON_CHAT_FORMAT_PEG_NATIVE) {
  1370. auto mapper = common_chat_peg_native_mapper(msg);
  1371. mapper.from_ast(ctx.ast, result);
  1372. } else if (syntax.format == COMMON_CHAT_FORMAT_PEG_CONSTRUCTED) {
  1373. auto mapper = common_chat_peg_constructed_mapper(msg);
  1374. mapper.from_ast(ctx.ast, result);
  1375. } else {
  1376. // Generic mapper
  1377. auto mapper = common_chat_peg_mapper(msg);
  1378. mapper.from_ast(ctx.ast, result);
  1379. }
  1380. if (!is_partial) {
  1381. LOG_DBG("Parsed message: %s\n", common_chat_msgs_to_json_oaicompat<json>({msg}).at(0).dump().c_str());
  1382. }
  1383. return msg;
  1384. }