chat-parser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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) {
  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. if (m.type == COMMON_REGEX_MATCH_TYPE_PARTIAL) {
  161. if (is_partial()) {
  162. throw common_chat_msg_partial_exception(regex.str());
  163. }
  164. return std::nullopt;
  165. }
  166. auto prelude = input_.substr(pos_, m.groups[0].begin - pos_);
  167. pos_ = m.groups[0].end;
  168. return find_regex_result{prelude, m.groups};
  169. }
  170. common_chat_msg_parser::find_regex_result common_chat_msg_parser::consume_regex(const common_regex & regex) {
  171. if (auto result = try_consume_regex(regex)) {
  172. return *result;
  173. }
  174. throw common_chat_msg_partial_exception(regex.str());
  175. }
  176. std::optional<common_chat_msg_parser::find_regex_result> common_chat_msg_parser::try_consume_regex(const common_regex & regex) {
  177. auto m = regex.search(input_, pos_);
  178. if (m.type == COMMON_REGEX_MATCH_TYPE_NONE) {
  179. return std::nullopt;
  180. }
  181. if (m.type == COMMON_REGEX_MATCH_TYPE_PARTIAL) {
  182. if (is_partial()) {
  183. throw common_chat_msg_partial_exception(regex.str());
  184. }
  185. return std::nullopt;
  186. }
  187. if (m.groups[0].begin != pos_) {
  188. // Didn't match at the current position.
  189. return std::nullopt;
  190. }
  191. pos_ = m.groups[0].end;
  192. return find_regex_result {
  193. /* .prelude = */ "",
  194. m.groups,
  195. };
  196. }
  197. std::optional<common_json> common_chat_msg_parser::try_consume_json() {
  198. auto it = input_.cbegin() + pos_;
  199. const auto end = input_.cend();
  200. common_json result;
  201. if (!common_json_parse(it, end, healing_marker_, result)) {
  202. return std::nullopt;
  203. }
  204. pos_ = std::distance(input_.cbegin(), it);
  205. if (result.healing_marker.marker.empty()) {
  206. // No healing marker, just return the parsed json
  207. return result;
  208. }
  209. if (!is_partial()) {
  210. throw common_chat_msg_partial_exception("JSON");
  211. }
  212. return result;
  213. }
  214. common_json common_chat_msg_parser::consume_json() {
  215. if (auto result = try_consume_json()) {
  216. return *result;
  217. }
  218. throw common_chat_msg_partial_exception("JSON");
  219. }
  220. common_chat_msg_parser::consume_json_result common_chat_msg_parser::consume_json_with_dumped_args(
  221. const std::vector<std::vector<std::string>> & args_paths,
  222. const std::vector<std::vector<std::string>> & content_paths
  223. ) {
  224. if (auto result = try_consume_json_with_dumped_args(args_paths, content_paths)) {
  225. return *result;
  226. }
  227. throw common_chat_msg_partial_exception("JSON");
  228. }
  229. std::optional<common_chat_msg_parser::consume_json_result> common_chat_msg_parser::try_consume_json_with_dumped_args(
  230. const std::vector<std::vector<std::string>> & args_paths,
  231. const std::vector<std::vector<std::string>> & content_paths
  232. ) {
  233. auto partial = try_consume_json();
  234. if (!partial) {
  235. return std::nullopt;
  236. }
  237. auto is_arguments_path = [&](const std::vector<std::string> & path) {
  238. return std::find(args_paths.begin(), args_paths.end(), path) != args_paths.end();
  239. };
  240. auto is_content_path = [&](const std::vector<std::string> & path) {
  241. return std::find(content_paths.begin(), content_paths.end(), path) != content_paths.end();
  242. };
  243. if (partial->healing_marker.marker.empty()) {
  244. if (args_paths.empty()) {
  245. // No arguments to dump, and JSON was parsed fully.
  246. return consume_json_result {
  247. partial->json,
  248. /* .is_partial = */ false,
  249. };
  250. }
  251. if (is_arguments_path({})) {
  252. // Entire JSON is the arguments and was parsed fully.
  253. return consume_json_result {
  254. partial->json.dump(),
  255. /* .is_partial = */ false,
  256. };
  257. }
  258. }
  259. LOG_DBG("Parsed partial JSON: %s (json_healing_marker: %s)\n", partial->json.dump().c_str(), partial->healing_marker.json_dump_marker.c_str());
  260. auto found_healing_marker = false;
  261. std::vector<std::string> path;
  262. std::function<json(const json &)> remove_unsupported_healings_and_dump_args = [&](const json & j) -> json {
  263. if (is_arguments_path(path)) {
  264. auto arguments = j.dump();
  265. if (is_partial() && !partial->healing_marker.marker.empty()) {
  266. auto idx = arguments.find(partial->healing_marker.json_dump_marker);
  267. if (idx != std::string::npos) {
  268. arguments.resize(idx);
  269. found_healing_marker = true;
  270. }
  271. if (arguments == "\"") {
  272. // This happens because of completing `:"$magic` after `"arguments"`
  273. arguments = "";
  274. }
  275. }
  276. return arguments;
  277. }
  278. if (is_content_path(path)) {
  279. if (!j.is_string()) {
  280. throw std::runtime_error("Content path must be a string");
  281. }
  282. std::string str = j;
  283. auto idx = str.find(partial->healing_marker.marker); // not using json_dump_marker as we're inside a string
  284. if (idx != std::string::npos) {
  285. str.resize(idx);
  286. found_healing_marker = true;
  287. }
  288. return str;
  289. }
  290. if (j.is_object()) {
  291. auto obj = json::object();
  292. for (const auto & p : j.items()) {
  293. const auto & key = p.key();
  294. const auto & value = p.value();
  295. const std::string key_str = key; // NOLINT
  296. auto idx = key_str.find(healing_marker_);
  297. if (idx != std::string::npos) {
  298. found_healing_marker = true;
  299. break;
  300. }
  301. path.push_back(key_str);
  302. if (value.is_string()) {
  303. const std::string value_str = value;
  304. if (value_str.find(healing_marker_) != std::string::npos) {
  305. found_healing_marker = true;
  306. if (is_content_path(path)) {
  307. if (partial->healing_marker.marker == partial->healing_marker.json_dump_marker) {
  308. // The healing occurred inside the string: good. Otherwise we just ditch the entire key/value pair.
  309. obj[key] = remove_unsupported_healings_and_dump_args(value);
  310. }
  311. }
  312. break;
  313. }
  314. obj[key] = value;
  315. } else {
  316. obj[key] = remove_unsupported_healings_and_dump_args(value);
  317. }
  318. path.pop_back();
  319. }
  320. return obj;
  321. }
  322. if (j.is_array()) {
  323. auto arr = json::array();
  324. for (const auto & value : j) {
  325. if (value.is_string()) {
  326. std::string str = value;
  327. auto idx = str.find(healing_marker_);
  328. if (idx != std::string::npos) {
  329. // Don't heal array values that aren't in the arguments.
  330. found_healing_marker = true;
  331. break;
  332. }
  333. }
  334. arr.push_back(remove_unsupported_healings_and_dump_args(value));
  335. }
  336. return arr;
  337. }
  338. return j;
  339. };
  340. auto cleaned = remove_unsupported_healings_and_dump_args(partial->json);
  341. 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());
  342. return consume_json_result {
  343. cleaned,
  344. /* .is_partial = */ found_healing_marker,
  345. };
  346. }