utils.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. #pragma once
  2. #include "llama.h"
  3. #include "common.h"
  4. #include "json.hpp"
  5. #include <string>
  6. #include <vector>
  7. #include <sstream>
  8. #include <random>
  9. #define DEFAULT_OAICOMPAT_MODEL "gpt-3.5-turbo-0613"
  10. using json = nlohmann::ordered_json;
  11. // https://community.openai.com/t/openai-chat-list-of-error-codes-and-types/357791/11
  12. enum error_type {
  13. ERROR_TYPE_INVALID_REQUEST,
  14. ERROR_TYPE_AUTHENTICATION,
  15. ERROR_TYPE_SERVER,
  16. ERROR_TYPE_NOT_FOUND,
  17. ERROR_TYPE_PERMISSION,
  18. ERROR_TYPE_UNAVAILABLE, // custom error
  19. ERROR_TYPE_NOT_SUPPORTED, // custom error
  20. };
  21. extern bool server_verbose;
  22. extern bool server_log_json;
  23. #ifndef SERVER_VERBOSE
  24. #define SERVER_VERBOSE 1
  25. #endif
  26. #if SERVER_VERBOSE != 1
  27. #define LOG_VERBOSE(MSG, ...)
  28. #else
  29. #define LOG_VERBOSE(MSG, ...) \
  30. do \
  31. { \
  32. if (server_verbose) \
  33. { \
  34. server_log("VERB", __func__, __LINE__, MSG, __VA_ARGS__); \
  35. } \
  36. } while (0)
  37. #endif
  38. #define LOG_ERROR( MSG, ...) server_log("ERR", __func__, __LINE__, MSG, __VA_ARGS__)
  39. #define LOG_WARNING(MSG, ...) server_log("WARN", __func__, __LINE__, MSG, __VA_ARGS__)
  40. #define LOG_INFO( MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
  41. static inline void server_log(const char * level, const char * function, int line, const char * message, const json & extra);
  42. template <typename T>
  43. static T json_value(const json & body, const std::string & key, const T & default_value) {
  44. // Fallback null to default value
  45. if (body.contains(key) && !body.at(key).is_null()) {
  46. try {
  47. return body.at(key);
  48. } catch (NLOHMANN_JSON_NAMESPACE::detail::type_error const &) {
  49. std::stringstream ss;
  50. ss << "Wrong type supplied for parameter '" << key << "'. Expected '" << json(default_value).type_name() << "', using default value.";
  51. LOG_WARNING(ss.str().c_str(), body);
  52. return default_value;
  53. }
  54. } else {
  55. return default_value;
  56. }
  57. }
  58. static inline void server_log(const char * level, const char * function, int line, const char * message, const json & extra) {
  59. std::stringstream ss_tid;
  60. ss_tid << std::this_thread::get_id();
  61. json log = json{
  62. {"tid", ss_tid.str()},
  63. {"timestamp", time(nullptr)},
  64. };
  65. if (server_log_json) {
  66. log.merge_patch({
  67. {"level", level},
  68. {"function", function},
  69. {"line", line},
  70. {"msg", message},
  71. });
  72. if (!extra.empty()) {
  73. log.merge_patch(extra);
  74. }
  75. printf("%s\n", log.dump(-1, ' ', false, json::error_handler_t::replace).c_str());
  76. } else {
  77. char buf[1024];
  78. snprintf(buf, 1024, "%4s [%24s] %s", level, function, message);
  79. if (!extra.empty()) {
  80. log.merge_patch(extra);
  81. }
  82. std::stringstream ss;
  83. ss << buf << " |";
  84. for (const auto & el : log.items())
  85. {
  86. const std::string value = el.value().dump(-1, ' ', false, json::error_handler_t::replace);
  87. ss << " " << el.key() << "=" << value;
  88. }
  89. const std::string str = ss.str();
  90. printf("%.*s\n", (int)str.size(), str.data());
  91. }
  92. fflush(stdout);
  93. }
  94. //
  95. // chat template utils
  96. //
  97. // Check if the template supplied via "--chat-template" is supported or not. Returns true if it's valid
  98. inline bool verify_custom_template(const std::string & tmpl) {
  99. llama_chat_message chat[] = {{"user", "test"}};
  100. int res = llama_chat_apply_template(nullptr, tmpl.c_str(), chat, 1, true, nullptr, 0);
  101. return res >= 0;
  102. }
  103. // Format given chat. If tmpl is empty, we take the template from model metadata
  104. inline std::string format_chat(const struct llama_model * model, const std::string & tmpl, const std::vector<json> & messages) {
  105. size_t alloc_size = 0;
  106. // vector holding all allocated string to be passed to llama_chat_apply_template
  107. std::vector<std::string> str(messages.size() * 2);
  108. std::vector<llama_chat_message> chat(messages.size());
  109. for (size_t i = 0; i < messages.size(); ++i) {
  110. const auto & curr_msg = messages[i];
  111. str[i*2 + 0] = json_value(curr_msg, "role", std::string(""));
  112. str[i*2 + 1] = json_value(curr_msg, "content", std::string(""));
  113. alloc_size += str[i*2 + 1].length();
  114. chat[i].role = str[i*2 + 0].c_str();
  115. chat[i].content = str[i*2 + 1].c_str();
  116. }
  117. const char * ptr_tmpl = tmpl.empty() ? nullptr : tmpl.c_str();
  118. std::vector<char> buf(alloc_size * 2);
  119. // run the first time to get the total output length
  120. int32_t res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), true, buf.data(), buf.size());
  121. // if it turns out that our buffer is too small, we resize it
  122. if ((size_t) res > buf.size()) {
  123. buf.resize(res);
  124. res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), true, buf.data(), buf.size());
  125. }
  126. const std::string formatted_chat(buf.data(), res);
  127. LOG_VERBOSE("formatted_chat", {{"text", formatted_chat.c_str()}});
  128. return formatted_chat;
  129. }
  130. //
  131. // base64 utils (TODO: move to common in the future)
  132. //
  133. static const std::string base64_chars =
  134. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  135. "abcdefghijklmnopqrstuvwxyz"
  136. "0123456789+/";
  137. static inline bool is_base64(uint8_t c) {
  138. return (isalnum(c) || (c == '+') || (c == '/'));
  139. }
  140. static inline std::vector<uint8_t> base64_decode(const std::string & encoded_string) {
  141. int i = 0;
  142. int j = 0;
  143. int in_ = 0;
  144. int in_len = encoded_string.size();
  145. uint8_t char_array_4[4];
  146. uint8_t char_array_3[3];
  147. std::vector<uint8_t> ret;
  148. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  149. char_array_4[i++] = encoded_string[in_]; in_++;
  150. if (i == 4) {
  151. for (i = 0; i < 4; i++) {
  152. char_array_4[i] = base64_chars.find(char_array_4[i]);
  153. }
  154. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  155. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  156. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  157. for (i = 0; (i < 3); i++) {
  158. ret.push_back(char_array_3[i]);
  159. }
  160. i = 0;
  161. }
  162. }
  163. if (i) {
  164. for (j = i; j < 4; j++) {
  165. char_array_4[j] = 0;
  166. }
  167. for (j = 0; j < 4; j++) {
  168. char_array_4[j] = base64_chars.find(char_array_4[j]);
  169. }
  170. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  171. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  172. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  173. for (j = 0; j < i - 1; j++) {
  174. ret.push_back(char_array_3[j]);
  175. }
  176. }
  177. return ret;
  178. }
  179. //
  180. // random string / id
  181. //
  182. static std::string random_string() {
  183. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  184. std::random_device rd;
  185. std::mt19937 generator(rd());
  186. std::string result(32, ' ');
  187. for (int i = 0; i < 32; ++i) {
  188. result[i] = str[generator() % str.size()];
  189. }
  190. return result;
  191. }
  192. static std::string gen_chatcmplid() {
  193. std::stringstream chatcmplid;
  194. chatcmplid << "chatcmpl-" << random_string();
  195. return chatcmplid.str();
  196. }
  197. //
  198. // other common utils
  199. //
  200. static size_t common_part(const std::vector<llama_token> & a, const std::vector<llama_token> & b) {
  201. size_t i;
  202. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  203. return i;
  204. }
  205. static bool ends_with(const std::string & str, const std::string & suffix) {
  206. return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  207. }
  208. static size_t find_partial_stop_string(const std::string &stop, const std::string &text) {
  209. if (!text.empty() && !stop.empty()) {
  210. const char text_last_char = text.back();
  211. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
  212. if (stop[char_index] == text_last_char) {
  213. const std::string current_partial = stop.substr(0, char_index + 1);
  214. if (ends_with(text, current_partial)) {
  215. return text.size() - char_index - 1;
  216. }
  217. }
  218. }
  219. }
  220. return std::string::npos;
  221. }
  222. // TODO: reuse llama_detokenize
  223. template <class Iter>
  224. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  225. std::string ret;
  226. for (; begin != end; ++begin) {
  227. ret += llama_token_to_piece(ctx, *begin);
  228. }
  229. return ret;
  230. }
  231. // format incomplete utf-8 multibyte character for output
  232. static std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  233. std::string out = token == -1 ? "" : llama_token_to_piece(ctx, token);
  234. // if the size is 1 and first bit is 1, meaning it's a partial character
  235. // (size > 1 meaning it's already a known token)
  236. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  237. std::stringstream ss;
  238. ss << std::hex << (out[0] & 0xff);
  239. std::string res(ss.str());
  240. out = "byte: \\x" + res;
  241. }
  242. return out;
  243. }
  244. struct completion_token_output {
  245. llama_token tok;
  246. std::string text_to_send;
  247. struct token_prob {
  248. llama_token tok;
  249. float prob;
  250. };
  251. std::vector<token_prob> probs;
  252. };
  253. // convert a vector of completion_token_output to json
  254. static json probs_vector_to_json(const llama_context * ctx, const std::vector<completion_token_output> & probs) {
  255. json out = json::array();
  256. for (const auto & prob : probs) {
  257. json probs_for_token = json::array();
  258. for (const auto & p : prob.probs) {
  259. const std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  260. probs_for_token.push_back(json {
  261. {"tok_str", tok_str},
  262. {"prob", p.prob},
  263. });
  264. }
  265. const std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  266. out.push_back(json {
  267. {"content", tok_str},
  268. {"probs", probs_for_token},
  269. });
  270. }
  271. return out;
  272. }
  273. //
  274. // OAI utils
  275. //
  276. static json oaicompat_completion_params_parse(
  277. const struct llama_model * model,
  278. const json & body, /* openai api json semantics */
  279. const std::string & chat_template) {
  280. json llama_params;
  281. llama_params["__oaicompat"] = true;
  282. // Map OpenAI parameters to llama.cpp parameters
  283. //
  284. // For parameters that are defined by the OpenAI documentation (e.g.
  285. // temperature), we explicitly specify OpenAI's intended default; we
  286. // need to do that because sometimes OpenAI disagrees with llama.cpp
  287. //
  288. // https://platform.openai.com/docs/api-reference/chat/create
  289. llama_sampling_params default_sparams;
  290. llama_params["model"] = json_value(body, "model", std::string("unknown"));
  291. llama_params["frequency_penalty"] = json_value(body, "frequency_penalty", 0.0);
  292. llama_params["logit_bias"] = json_value(body, "logit_bias", json::object());
  293. llama_params["n_predict"] = json_value(body, "max_tokens", -1);
  294. llama_params["presence_penalty"] = json_value(body, "presence_penalty", 0.0);
  295. llama_params["seed"] = json_value(body, "seed", LLAMA_DEFAULT_SEED);
  296. llama_params["stream"] = json_value(body, "stream", false);
  297. llama_params["temperature"] = json_value(body, "temperature", 0.0);
  298. llama_params["top_p"] = json_value(body, "top_p", 1.0);
  299. // Apply chat template to the list of messages
  300. llama_params["prompt"] = format_chat(model, chat_template, body["messages"]);
  301. // Handle "stop" field
  302. if (body.contains("stop") && body["stop"].is_string()) {
  303. llama_params["stop"] = json::array({body["stop"].get<std::string>()});
  304. } else {
  305. llama_params["stop"] = json_value(body, "stop", json::array());
  306. }
  307. // Handle "response_format" field
  308. if (body.contains("response_format")) {
  309. json response_format = json_value(body, "response_format", json::object());
  310. std::string response_type = json_value(response_format, "type", std::string());
  311. if (response_type == "json_object") {
  312. llama_params["json_schema"] = json_value(response_format, "schema", json::object());
  313. } else if (!response_type.empty() && response_type != "text") {
  314. throw std::runtime_error("response_format type must be one of \"text\" or \"json_object\", but got: " + response_type);
  315. }
  316. }
  317. // Handle "n" field
  318. int n_choices = json_value(body, "n", 1);
  319. if (n_choices != 1) {
  320. throw std::runtime_error("Only one completion choice is allowed");
  321. }
  322. // Handle "logprobs" field
  323. // TODO: The response format of this option is not yet OAI-compatible, but seems like no one really using it; We may need to fix it in the future
  324. if (body.contains("logprobs")) {
  325. llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
  326. } else if (body.contains("top_logprobs")) {
  327. throw std::runtime_error("top_logprobs requires logprobs to be set to true");
  328. }
  329. // Params supported by OAI but unsupported by llama.cpp
  330. static const std::vector<std::string> unsupported_params { "tools", "tool_choice" };
  331. for (auto & param : unsupported_params) {
  332. if (body.contains(param)) {
  333. throw std::runtime_error("Unsupported param: " + param);
  334. }
  335. }
  336. // Copy remaining properties to llama_params
  337. // This allows user to use llama.cpp-specific params like "mirostat", "tfs_z",... via OAI endpoint.
  338. // See "launch_slot_with_task()" for a complete list of params supported by llama.cpp
  339. for (const auto & item : body.items()) {
  340. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  341. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  342. llama_params[item.key()] = item.value();
  343. }
  344. }
  345. return llama_params;
  346. }
  347. static json format_final_response_oaicompat(const json & request, json result, const std::string & completion_id, bool streaming = false) {
  348. bool stopped_word = result.count("stopped_word") != 0;
  349. bool stopped_eos = json_value(result, "stopped_eos", false);
  350. int num_tokens_predicted = json_value(result, "tokens_predicted", 0);
  351. int num_prompt_tokens = json_value(result, "tokens_evaluated", 0);
  352. std::string content = json_value(result, "content", std::string(""));
  353. std::string finish_reason = "length";
  354. if (stopped_word || stopped_eos) {
  355. finish_reason = "stop";
  356. }
  357. json choices =
  358. streaming ? json::array({json{{"finish_reason", finish_reason},
  359. {"index", 0},
  360. {"delta", json::object()}}})
  361. : json::array({json{{"finish_reason", finish_reason},
  362. {"index", 0},
  363. {"message", json{{"content", content},
  364. {"role", "assistant"}}}}});
  365. std::time_t t = std::time(0);
  366. json res = json {
  367. {"choices", choices},
  368. {"created", t},
  369. {"model",
  370. json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  371. {"object", streaming ? "chat.completion.chunk" : "chat.completion"},
  372. {"usage", json {
  373. {"completion_tokens", num_tokens_predicted},
  374. {"prompt_tokens", num_prompt_tokens},
  375. {"total_tokens", num_tokens_predicted + num_prompt_tokens}
  376. }},
  377. {"id", completion_id}
  378. };
  379. if (server_verbose) {
  380. res["__verbose"] = result;
  381. }
  382. if (result.contains("completion_probabilities")) {
  383. res["completion_probabilities"] = json_value(result, "completion_probabilities", json::array());
  384. }
  385. return res;
  386. }
  387. // return value is vector as there is one case where we might need to generate two responses
  388. static std::vector<json> format_partial_response_oaicompat(json result, const std::string & completion_id) {
  389. if (!result.contains("model") || !result.contains("oaicompat_token_ctr")) {
  390. return std::vector<json>({result});
  391. }
  392. bool first = json_value(result, "oaicompat_token_ctr", 0) == 0;
  393. std::string modelname = json_value(result, "model", std::string(DEFAULT_OAICOMPAT_MODEL));
  394. bool stopped_word = json_value(result, "stopped_word", false);
  395. bool stopped_eos = json_value(result, "stopped_eos", false);
  396. bool stopped_limit = json_value(result, "stopped_limit", false);
  397. std::string content = json_value(result, "content", std::string(""));
  398. std::string finish_reason;
  399. if (stopped_word || stopped_eos) {
  400. finish_reason = "stop";
  401. }
  402. if (stopped_limit) {
  403. finish_reason = "length";
  404. }
  405. std::time_t t = std::time(0);
  406. json choices;
  407. if (!finish_reason.empty()) {
  408. choices = json::array({json{{"finish_reason", finish_reason},
  409. {"index", 0},
  410. {"delta", json::object()}}});
  411. } else {
  412. if (first) {
  413. if (content.empty()) {
  414. choices = json::array({json{{"finish_reason", nullptr},
  415. {"index", 0},
  416. {"delta", json{{"role", "assistant"}}}}});
  417. } else {
  418. // We have to send this as two updates to conform to openai behavior
  419. json initial_ret = json{{"choices", json::array({json{
  420. {"finish_reason", nullptr},
  421. {"index", 0},
  422. {"delta", json{
  423. {"role", "assistant"}
  424. }}}})},
  425. {"created", t},
  426. {"id", completion_id},
  427. {"model", modelname},
  428. {"object", "chat.completion.chunk"}};
  429. json second_ret = json{
  430. {"choices", json::array({json{{"finish_reason", nullptr},
  431. {"index", 0},
  432. {"delta", json{
  433. {"content", content}}}
  434. }})},
  435. {"created", t},
  436. {"id", completion_id},
  437. {"model", modelname},
  438. {"object", "chat.completion.chunk"}};
  439. return std::vector<json>({initial_ret, second_ret});
  440. }
  441. } else {
  442. // Some idiosyncrasy in task processing logic makes several trailing calls
  443. // with empty content, we ignore these at the calee site.
  444. if (content.empty()) {
  445. return std::vector<json>({json::object()});
  446. }
  447. choices = json::array({json{
  448. {"finish_reason", nullptr},
  449. {"index", 0},
  450. {"delta",
  451. json{
  452. {"content", content},
  453. }},
  454. }});
  455. }
  456. }
  457. json ret = json {
  458. {"choices", choices},
  459. {"created", t},
  460. {"id", completion_id},
  461. {"model", modelname},
  462. {"object", "chat.completion.chunk"}
  463. };
  464. if (!finish_reason.empty()) {
  465. int num_tokens_predicted = json_value(result, "tokens_predicted", 0);
  466. int num_prompt_tokens = json_value(result, "tokens_evaluated", 0);
  467. ret.push_back({"usage", json {
  468. {"completion_tokens", num_tokens_predicted},
  469. {"prompt_tokens", num_prompt_tokens},
  470. {"total_tokens", num_tokens_predicted + num_prompt_tokens}
  471. }});
  472. }
  473. return std::vector<json>({ret});
  474. }
  475. static json format_embeddings_response_oaicompat(const json & request, const json & embeddings) {
  476. json data = json::array();
  477. int i = 0;
  478. for (auto & elem : embeddings) {
  479. data.push_back(json{
  480. {"embedding", json_value(elem, "embedding", json::array())},
  481. {"index", i++},
  482. {"object", "embedding"}
  483. });
  484. }
  485. json res = json {
  486. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  487. {"object", "list"},
  488. {"usage", json {
  489. {"prompt_tokens", 0},
  490. {"total_tokens", 0}
  491. }},
  492. {"data", data}
  493. };
  494. return res;
  495. }
  496. static json format_tokenizer_response(const std::vector<llama_token> & tokens) {
  497. return json {
  498. {"tokens", tokens}
  499. };
  500. }
  501. static json format_detokenized_response(const std::string & content) {
  502. return json {
  503. {"content", content}
  504. };
  505. }
  506. static json format_error_response(const std::string & message, const enum error_type type) {
  507. std::string type_str;
  508. int code = 500;
  509. switch (type) {
  510. case ERROR_TYPE_INVALID_REQUEST:
  511. type_str = "invalid_request_error";
  512. code = 400;
  513. break;
  514. case ERROR_TYPE_AUTHENTICATION:
  515. type_str = "authentication_error";
  516. code = 401;
  517. break;
  518. case ERROR_TYPE_NOT_FOUND:
  519. type_str = "not_found_error";
  520. code = 404;
  521. break;
  522. case ERROR_TYPE_SERVER:
  523. type_str = "server_error";
  524. code = 500;
  525. break;
  526. case ERROR_TYPE_PERMISSION:
  527. type_str = "permission_error";
  528. code = 403;
  529. break;
  530. case ERROR_TYPE_NOT_SUPPORTED:
  531. type_str = "not_supported_error";
  532. code = 501;
  533. break;
  534. case ERROR_TYPE_UNAVAILABLE:
  535. type_str = "unavailable_error";
  536. code = 503;
  537. break;
  538. }
  539. return json {
  540. {"code", code},
  541. {"message", message},
  542. {"type", type_str},
  543. };
  544. }