chat-parser.cpp 58 KB

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