1
0

chat-parser.cpp 14 KB

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