utils.hpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. #pragma once
  2. #include "common.h"
  3. #include "log.h"
  4. #include "llama.h"
  5. #ifndef NDEBUG
  6. // crash the server in debug mode, otherwise send an http 500 error
  7. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  8. #endif
  9. // increase max payload length to allow use of larger context size
  10. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 1048576
  11. #include "httplib.h"
  12. // Change JSON_ASSERT from assert() to GGML_ASSERT:
  13. #define JSON_ASSERT GGML_ASSERT
  14. #include "json.hpp"
  15. #include <random>
  16. #include <sstream>
  17. #include <string>
  18. #include <vector>
  19. #define DEFAULT_OAICOMPAT_MODEL "gpt-3.5-turbo-0613"
  20. using json = nlohmann::ordered_json;
  21. using llama_tokens = std::vector<llama_token>;
  22. #define SLT_INF(slot, fmt, ...) LOG_INF("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  23. #define SLT_WRN(slot, fmt, ...) LOG_WRN("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  24. #define SLT_ERR(slot, fmt, ...) LOG_ERR("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  25. #define SLT_DBG(slot, fmt, ...) LOG_DBG("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  26. #define SRV_INF(fmt, ...) LOG_INF("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  27. #define SRV_WRN(fmt, ...) LOG_WRN("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  28. #define SRV_ERR(fmt, ...) LOG_ERR("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  29. #define SRV_DBG(fmt, ...) LOG_DBG("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  30. #define QUE_INF(fmt, ...) LOG_INF("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  31. #define QUE_WRN(fmt, ...) LOG_WRN("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  32. #define QUE_ERR(fmt, ...) LOG_ERR("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  33. #define QUE_DBG(fmt, ...) LOG_DBG("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  34. // https://community.openai.com/t/openai-chat-list-of-error-codes-and-types/357791/11
  35. enum error_type {
  36. ERROR_TYPE_INVALID_REQUEST,
  37. ERROR_TYPE_AUTHENTICATION,
  38. ERROR_TYPE_SERVER,
  39. ERROR_TYPE_NOT_FOUND,
  40. ERROR_TYPE_PERMISSION,
  41. ERROR_TYPE_UNAVAILABLE, // custom error
  42. ERROR_TYPE_NOT_SUPPORTED, // custom error
  43. };
  44. template <typename T>
  45. static T json_value(const json & body, const std::string & key, const T & default_value) {
  46. // Fallback null to default value
  47. if (body.contains(key) && !body.at(key).is_null()) {
  48. try {
  49. return body.at(key);
  50. } catch (NLOHMANN_JSON_NAMESPACE::detail::type_error const &) {
  51. LOG_WRN("Wrong type supplied for parameter '%s'. Expected '%s', using default value\n", key.c_str(), json(default_value).type_name());
  52. return default_value;
  53. }
  54. } else {
  55. return default_value;
  56. }
  57. }
  58. //
  59. // tokenizer and input processing utils
  60. //
  61. static bool json_is_array_of_numbers(const json & data) {
  62. if (data.is_array()) {
  63. for (const auto & e : data) {
  64. if (!e.is_number_integer()) {
  65. return false;
  66. }
  67. }
  68. return true;
  69. }
  70. return false;
  71. }
  72. // is array having BOTH numbers & strings?
  73. static bool json_is_array_of_mixed_numbers_strings(const json & data) {
  74. bool seen_string = false;
  75. bool seen_number = false;
  76. if (data.is_array()) {
  77. for (const auto & e : data) {
  78. seen_string |= e.is_string();
  79. seen_number |= e.is_number_integer();
  80. if (seen_number && seen_string) {
  81. return true;
  82. }
  83. }
  84. }
  85. return false;
  86. }
  87. /**
  88. * this handles 2 cases:
  89. * - only string, example: "string"
  90. * - mixed string and tokens, example: [12, 34, "string", 56, 78]
  91. */
  92. static llama_tokens tokenize_mixed(const llama_context * ctx, const json & json_prompt, bool add_special, bool parse_special) {
  93. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  94. // or the first element of the json_prompt array is a string.
  95. llama_tokens prompt_tokens;
  96. if (json_prompt.is_array()) {
  97. bool first = true;
  98. for (const auto & p : json_prompt) {
  99. if (p.is_string()) {
  100. auto s = p.template get<std::string>();
  101. llama_tokens p;
  102. if (first) {
  103. p = common_tokenize(ctx, s, add_special, parse_special);
  104. first = false;
  105. } else {
  106. p = common_tokenize(ctx, s, false, parse_special);
  107. }
  108. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  109. } else {
  110. if (first) {
  111. first = false;
  112. }
  113. prompt_tokens.push_back(p.template get<llama_token>());
  114. }
  115. }
  116. } else {
  117. auto s = json_prompt.template get<std::string>();
  118. prompt_tokens = common_tokenize(ctx, s, add_special, parse_special);
  119. }
  120. return prompt_tokens;
  121. }
  122. /**
  123. * break the input "prompt" object into multiple prompt if needed, then tokenize them
  124. * this supports these cases:
  125. * - "prompt": "string"
  126. * - "prompt": [12, 34, 56]
  127. * - "prompt": [12, 34, "string", 56, 78]
  128. * and multiple prompts (multi-tasks):
  129. * - "prompt": ["string1", "string2"]
  130. * - "prompt": ["string1", [12, 34, 56]]
  131. * - "prompt": [[12, 34, "string", 56, 78], [12, 34, 56]]
  132. */
  133. static std::vector<llama_tokens> tokenize_input_prompts(llama_context * ctx, const json & json_prompt, bool add_special, bool parse_special) {
  134. std::vector<llama_tokens> result;
  135. if (json_prompt.is_string() || json_is_array_of_mixed_numbers_strings(json_prompt)) {
  136. // string or mixed
  137. result.push_back(tokenize_mixed(ctx, json_prompt, add_special, parse_special));
  138. } else if (json_is_array_of_numbers(json_prompt)) {
  139. // array of tokens
  140. result.push_back(json_prompt.get<llama_tokens>());
  141. } else if (json_prompt.is_array()) {
  142. // array of prompts
  143. result.reserve(json_prompt.size());
  144. for (const auto & p : json_prompt) {
  145. if (p.is_string() || json_is_array_of_mixed_numbers_strings(p)) {
  146. result.push_back(tokenize_mixed(ctx, p, add_special, parse_special));
  147. } else if (json_is_array_of_numbers(p)) {
  148. // array of tokens
  149. result.push_back(p.get<llama_tokens>());
  150. } else {
  151. throw std::runtime_error("element of \"prompt\" must be a string, an list of tokens, or a list of mixed strings & tokens");
  152. }
  153. }
  154. } else {
  155. throw std::runtime_error("\"prompt\" must be a string, an list of tokens, a list of mixed strings & tokens, or a list of prompts");
  156. }
  157. return result;
  158. }
  159. //
  160. // template utils
  161. //
  162. // format rerank task: [BOS]query[EOS][SEP]doc[EOS]
  163. static llama_tokens format_rerank(const struct llama_model * model, const llama_tokens & query, const llama_tokens & doc) {
  164. llama_tokens result;
  165. result.reserve(doc.size() + query.size() + 4);
  166. result.push_back(llama_token_bos(model));
  167. result.insert(result.end(), query.begin(), query.end());
  168. result.push_back(llama_token_eos(model));
  169. result.push_back(llama_token_sep(model));
  170. result.insert(result.end(), doc.begin(), doc.end());
  171. result.push_back(llama_token_eos(model));
  172. return result;
  173. }
  174. // format infill task
  175. static llama_tokens format_infill(
  176. const llama_context * ctx,
  177. const json & input_prefix,
  178. const json & input_suffix,
  179. const json & input_extra,
  180. const int n_batch,
  181. const int n_predict,
  182. const int n_ctx,
  183. const bool spm_infill,
  184. const llama_tokens & tokens_prompt
  185. ) {
  186. // TODO: optimize this block by reducing memory allocations and movement
  187. // use FIM repo-level pattern:
  188. // ref: https://arxiv.org/pdf/2409.12186
  189. //
  190. // [FIM_REP]myproject
  191. // [FIM_SEP]filename0
  192. // extra chunk 0
  193. // [FIM_SEP]filename1
  194. // extra chunk 1
  195. // ...
  196. // [FIM_SEP]filename
  197. // [FIM_PRE]prefix[FIM_SUF]suffix[FIM_MID]prompt
  198. //
  199. llama_tokens extra_tokens;
  200. extra_tokens.reserve(n_ctx);
  201. auto model = llama_get_model(ctx);
  202. auto tokens_prefix = tokenize_mixed(ctx, input_prefix, false, false);
  203. auto tokens_suffix = tokenize_mixed(ctx, input_suffix, false, false);
  204. if (llama_token_fim_rep(model) != LLAMA_TOKEN_NULL) {
  205. // TODO: make project name an input
  206. static const auto k_fim_repo = common_tokenize(ctx, "myproject\n", false, false);
  207. extra_tokens.push_back(llama_token_fim_rep(model));
  208. extra_tokens.insert(extra_tokens.end(), k_fim_repo.begin(), k_fim_repo.end());
  209. }
  210. for (const auto & chunk : input_extra) {
  211. // { "text": string, "filename": string }
  212. const std::string text = json_value(chunk, "text", std::string());
  213. const std::string filename = json_value(chunk, "filename", std::string("tmp"));
  214. if (llama_token_fim_sep(model) != LLAMA_TOKEN_NULL) {
  215. const auto k_fim_file = common_tokenize(ctx, filename + "\n", false, false);
  216. extra_tokens.insert(extra_tokens.end(), llama_token_fim_sep(model));
  217. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  218. } else {
  219. // chunk separator in binary form to avoid confusing the AI
  220. static const char k_chunk_prefix_str[] = {0x0a, 0x0a, 0x2d, 0x2d, 0x2d, 0x20, 0x73, 0x6e, 0x69, 0x70, 0x70, 0x65, 0x74, 0x20, 0x2d, 0x2d, 0x2d, 0x0a, 0x0a, 0x00};
  221. static const auto k_chunk_prefix_tokens = common_tokenize(ctx, k_chunk_prefix_str, false, false);
  222. extra_tokens.insert(extra_tokens.end(), k_chunk_prefix_tokens.begin(), k_chunk_prefix_tokens.end());
  223. }
  224. const auto chunk_tokens = common_tokenize(ctx, text, false, false);
  225. extra_tokens.insert(extra_tokens.end(), chunk_tokens.begin(), chunk_tokens.end());
  226. }
  227. if (llama_token_fim_sep(model) != LLAMA_TOKEN_NULL) {
  228. // TODO: current filename
  229. static const auto k_fim_file = common_tokenize(ctx, "filename\n", false, false);
  230. extra_tokens.insert(extra_tokens.end(), llama_token_fim_sep(model));
  231. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  232. }
  233. // for now pick FIM context to fit in a batch (ratio prefix:suffix = 3:1, TODO: configurable?)
  234. const int n_prefix_take = std::min<int>(tokens_prefix.size(), 3*(n_batch/4));
  235. const int n_suffix_take = std::min<int>(tokens_suffix.size(), std::max<int>(0, (n_batch/4) - (2 + tokens_prompt.size())));
  236. SRV_DBG("n_prefix_take = %d, n_suffix_take = %d, total = %d\n", n_prefix_take, n_suffix_take, (n_prefix_take + n_suffix_take));
  237. // fill the rest of the context with extra chunks
  238. const int n_extra_take = std::min<int>(std::max<int>(0, n_ctx - (n_batch) - 2*n_predict), extra_tokens.size());
  239. tokens_prefix.erase(tokens_prefix.begin(), tokens_prefix.begin() + tokens_prefix.size() - n_prefix_take);
  240. tokens_suffix.resize(n_suffix_take);
  241. tokens_prefix.insert(tokens_prefix.begin(), llama_token_fim_pre(model));
  242. tokens_prefix.insert(tokens_prefix.end(), tokens_prompt.begin(), tokens_prompt.end());
  243. tokens_suffix.insert(tokens_suffix.begin(), llama_token_fim_suf(model));
  244. auto embd_inp = spm_infill ? tokens_suffix : tokens_prefix;
  245. auto embd_end = spm_infill ? tokens_prefix : tokens_suffix;
  246. if (llama_add_bos_token(model)) {
  247. embd_inp.insert(embd_inp.begin(), llama_token_bos(model));
  248. }
  249. SRV_DBG("extra: n_ctx = %d, n_extra_take = %d, n_extra = %d\n", n_ctx, n_extra_take, (int) extra_tokens.size());
  250. // put the extra context before the FIM prefix
  251. embd_inp.insert(embd_inp.begin(), extra_tokens.end() - n_extra_take, extra_tokens.end());
  252. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  253. embd_inp.push_back(llama_token_fim_mid(model));
  254. return embd_inp;
  255. }
  256. // Format given chat. If tmpl is empty, we take the template from model metadata
  257. inline std::string format_chat(const struct llama_model * model, const std::string & tmpl, const std::vector<json> & messages) {
  258. std::vector<common_chat_msg> chat;
  259. for (size_t i = 0; i < messages.size(); ++i) {
  260. const auto & curr_msg = messages[i];
  261. std::string role = json_value(curr_msg, "role", std::string(""));
  262. std::string content;
  263. if (curr_msg.contains("content")) {
  264. if (curr_msg["content"].is_string()) {
  265. content = curr_msg["content"].get<std::string>();
  266. } else if (curr_msg["content"].is_array()) {
  267. for (const auto & part : curr_msg["content"]) {
  268. if (part.contains("text")) {
  269. content += "\n" + part["text"].get<std::string>();
  270. }
  271. }
  272. } else {
  273. throw std::runtime_error("Invalid 'content' type (ref: https://github.com/ggerganov/llama.cpp/issues/8367)");
  274. }
  275. } else {
  276. throw std::runtime_error("Missing 'content' (ref: https://github.com/ggerganov/llama.cpp/issues/8367)");
  277. }
  278. chat.push_back({role, content});
  279. }
  280. const auto formatted_chat = common_chat_apply_template(model, tmpl, chat, true);
  281. LOG_DBG("formatted_chat: '%s'\n", formatted_chat.c_str());
  282. return formatted_chat;
  283. }
  284. static std::string llama_get_chat_template(const struct llama_model * model) {
  285. std::string template_key = "tokenizer.chat_template";
  286. // call with NULL buffer to get the total size of the string
  287. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), NULL, 0);
  288. if (res < 0) {
  289. return "";
  290. } else {
  291. std::vector<char> model_template(res, 0);
  292. llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  293. return std::string(model_template.data(), model_template.size());
  294. }
  295. }
  296. //
  297. // base64 utils (TODO: move to common in the future)
  298. //
  299. static const std::string base64_chars =
  300. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  301. "abcdefghijklmnopqrstuvwxyz"
  302. "0123456789+/";
  303. static inline bool is_base64(uint8_t c) {
  304. return (isalnum(c) || (c == '+') || (c == '/'));
  305. }
  306. static inline std::vector<uint8_t> base64_decode(const std::string & encoded_string) {
  307. int i = 0;
  308. int j = 0;
  309. int in_ = 0;
  310. int in_len = encoded_string.size();
  311. uint8_t char_array_4[4];
  312. uint8_t char_array_3[3];
  313. std::vector<uint8_t> ret;
  314. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  315. char_array_4[i++] = encoded_string[in_]; in_++;
  316. if (i == 4) {
  317. for (i = 0; i < 4; i++) {
  318. char_array_4[i] = base64_chars.find(char_array_4[i]);
  319. }
  320. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  321. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  322. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  323. for (i = 0; (i < 3); i++) {
  324. ret.push_back(char_array_3[i]);
  325. }
  326. i = 0;
  327. }
  328. }
  329. if (i) {
  330. for (j = i; j < 4; j++) {
  331. char_array_4[j] = 0;
  332. }
  333. for (j = 0; j < 4; j++) {
  334. char_array_4[j] = base64_chars.find(char_array_4[j]);
  335. }
  336. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  337. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  338. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  339. for (j = 0; j < i - 1; j++) {
  340. ret.push_back(char_array_3[j]);
  341. }
  342. }
  343. return ret;
  344. }
  345. //
  346. // random string / id
  347. //
  348. static std::string random_string() {
  349. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  350. std::random_device rd;
  351. std::mt19937 generator(rd());
  352. std::string result(32, ' ');
  353. for (int i = 0; i < 32; ++i) {
  354. result[i] = str[generator() % str.size()];
  355. }
  356. return result;
  357. }
  358. static std::string gen_chatcmplid() {
  359. return "chatcmpl-" + random_string();
  360. }
  361. //
  362. // other common utils
  363. //
  364. static size_t longest_common_prefix(const llama_tokens & a, const llama_tokens & b) {
  365. size_t i;
  366. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  367. return i;
  368. }
  369. static size_t longest_common_subsequence(const llama_tokens & a, const llama_tokens & b) {
  370. // check for empty sequences
  371. if (a.empty() || b.empty()) {
  372. return 0;
  373. }
  374. // get the lengths of the input sequences
  375. size_t a_len = a.size();
  376. size_t b_len = b.size();
  377. // initialize the maximum length of the longest common subsequence (LCS)
  378. size_t max_length = 0;
  379. // use two rows instead of a 2D matrix to optimize space
  380. std::vector<size_t> prev_row(b_len + 1, 0);
  381. std::vector<size_t> curr_row(b_len + 1, 0);
  382. // iterate through the elements of a
  383. for (size_t i = 1; i <= a_len; i++) {
  384. // iterate through the elements of b
  385. for (size_t j = 1; j <= b_len; j++) {
  386. // if elements at the current positions match
  387. if (a[i - 1] == b[j - 1]) {
  388. // if it's the first element of either sequences, set LCS length to 1
  389. if (i == 1 || j == 1) {
  390. curr_row[j] = 1;
  391. } else {
  392. // increment LCS length by 1 compared to the previous element
  393. curr_row[j] = prev_row[j - 1] + 1;
  394. }
  395. // update max_length if necessary
  396. if (curr_row[j] > max_length) {
  397. max_length = curr_row[j];
  398. }
  399. } else {
  400. // reset LCS length if elements don't match
  401. curr_row[j] = 0;
  402. }
  403. }
  404. // update the previous row for the next iteration
  405. prev_row = curr_row;
  406. }
  407. // return the maximum length of the LCS
  408. return max_length;
  409. }
  410. static bool ends_with(const std::string & str, const std::string & suffix) {
  411. return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  412. }
  413. static size_t find_partial_stop_string(const std::string &stop, const std::string &text) {
  414. if (!text.empty() && !stop.empty()) {
  415. const char text_last_char = text.back();
  416. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
  417. if (stop[char_index] == text_last_char) {
  418. const std::string current_partial = stop.substr(0, char_index + 1);
  419. if (ends_with(text, current_partial)) {
  420. return text.size() - char_index - 1;
  421. }
  422. }
  423. }
  424. }
  425. return std::string::npos;
  426. }
  427. // TODO: reuse llama_detokenize
  428. template <class Iter>
  429. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  430. std::string ret;
  431. for (; begin != end; ++begin) {
  432. ret += common_token_to_piece(ctx, *begin);
  433. }
  434. return ret;
  435. }
  436. // format incomplete utf-8 multibyte character for output
  437. static std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  438. std::string out = token == -1 ? "" : common_token_to_piece(ctx, token);
  439. // if the size is 1 and first bit is 1, meaning it's a partial character
  440. // (size > 1 meaning it's already a known token)
  441. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  442. std::stringstream ss;
  443. ss << std::hex << (out[0] & 0xff);
  444. std::string res(ss.str());
  445. out = "byte: \\x" + res;
  446. }
  447. return out;
  448. }
  449. struct completion_token_output {
  450. llama_token tok;
  451. std::string text_to_send;
  452. struct token_prob {
  453. llama_token tok;
  454. float prob;
  455. };
  456. std::vector<token_prob> probs;
  457. };
  458. // convert a vector of completion_token_output to json
  459. static json probs_vector_to_json(const llama_context * ctx, const std::vector<completion_token_output> & probs) {
  460. json out = json::array();
  461. for (const auto & prob : probs) {
  462. json probs_for_token = json::array();
  463. for (const auto & p : prob.probs) {
  464. const std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  465. probs_for_token.push_back(json {
  466. {"tok_str", tok_str},
  467. {"prob", p.prob},
  468. });
  469. }
  470. const std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  471. out.push_back(json {
  472. {"content", tok_str},
  473. {"probs", probs_for_token},
  474. });
  475. }
  476. return out;
  477. }
  478. static bool server_sent_event(httplib::DataSink & sink, const char * event, const json & data) {
  479. const std::string str =
  480. std::string(event) + ": " +
  481. data.dump(-1, ' ', false, json::error_handler_t::replace) +
  482. "\n\n"; // note: these newlines are important (not sure why though, if you know, add a comment to explain)
  483. LOG_DBG("data stream, to_send: %s", str.c_str());
  484. return sink.write(str.c_str(), str.size());
  485. }
  486. //
  487. // OAI utils
  488. //
  489. static json oaicompat_completion_params_parse(
  490. const struct llama_model * model,
  491. const json & body, /* openai api json semantics */
  492. const std::string & chat_template) {
  493. json llama_params;
  494. llama_params["__oaicompat"] = true;
  495. // Apply chat template to the list of messages
  496. llama_params["prompt"] = format_chat(model, chat_template, body.at("messages"));
  497. // Handle "stop" field
  498. if (body.contains("stop") && body.at("stop").is_string()) {
  499. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  500. } else {
  501. llama_params["stop"] = json_value(body, "stop", json::array());
  502. }
  503. // Handle "response_format" field
  504. if (body.contains("response_format")) {
  505. json response_format = json_value(body, "response_format", json::object());
  506. std::string response_type = json_value(response_format, "type", std::string());
  507. if (response_type == "json_object") {
  508. llama_params["json_schema"] = json_value(response_format, "schema", json::object());
  509. } else if (response_type == "json_schema") {
  510. json json_schema = json_value(response_format, "json_schema", json::object());
  511. llama_params["json_schema"] = json_value(json_schema, "schema", json::object());
  512. } else if (!response_type.empty() && response_type != "text") {
  513. throw std::runtime_error("response_format type must be one of \"text\" or \"json_object\", but got: " + response_type);
  514. }
  515. }
  516. // Handle "n" field
  517. int n_choices = json_value(body, "n", 1);
  518. if (n_choices != 1) {
  519. throw std::runtime_error("Only one completion choice is allowed");
  520. }
  521. // Handle "logprobs" field
  522. // 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
  523. if (json_value(body, "logprobs", false)) {
  524. llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
  525. } else if (body.contains("top_logprobs") && !body.at("top_logprobs").is_null()) {
  526. throw std::runtime_error("top_logprobs requires logprobs to be set to true");
  527. }
  528. // Params supported by OAI but unsupported by llama.cpp
  529. static const std::vector<std::string> unsupported_params { "tools", "tool_choice" };
  530. for (const auto & param : unsupported_params) {
  531. if (body.contains(param)) {
  532. throw std::runtime_error("Unsupported param: " + param);
  533. }
  534. }
  535. // Copy remaining properties to llama_params
  536. // This allows user to use llama.cpp-specific params like "mirostat", ... via OAI endpoint.
  537. // See "launch_slot_with_task()" for a complete list of params supported by llama.cpp
  538. for (const auto & item : body.items()) {
  539. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  540. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  541. llama_params[item.key()] = item.value();
  542. }
  543. }
  544. return llama_params;
  545. }
  546. static json format_final_response_oaicompat(const json & request, const json & result, const std::string & completion_id, bool streaming = false, bool verbose = false) {
  547. bool stopped_word = result.count("stopped_word") != 0;
  548. bool stopped_eos = json_value(result, "stopped_eos", false);
  549. int num_tokens_predicted = json_value(result, "tokens_predicted", 0);
  550. int num_prompt_tokens = json_value(result, "tokens_evaluated", 0);
  551. std::string content = json_value(result, "content", std::string(""));
  552. std::string finish_reason = "length";
  553. if (stopped_word || stopped_eos) {
  554. finish_reason = "stop";
  555. }
  556. json choices =
  557. streaming ? json::array({json{{"finish_reason", finish_reason},
  558. {"index", 0},
  559. {"delta", json::object()}}})
  560. : json::array({json{{"finish_reason", finish_reason},
  561. {"index", 0},
  562. {"message", json{{"content", content},
  563. {"role", "assistant"}}}}});
  564. std::time_t t = std::time(0);
  565. json res = json {
  566. {"choices", choices},
  567. {"created", t},
  568. {"model",
  569. json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  570. {"object", streaming ? "chat.completion.chunk" : "chat.completion"},
  571. {"usage", json {
  572. {"completion_tokens", num_tokens_predicted},
  573. {"prompt_tokens", num_prompt_tokens},
  574. {"total_tokens", num_tokens_predicted + num_prompt_tokens}
  575. }},
  576. {"id", completion_id}
  577. };
  578. // extra fields for debugging purposes
  579. if (verbose) {
  580. res["__verbose"] = result;
  581. }
  582. if (result.contains("completion_probabilities")) {
  583. res["completion_probabilities"] = json_value(result, "completion_probabilities", json::array());
  584. }
  585. return res;
  586. }
  587. // return value is vector as there is one case where we might need to generate two responses
  588. static std::vector<json> format_partial_response_oaicompat(const json & result, const std::string & completion_id) {
  589. if (!result.contains("model") || !result.contains("oaicompat_token_ctr")) {
  590. return std::vector<json>({result});
  591. }
  592. bool first = json_value(result, "oaicompat_token_ctr", 0) == 0;
  593. std::string modelname = json_value(result, "model", std::string(DEFAULT_OAICOMPAT_MODEL));
  594. bool stopped_word = json_value(result, "stopped_word", false);
  595. bool stopped_eos = json_value(result, "stopped_eos", false);
  596. bool stopped_limit = json_value(result, "stopped_limit", false);
  597. std::string content = json_value(result, "content", std::string(""));
  598. std::string finish_reason;
  599. if (stopped_word || stopped_eos) {
  600. finish_reason = "stop";
  601. }
  602. if (stopped_limit) {
  603. finish_reason = "length";
  604. }
  605. std::time_t t = std::time(0);
  606. json choices;
  607. if (!finish_reason.empty()) {
  608. choices = json::array({json{{"finish_reason", finish_reason},
  609. {"index", 0},
  610. {"delta", json::object()}}});
  611. } else {
  612. if (first) {
  613. if (content.empty()) {
  614. choices = json::array({json{{"finish_reason", nullptr},
  615. {"index", 0},
  616. {"delta", json{{"role", "assistant"}}}}});
  617. } else {
  618. // We have to send this as two updates to conform to openai behavior
  619. json initial_ret = json{{"choices", json::array({json{
  620. {"finish_reason", nullptr},
  621. {"index", 0},
  622. {"delta", json{
  623. {"role", "assistant"}
  624. }}}})},
  625. {"created", t},
  626. {"id", completion_id},
  627. {"model", modelname},
  628. {"object", "chat.completion.chunk"}};
  629. json second_ret = json{
  630. {"choices", json::array({json{{"finish_reason", nullptr},
  631. {"index", 0},
  632. {"delta", json{
  633. {"content", content}}}
  634. }})},
  635. {"created", t},
  636. {"id", completion_id},
  637. {"model", modelname},
  638. {"object", "chat.completion.chunk"}};
  639. return std::vector<json>({initial_ret, second_ret});
  640. }
  641. } else {
  642. // Some idiosyncrasy in task processing logic makes several trailing calls
  643. // with empty content, we ignore these at the calee site.
  644. if (content.empty()) {
  645. return std::vector<json>({json::object()});
  646. }
  647. choices = json::array({json{
  648. {"finish_reason", nullptr},
  649. {"index", 0},
  650. {"delta",
  651. json{
  652. {"content", content},
  653. }},
  654. }});
  655. }
  656. }
  657. json ret = json {
  658. {"choices", choices},
  659. {"created", t},
  660. {"id", completion_id},
  661. {"model", modelname},
  662. {"object", "chat.completion.chunk"}
  663. };
  664. if (!finish_reason.empty()) {
  665. int num_tokens_predicted = json_value(result, "tokens_predicted", 0);
  666. int num_prompt_tokens = json_value(result, "tokens_evaluated", 0);
  667. ret.push_back({"usage", json {
  668. {"completion_tokens", num_tokens_predicted},
  669. {"prompt_tokens", num_prompt_tokens},
  670. {"total_tokens", num_tokens_predicted + num_prompt_tokens}
  671. }});
  672. }
  673. return std::vector<json>({ret});
  674. }
  675. static json format_embeddings_response_oaicompat(const json & request, const json & embeddings) {
  676. json data = json::array();
  677. int i = 0;
  678. for (const auto & elem : embeddings) {
  679. data.push_back(json{
  680. {"embedding", json_value(elem, "embedding", json::array())},
  681. {"index", i++},
  682. {"object", "embedding"}
  683. });
  684. }
  685. json res = json {
  686. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  687. {"object", "list"},
  688. {"usage", json { // TODO: fill
  689. {"prompt_tokens", 0},
  690. {"total_tokens", 0}
  691. }},
  692. {"data", data}
  693. };
  694. return res;
  695. }
  696. static json format_response_rerank(const json & request, const json & ranks) {
  697. json data = json::array();
  698. int i = 0;
  699. for (const auto & rank : ranks) {
  700. data.push_back(json{
  701. {"index", i++},
  702. {"relevance_score", json_value(rank, "score", 0.0)},
  703. });
  704. }
  705. json res = json {
  706. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  707. {"object", "list"},
  708. {"usage", json { // TODO: fill
  709. {"prompt_tokens", 0},
  710. {"total_tokens", 0}
  711. }},
  712. {"results", data}
  713. };
  714. return res;
  715. }
  716. static bool is_valid_utf8(const std::string & str) {
  717. const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data());
  718. const unsigned char* end = bytes + str.length();
  719. while (bytes < end) {
  720. if (*bytes <= 0x7F) {
  721. // 1-byte sequence (0xxxxxxx)
  722. bytes++;
  723. } else if ((*bytes & 0xE0) == 0xC0) {
  724. // 2-byte sequence (110xxxxx 10xxxxxx)
  725. if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80)
  726. return false;
  727. bytes += 2;
  728. } else if ((*bytes & 0xF0) == 0xE0) {
  729. // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx)
  730. if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80)
  731. return false;
  732. bytes += 3;
  733. } else if ((*bytes & 0xF8) == 0xF0) {
  734. // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
  735. if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 ||
  736. (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80)
  737. return false;
  738. bytes += 4;
  739. } else {
  740. // Invalid UTF-8 lead byte
  741. return false;
  742. }
  743. }
  744. return true;
  745. }
  746. static json format_tokenizer_response(const json & tokens) {
  747. return json {
  748. {"tokens", tokens}
  749. };
  750. }
  751. static json format_detokenized_response(const std::string & content) {
  752. return json {
  753. {"content", content}
  754. };
  755. }
  756. static json format_error_response(const std::string & message, const enum error_type type) {
  757. std::string type_str;
  758. int code = 500;
  759. switch (type) {
  760. case ERROR_TYPE_INVALID_REQUEST:
  761. type_str = "invalid_request_error";
  762. code = 400;
  763. break;
  764. case ERROR_TYPE_AUTHENTICATION:
  765. type_str = "authentication_error";
  766. code = 401;
  767. break;
  768. case ERROR_TYPE_NOT_FOUND:
  769. type_str = "not_found_error";
  770. code = 404;
  771. break;
  772. case ERROR_TYPE_SERVER:
  773. type_str = "server_error";
  774. code = 500;
  775. break;
  776. case ERROR_TYPE_PERMISSION:
  777. type_str = "permission_error";
  778. code = 403;
  779. break;
  780. case ERROR_TYPE_NOT_SUPPORTED:
  781. type_str = "not_supported_error";
  782. code = 501;
  783. break;
  784. case ERROR_TYPE_UNAVAILABLE:
  785. type_str = "unavailable_error";
  786. code = 503;
  787. break;
  788. }
  789. return json {
  790. {"code", code},
  791. {"message", message},
  792. {"type", type_str},
  793. };
  794. }