1
0

chat-parser.cpp 14 KB

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