1
0

chat-parser.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. common_chat_msg_parser::common_chat_msg_parser(const std::string & input, bool is_partial, const common_chat_syntax & syntax)
  14. : input_(input), is_partial_(is_partial), syntax_(syntax)
  15. {
  16. result_.role = "assistant";
  17. while (true) {
  18. std::string id = std::to_string(std::rand());
  19. if (input.find(id) == std::string::npos) {
  20. healing_marker_ = id;
  21. break;
  22. }
  23. }
  24. }
  25. std::string common_chat_msg_parser::str(const common_string_range & rng) const {
  26. GGML_ASSERT(rng.begin <= rng.end);
  27. return input_.substr(rng.begin, rng.end - rng.begin);
  28. }
  29. void common_chat_msg_parser::add_content(const std::string &content) {
  30. result_.content += content;
  31. }
  32. void common_chat_msg_parser::add_reasoning_content(const std::string &reasoning_content) {
  33. result_.reasoning_content += reasoning_content;
  34. }
  35. bool common_chat_msg_parser::add_tool_call(const std::string & name, const std::string & id, const std::string & arguments) {
  36. if (name.empty()) {
  37. return false;
  38. }
  39. common_chat_tool_call tool_call;
  40. tool_call.name = name;
  41. tool_call.arguments = arguments;
  42. tool_call.id = id;
  43. // LOG_DBG("Tool call arguments:\n\traw: %s\n\tresult: %s\n", arguments.c_str(), tool_call.arguments.c_str());
  44. result_.tool_calls.emplace_back(tool_call);
  45. return true;
  46. }
  47. bool common_chat_msg_parser::add_tool_call(const json & tool_call) {
  48. std::string name = tool_call.contains("name") ? tool_call.at("name") : "";
  49. std::string id = tool_call.contains("id") ? tool_call.at("id") : "";
  50. std::string arguments = "";
  51. if (tool_call.contains("arguments")) {
  52. if (tool_call.at("arguments").is_object()) {
  53. arguments = tool_call.at("arguments").dump();
  54. } else {
  55. arguments = tool_call.at("arguments");
  56. }
  57. }
  58. return add_tool_call(name, id, arguments);
  59. }
  60. bool common_chat_msg_parser::add_tool_calls(const json & arr) {
  61. for (const auto & item : arr) {
  62. if (!add_tool_call(item)) {
  63. return false;
  64. }
  65. }
  66. return true;
  67. }
  68. bool common_chat_msg_parser::add_tool_call_short_form(const json & tool_call) {
  69. if (!tool_call.is_object() || tool_call.size() != 1) {
  70. return false;
  71. }
  72. // Get the tool name (the single key in the object)
  73. auto it = tool_call.begin();
  74. std::string name = it.key();
  75. if (name.empty()) {
  76. return false;
  77. }
  78. // Get the arguments (the nested object)
  79. const json & args_json = it.value();
  80. std::string arguments = "";
  81. if (args_json.is_object()) {
  82. arguments = args_json.dump();
  83. } else if (args_json.is_string()) {
  84. arguments = args_json;
  85. } else if (!args_json.is_null()) {
  86. // For other types, convert to string representation
  87. arguments = args_json.dump();
  88. }
  89. return add_tool_call(name, "", arguments);
  90. }
  91. void common_chat_msg_parser::finish() {
  92. if (!is_partial_ && pos_ != input_.size()) {
  93. throw std::runtime_error("Unexpected content at end of input");// + input_.substr(pos_));
  94. }
  95. }
  96. bool common_chat_msg_parser::consume_spaces() {
  97. const auto length = input_.size();
  98. auto consumed = false;
  99. while (pos_ < length && std::isspace(input_[pos_])) {
  100. ++pos_;
  101. consumed = true;
  102. }
  103. return consumed;
  104. }
  105. bool common_chat_msg_parser::try_consume_literal(const std::string & literal) {
  106. auto pos = pos_;
  107. for (auto i = 0u; i < literal.size(); ++i) {
  108. if (pos >= input_.size()) {
  109. return false;
  110. }
  111. if (input_[pos] != literal[i]) {
  112. return false;
  113. }
  114. ++pos;
  115. }
  116. pos_ = pos;
  117. return true;
  118. }
  119. std::optional<common_chat_msg_parser::find_regex_result> common_chat_msg_parser::try_find_literal(const std::string & literal) {
  120. auto idx = input_.find(literal, pos_);
  121. if (idx != std::string::npos) {
  122. find_regex_result res;
  123. res.prelude = input_.substr(pos_, idx - pos_);
  124. auto end = idx + literal.size();
  125. res.groups.emplace_back(common_string_range{idx, end});
  126. move_to(end);
  127. return res;
  128. }
  129. if (is_partial_) {
  130. idx = string_find_partial_stop(input_, literal);
  131. if (idx != std::string::npos && idx >= pos_) {
  132. find_regex_result res;
  133. res.prelude = input_.substr(pos_, idx - pos_);
  134. auto end = input_.size();
  135. res.groups.emplace_back(common_string_range{idx, end});
  136. move_to(end);
  137. return res;
  138. }
  139. }
  140. return std::nullopt;
  141. }
  142. void common_chat_msg_parser::consume_literal(const std::string & literal) {
  143. if (!try_consume_literal(literal)) {
  144. throw common_chat_msg_partial_exception(literal);
  145. }
  146. }
  147. bool common_chat_msg_parser::try_parse_reasoning(const std::string & start_think, const std::string & end_think) {
  148. std::string pending_reasoning_prefix;
  149. if (syntax_.reasoning_format == COMMON_REASONING_FORMAT_NONE) {
  150. return false;
  151. }
  152. auto set_reasoning_prefix = [&](size_t prefix_pos) {
  153. if (!syntax_.thinking_forced_open || syntax_.reasoning_in_content) {
  154. return;
  155. }
  156. if (prefix_pos + start_think.size() > input_.size()) {
  157. pending_reasoning_prefix.clear();
  158. return;
  159. }
  160. // Capture the exact literal that opened the reasoning section so we can
  161. // surface it back to callers. This ensures formats that force the
  162. // reasoning tag open (e.g. DeepSeek R1) retain their original prefix
  163. // instead of dropping it during parsing.
  164. pending_reasoning_prefix = input_.substr(prefix_pos, start_think.size());
  165. };
  166. auto handle_reasoning = [&](const std::string & reasoning, bool closed) {
  167. auto stripped_reasoning = string_strip(reasoning);
  168. if (stripped_reasoning.empty()) {
  169. return;
  170. }
  171. if (syntax_.reasoning_in_content) {
  172. add_content(syntax_.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK ? "<think>" : start_think);
  173. add_content(stripped_reasoning);
  174. if (closed) {
  175. add_content(syntax_.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK ? "</think>" : end_think);
  176. }
  177. } else {
  178. if (!pending_reasoning_prefix.empty()) {
  179. add_reasoning_content(pending_reasoning_prefix);
  180. pending_reasoning_prefix.clear();
  181. }
  182. add_reasoning_content(stripped_reasoning);
  183. }
  184. };
  185. const size_t saved_pos = pos_;
  186. const size_t saved_content_size = result_.content.size();
  187. const size_t saved_reasoning_size = result_.reasoning_content.size();
  188. auto restore_state = [&]() {
  189. move_to(saved_pos);
  190. result_.content.resize(saved_content_size);
  191. result_.reasoning_content.resize(saved_reasoning_size);
  192. };
  193. // Allow leading whitespace to be preserved as content when reasoning is present at the start
  194. size_t cursor = pos_;
  195. size_t whitespace_end = cursor;
  196. while (whitespace_end < input_.size() && std::isspace(static_cast<unsigned char>(input_[whitespace_end]))) {
  197. ++whitespace_end;
  198. }
  199. if (whitespace_end >= input_.size()) {
  200. restore_state();
  201. if (syntax_.thinking_forced_open) {
  202. auto rest = input_.substr(saved_pos);
  203. if (!rest.empty()) {
  204. handle_reasoning(rest, /* closed */ !is_partial());
  205. }
  206. move_to(input_.size());
  207. return true;
  208. }
  209. return false;
  210. }
  211. cursor = whitespace_end;
  212. const size_t remaining = input_.size() - cursor;
  213. const size_t start_prefix = std::min(start_think.size(), remaining);
  214. const bool has_start_tag = input_.compare(cursor, start_prefix, start_think, 0, start_prefix) == 0;
  215. if (has_start_tag && start_prefix < start_think.size()) {
  216. move_to(input_.size());
  217. return true;
  218. }
  219. if (has_start_tag) {
  220. if (whitespace_end > pos_) {
  221. add_content(input_.substr(pos_, whitespace_end - pos_));
  222. }
  223. set_reasoning_prefix(cursor);
  224. cursor += start_think.size();
  225. } else if (syntax_.thinking_forced_open) {
  226. cursor = whitespace_end;
  227. } else {
  228. restore_state();
  229. return false;
  230. }
  231. while (true) {
  232. if (cursor >= input_.size()) {
  233. move_to(input_.size());
  234. return true;
  235. }
  236. size_t end_pos = input_.find(end_think, cursor);
  237. if (end_pos == std::string::npos) {
  238. std::string_view remaining_view(input_.data() + cursor, input_.size() - cursor);
  239. size_t partial_off = string_find_partial_stop(remaining_view, end_think);
  240. size_t reasoning_end = partial_off == std::string::npos ? input_.size() : cursor + partial_off;
  241. if (reasoning_end > cursor) {
  242. handle_reasoning(input_.substr(cursor, reasoning_end - cursor), /* closed */ partial_off == std::string::npos && !is_partial());
  243. }
  244. move_to(input_.size());
  245. return true;
  246. }
  247. if (end_pos > cursor) {
  248. handle_reasoning(input_.substr(cursor, end_pos - cursor), /* closed */ true);
  249. } else {
  250. handle_reasoning("", /* closed */ true);
  251. }
  252. cursor = end_pos + end_think.size();
  253. while (cursor < input_.size() && std::isspace(static_cast<unsigned char>(input_[cursor]))) {
  254. ++cursor;
  255. }
  256. const size_t next_remaining = input_.size() - cursor;
  257. if (next_remaining == 0) {
  258. move_to(cursor);
  259. return true;
  260. }
  261. const size_t next_prefix = std::min(start_think.size(), next_remaining);
  262. if (input_.compare(cursor, next_prefix, start_think, 0, next_prefix) == 0) {
  263. if (next_prefix < start_think.size()) {
  264. move_to(input_.size());
  265. return true;
  266. }
  267. set_reasoning_prefix(cursor);
  268. cursor += start_think.size();
  269. continue;
  270. }
  271. move_to(cursor);
  272. return true;
  273. }
  274. }
  275. std::string common_chat_msg_parser::consume_rest() {
  276. auto rest = input_.substr(pos_);
  277. pos_ = input_.size();
  278. return rest;
  279. }
  280. // Tries to find the regex, consumes it (pos right after it) and gives the prelude (right before it) and the groups to the callback.
  281. 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) {
  282. auto m = regex.search(input_, from == std::string::npos ? pos_ : from);
  283. if (m.type == COMMON_REGEX_MATCH_TYPE_NONE) {
  284. return std::nullopt;
  285. }
  286. auto prelude = input_.substr(pos_, m.groups[0].begin - pos_);
  287. pos_ = m.groups[0].end;
  288. if (add_prelude_to_content) {
  289. add_content(prelude);
  290. }
  291. if (m.type == COMMON_REGEX_MATCH_TYPE_PARTIAL) {
  292. if (is_partial()) {
  293. throw common_chat_msg_partial_exception(regex.str());
  294. }
  295. return std::nullopt;
  296. }
  297. return find_regex_result{prelude, m.groups};
  298. }
  299. common_chat_msg_parser::find_regex_result common_chat_msg_parser::consume_regex(const common_regex & regex) {
  300. if (auto result = try_consume_regex(regex)) {
  301. return *result;
  302. }
  303. throw common_chat_msg_partial_exception(regex.str());
  304. }
  305. std::optional<common_chat_msg_parser::find_regex_result> common_chat_msg_parser::try_consume_regex(const common_regex & regex) {
  306. auto m = regex.search(input_, pos_);
  307. if (m.type == COMMON_REGEX_MATCH_TYPE_NONE) {
  308. return std::nullopt;
  309. }
  310. if (m.type == COMMON_REGEX_MATCH_TYPE_PARTIAL) {
  311. if (is_partial()) {
  312. throw common_chat_msg_partial_exception(regex.str());
  313. }
  314. return std::nullopt;
  315. }
  316. if (m.groups[0].begin != pos_) {
  317. // Didn't match at the current position.
  318. return std::nullopt;
  319. }
  320. pos_ = m.groups[0].end;
  321. return find_regex_result {
  322. /* .prelude = */ "",
  323. m.groups,
  324. };
  325. }
  326. std::optional<common_json> common_chat_msg_parser::try_consume_json() {
  327. auto it = input_.cbegin() + pos_;
  328. const auto end = input_.cend();
  329. common_json result;
  330. if (!common_json_parse(it, end, healing_marker_, result)) {
  331. return std::nullopt;
  332. }
  333. pos_ = std::distance(input_.cbegin(), it);
  334. if (result.healing_marker.marker.empty()) {
  335. // No healing marker, just return the parsed json
  336. return result;
  337. }
  338. if (!is_partial()) {
  339. throw common_chat_msg_partial_exception("JSON");
  340. }
  341. return result;
  342. }
  343. common_json common_chat_msg_parser::consume_json() {
  344. if (auto result = try_consume_json()) {
  345. return *result;
  346. }
  347. throw common_chat_msg_partial_exception("JSON");
  348. }
  349. common_chat_msg_parser::consume_json_result common_chat_msg_parser::consume_json_with_dumped_args(
  350. const std::vector<std::vector<std::string>> & args_paths,
  351. const std::vector<std::vector<std::string>> & content_paths
  352. ) {
  353. if (auto result = try_consume_json_with_dumped_args(args_paths, content_paths)) {
  354. return *result;
  355. }
  356. throw common_chat_msg_partial_exception("JSON");
  357. }
  358. std::optional<common_chat_msg_parser::consume_json_result> common_chat_msg_parser::try_consume_json_with_dumped_args(
  359. const std::vector<std::vector<std::string>> & args_paths,
  360. const std::vector<std::vector<std::string>> & content_paths
  361. ) {
  362. auto partial = try_consume_json();
  363. if (!partial) {
  364. return std::nullopt;
  365. }
  366. auto is_arguments_path = [&](const std::vector<std::string> & path) {
  367. return std::find(args_paths.begin(), args_paths.end(), path) != args_paths.end();
  368. };
  369. auto is_content_path = [&](const std::vector<std::string> & path) {
  370. return std::find(content_paths.begin(), content_paths.end(), path) != content_paths.end();
  371. };
  372. if (partial->healing_marker.marker.empty()) {
  373. if (args_paths.empty()) {
  374. // No arguments to dump, and JSON was parsed fully.
  375. return consume_json_result {
  376. partial->json,
  377. /* .is_partial = */ false,
  378. };
  379. }
  380. if (is_arguments_path({})) {
  381. // Entire JSON is the arguments and was parsed fully.
  382. return consume_json_result {
  383. partial->json.dump(/* indent */ -1, /* indent_char */ ' ', /* ensure_ascii */ true),
  384. /* .is_partial = */ false,
  385. };
  386. }
  387. }
  388. LOG_DBG("Parsed partial JSON: %s (json_healing_marker: %s)\n", partial->json.dump().c_str(), partial->healing_marker.json_dump_marker.c_str());
  389. auto found_healing_marker = false;
  390. std::vector<std::string> path;
  391. std::function<json(const json &)> remove_unsupported_healings_and_dump_args = [&](const json & j) -> json {
  392. if (is_arguments_path(path)) {
  393. auto arguments = j.dump(/* indent */ -1, /* indent_char */ ' ', /* ensure_ascii */ true);
  394. if (is_partial() && !partial->healing_marker.marker.empty()) {
  395. auto idx = arguments.find(partial->healing_marker.json_dump_marker);
  396. if (idx != std::string::npos) {
  397. arguments.resize(idx);
  398. found_healing_marker = true;
  399. }
  400. if (arguments == "\"") {
  401. // This happens because of completing `:"$magic` after `"arguments"`
  402. arguments = "";
  403. }
  404. }
  405. return arguments;
  406. }
  407. if (is_content_path(path)) {
  408. if (!j.is_string()) {
  409. throw std::runtime_error("Content path must be a string");
  410. }
  411. std::string str = j;
  412. auto idx = str.find(partial->healing_marker.marker); // not using json_dump_marker as we're inside a string
  413. if (idx != std::string::npos) {
  414. str.resize(idx);
  415. found_healing_marker = true;
  416. }
  417. return str;
  418. }
  419. if (j.is_object()) {
  420. auto obj = json::object();
  421. for (const auto & p : j.items()) {
  422. const auto & key = p.key();
  423. const auto & value = p.value();
  424. const std::string key_str = key; // NOLINT
  425. auto idx = key_str.find(healing_marker_);
  426. if (idx != std::string::npos) {
  427. found_healing_marker = true;
  428. break;
  429. }
  430. path.push_back(key_str);
  431. if (value.is_string()) {
  432. const std::string value_str = value;
  433. if (value_str.find(healing_marker_) != std::string::npos) {
  434. found_healing_marker = true;
  435. if (is_content_path(path)) {
  436. if (partial->healing_marker.marker == partial->healing_marker.json_dump_marker) {
  437. // The healing occurred inside the string: good. Otherwise we just ditch the entire key/value pair.
  438. obj[key] = remove_unsupported_healings_and_dump_args(value);
  439. }
  440. }
  441. break;
  442. }
  443. obj[key] = value;
  444. } else {
  445. obj[key] = remove_unsupported_healings_and_dump_args(value);
  446. }
  447. path.pop_back();
  448. }
  449. return obj;
  450. }
  451. if (j.is_array()) {
  452. auto arr = json::array();
  453. for (const auto & value : j) {
  454. if (value.is_string()) {
  455. std::string str = value;
  456. auto idx = str.find(healing_marker_);
  457. if (idx != std::string::npos) {
  458. // Don't heal array values that aren't in the arguments.
  459. found_healing_marker = true;
  460. break;
  461. }
  462. }
  463. arr.push_back(remove_unsupported_healings_and_dump_args(value));
  464. }
  465. return arr;
  466. }
  467. return j;
  468. };
  469. auto cleaned = remove_unsupported_healings_and_dump_args(partial->json);
  470. 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());
  471. return consume_json_result {
  472. cleaned,
  473. /* .is_partial = */ found_healing_marker,
  474. };
  475. }
  476. void common_chat_msg_parser::clear_tools() {
  477. result_.tool_calls.clear();
  478. }