utils.hpp 22 KB

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