chat-parser.cpp 15 KB

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