chat-parser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. #include "chat-parser.h"
  2. #include "common.h"
  3. #include "log.h"
  4. #include "regex-partial.h"
  5. #include <optional>
  6. #include <stdexcept>
  7. #include <string>
  8. #include <vector>
  9. using json = nlohmann::ordered_json;
  10. common_chat_msg_parser::common_chat_msg_parser(const std::string & input, bool is_partial, const common_chat_syntax & syntax)
  11. : input_(input), is_partial_(is_partial), syntax_(syntax)
  12. {
  13. result_.role = "assistant";
  14. while (true) {
  15. std::string id = std::to_string(std::rand());
  16. if (input.find(id) == std::string::npos) {
  17. healing_marker_ = id;
  18. break;
  19. }
  20. }
  21. }
  22. std::string common_chat_msg_parser::str(const common_string_range & rng) const {
  23. GGML_ASSERT(rng.begin <= rng.end);
  24. return input_.substr(rng.begin, rng.end - rng.begin);
  25. }
  26. void common_chat_msg_parser::add_content(const std::string &content) {
  27. result_.content += content;
  28. }
  29. void common_chat_msg_parser::add_reasoning_content(const std::string &reasoning_content) {
  30. result_.reasoning_content += reasoning_content;
  31. }
  32. bool common_chat_msg_parser::add_tool_call(const std::string & name, const std::string & id, const std::string & arguments) {
  33. if (name.empty()) {
  34. return false;
  35. }
  36. common_chat_tool_call tool_call;
  37. tool_call.name = name;
  38. tool_call.arguments = arguments;
  39. tool_call.id = id;
  40. // LOG_DBG("Tool call arguments:\n\traw: %s\n\tresult: %s\n", arguments.c_str(), tool_call.arguments.c_str());
  41. result_.tool_calls.emplace_back(tool_call);
  42. return true;
  43. }
  44. bool common_chat_msg_parser::add_tool_call(const json & tool_call) {
  45. std::string name = tool_call.contains("name") ? tool_call.at("name") : "";
  46. std::string id = tool_call.contains("id") ? tool_call.at("id") : "";
  47. std::string arguments = tool_call.contains("arguments") ? tool_call.at("arguments") : "";
  48. return add_tool_call(name, id, arguments);
  49. }
  50. bool common_chat_msg_parser::add_tool_calls(const json & arr) {
  51. for (const auto & item : arr) {
  52. if (!add_tool_call(item)) {
  53. return false;
  54. }
  55. }
  56. return true;
  57. }
  58. void common_chat_msg_parser::finish() {
  59. if (!is_partial_ && pos_ != input_.size()) {
  60. throw std::runtime_error("Unexpected content at end of input");// + input_.substr(pos_));
  61. }
  62. }
  63. bool common_chat_msg_parser::consume_spaces() {
  64. const auto length = input_.size();
  65. auto consumed = false;
  66. while (pos_ < length && std::isspace(input_[pos_])) {
  67. ++pos_;
  68. consumed = true;
  69. }
  70. return consumed;
  71. }
  72. bool common_chat_msg_parser::try_consume_literal(const std::string & literal) {
  73. auto pos = pos_;
  74. for (auto i = 0u; i < literal.size(); ++i) {
  75. if (pos >= input_.size()) {
  76. return false;
  77. }
  78. if (input_[pos] != literal[i]) {
  79. return false;
  80. }
  81. ++pos;
  82. }
  83. pos_ = pos;
  84. return true;
  85. }
  86. std::optional<common_chat_msg_parser::find_regex_result> common_chat_msg_parser::try_find_literal(const std::string & literal) {
  87. auto idx = input_.find(literal, pos_);
  88. if (idx != std::string::npos) {
  89. find_regex_result res;
  90. res.prelude = input_.substr(pos_, idx - pos_);
  91. auto end = idx + literal.size();
  92. res.groups.emplace_back(common_string_range{idx, end});
  93. move_to(end);
  94. return res;
  95. }
  96. if (is_partial_) {
  97. idx = string_find_partial_stop(input_, literal);
  98. if (idx != std::string::npos && idx >= pos_) {
  99. find_regex_result res;
  100. res.prelude = input_.substr(pos_, idx - pos_);
  101. auto end = input_.size();
  102. res.groups.emplace_back(common_string_range{idx, end});
  103. move_to(end);
  104. return res;
  105. }
  106. }
  107. return std::nullopt;
  108. }
  109. void common_chat_msg_parser::consume_literal(const std::string & literal) {
  110. if (!try_consume_literal(literal)) {
  111. throw common_chat_msg_partial_exception(literal);
  112. }
  113. }
  114. bool common_chat_msg_parser::try_parse_reasoning(const std::string & start_think, const std::string & end_think) {
  115. auto handle_reasoning = [&](const std::string & reasoning, bool closed) {
  116. auto stripped_reasoning = string_strip(reasoning);
  117. if (stripped_reasoning.empty()) {
  118. return;
  119. }
  120. if (syntax_.reasoning_in_content) {
  121. add_content(syntax_.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK ? "<think>" : start_think);
  122. add_content(stripped_reasoning);
  123. if (closed) {
  124. add_content(syntax_.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK ? "</think>" : end_think);
  125. }
  126. } else {
  127. add_reasoning_content(stripped_reasoning);
  128. }
  129. };
  130. if (syntax_.reasoning_format != COMMON_REASONING_FORMAT_NONE) {
  131. if (syntax_.thinking_forced_open || try_consume_literal(start_think)) {
  132. if (auto res = try_find_literal(end_think)) {
  133. handle_reasoning(res->prelude, /* closed */ true);
  134. consume_spaces();
  135. return true;
  136. }
  137. auto rest = consume_rest();
  138. if (!rest.empty()) {
  139. handle_reasoning(rest, /* closed */ !is_partial());
  140. }
  141. if (!syntax_.thinking_forced_open) {
  142. throw common_chat_msg_partial_exception(end_think);
  143. }
  144. return true;
  145. }
  146. }
  147. return false;
  148. }
  149. std::string common_chat_msg_parser::consume_rest() {
  150. auto rest = input_.substr(pos_);
  151. pos_ = input_.size();
  152. return rest;
  153. }
  154. // Tries to find the regex, consumes it (pos right after it) and gives the prelude (right before it) and the groups to the callback.
  155. 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) {
  156. auto m = regex.search(input_, from == std::string::npos ? pos_ : from);
  157. if (m.type == COMMON_REGEX_MATCH_TYPE_NONE) {
  158. return std::nullopt;
  159. }
  160. auto prelude = input_.substr(pos_, m.groups[0].begin - pos_);
  161. pos_ = m.groups[0].end;
  162. if (add_prelude_to_content) {
  163. add_content(prelude);
  164. }
  165. if (m.type == COMMON_REGEX_MATCH_TYPE_PARTIAL) {
  166. if (is_partial()) {
  167. throw common_chat_msg_partial_exception(regex.str());
  168. }
  169. return std::nullopt;
  170. }
  171. return find_regex_result{prelude, m.groups};
  172. }
  173. common_chat_msg_parser::find_regex_result common_chat_msg_parser::consume_regex(const common_regex & regex) {
  174. if (auto result = try_consume_regex(regex)) {
  175. return *result;
  176. }
  177. throw common_chat_msg_partial_exception(regex.str());
  178. }
  179. std::optional<common_chat_msg_parser::find_regex_result> common_chat_msg_parser::try_consume_regex(const common_regex & regex) {
  180. auto m = regex.search(input_, pos_);
  181. if (m.type == COMMON_REGEX_MATCH_TYPE_NONE) {
  182. return std::nullopt;
  183. }
  184. if (m.type == COMMON_REGEX_MATCH_TYPE_PARTIAL) {
  185. if (is_partial()) {
  186. throw common_chat_msg_partial_exception(regex.str());
  187. }
  188. return std::nullopt;
  189. }
  190. if (m.groups[0].begin != pos_) {
  191. // Didn't match at the current position.
  192. return std::nullopt;
  193. }
  194. pos_ = m.groups[0].end;
  195. return find_regex_result {
  196. /* .prelude = */ "",
  197. m.groups,
  198. };
  199. }
  200. std::optional<common_json> common_chat_msg_parser::try_consume_json() {
  201. auto it = input_.cbegin() + pos_;
  202. const auto end = input_.cend();
  203. common_json result;
  204. if (!common_json_parse(it, end, healing_marker_, result)) {
  205. return std::nullopt;
  206. }
  207. pos_ = std::distance(input_.cbegin(), it);
  208. if (result.healing_marker.marker.empty()) {
  209. // No healing marker, just return the parsed json
  210. return result;
  211. }
  212. if (!is_partial()) {
  213. throw common_chat_msg_partial_exception("JSON");
  214. }
  215. return result;
  216. }
  217. common_json common_chat_msg_parser::consume_json() {
  218. if (auto result = try_consume_json()) {
  219. return *result;
  220. }
  221. throw common_chat_msg_partial_exception("JSON");
  222. }
  223. common_chat_msg_parser::consume_json_result common_chat_msg_parser::consume_json_with_dumped_args(
  224. const std::vector<std::vector<std::string>> & args_paths,
  225. const std::vector<std::vector<std::string>> & content_paths
  226. ) {
  227. if (auto result = try_consume_json_with_dumped_args(args_paths, content_paths)) {
  228. return *result;
  229. }
  230. throw common_chat_msg_partial_exception("JSON");
  231. }
  232. std::optional<common_chat_msg_parser::consume_json_result> common_chat_msg_parser::try_consume_json_with_dumped_args(
  233. const std::vector<std::vector<std::string>> & args_paths,
  234. const std::vector<std::vector<std::string>> & content_paths
  235. ) {
  236. auto partial = try_consume_json();
  237. if (!partial) {
  238. return std::nullopt;
  239. }
  240. auto is_arguments_path = [&](const std::vector<std::string> & path) {
  241. return std::find(args_paths.begin(), args_paths.end(), path) != args_paths.end();
  242. };
  243. auto is_content_path = [&](const std::vector<std::string> & path) {
  244. return std::find(content_paths.begin(), content_paths.end(), path) != content_paths.end();
  245. };
  246. if (partial->healing_marker.marker.empty()) {
  247. if (args_paths.empty()) {
  248. // No arguments to dump, and JSON was parsed fully.
  249. return consume_json_result {
  250. partial->json,
  251. /* .is_partial = */ false,
  252. };
  253. }
  254. if (is_arguments_path({})) {
  255. // Entire JSON is the arguments and was parsed fully.
  256. return consume_json_result {
  257. partial->json.dump(),
  258. /* .is_partial = */ false,
  259. };
  260. }
  261. }
  262. LOG_DBG("Parsed partial JSON: %s (json_healing_marker: %s)\n", partial->json.dump().c_str(), partial->healing_marker.json_dump_marker.c_str());
  263. auto found_healing_marker = false;
  264. std::vector<std::string> path;
  265. std::function<json(const json &)> remove_unsupported_healings_and_dump_args = [&](const json & j) -> json {
  266. if (is_arguments_path(path)) {
  267. auto arguments = j.dump();
  268. if (is_partial() && !partial->healing_marker.marker.empty()) {
  269. auto idx = arguments.find(partial->healing_marker.json_dump_marker);
  270. if (idx != std::string::npos) {
  271. arguments.resize(idx);
  272. found_healing_marker = true;
  273. }
  274. if (arguments == "\"") {
  275. // This happens because of completing `:"$magic` after `"arguments"`
  276. arguments = "";
  277. }
  278. }
  279. return arguments;
  280. }
  281. if (is_content_path(path)) {
  282. if (!j.is_string()) {
  283. throw std::runtime_error("Content path must be a string");
  284. }
  285. std::string str = j;
  286. auto idx = str.find(partial->healing_marker.marker); // not using json_dump_marker as we're inside a string
  287. if (idx != std::string::npos) {
  288. str.resize(idx);
  289. found_healing_marker = true;
  290. }
  291. return str;
  292. }
  293. if (j.is_object()) {
  294. auto obj = json::object();
  295. for (const auto & p : j.items()) {
  296. const auto & key = p.key();
  297. const auto & value = p.value();
  298. const std::string key_str = key; // NOLINT
  299. auto idx = key_str.find(healing_marker_);
  300. if (idx != std::string::npos) {
  301. found_healing_marker = true;
  302. break;
  303. }
  304. path.push_back(key_str);
  305. if (value.is_string()) {
  306. const std::string value_str = value;
  307. if (value_str.find(healing_marker_) != std::string::npos) {
  308. found_healing_marker = true;
  309. if (is_content_path(path)) {
  310. if (partial->healing_marker.marker == partial->healing_marker.json_dump_marker) {
  311. // The healing occurred inside the string: good. Otherwise we just ditch the entire key/value pair.
  312. obj[key] = remove_unsupported_healings_and_dump_args(value);
  313. }
  314. }
  315. break;
  316. }
  317. obj[key] = value;
  318. } else {
  319. obj[key] = remove_unsupported_healings_and_dump_args(value);
  320. }
  321. path.pop_back();
  322. }
  323. return obj;
  324. }
  325. if (j.is_array()) {
  326. auto arr = json::array();
  327. for (const auto & value : j) {
  328. if (value.is_string()) {
  329. std::string str = value;
  330. auto idx = str.find(healing_marker_);
  331. if (idx != std::string::npos) {
  332. // Don't heal array values that aren't in the arguments.
  333. found_healing_marker = true;
  334. break;
  335. }
  336. }
  337. arr.push_back(remove_unsupported_healings_and_dump_args(value));
  338. }
  339. return arr;
  340. }
  341. return j;
  342. };
  343. auto cleaned = remove_unsupported_healings_and_dump_args(partial->json);
  344. 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());
  345. return consume_json_result {
  346. cleaned,
  347. /* .is_partial = */ found_healing_marker,
  348. };
  349. }