utils.hpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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. #include <memory>
  20. #define DEFAULT_OAICOMPAT_MODEL "gpt-3.5-turbo-0613"
  21. using json = nlohmann::ordered_json;
  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. template <typename T>
  35. static T json_value(const json & body, const std::string & key, const T & default_value) {
  36. // Fallback null to default value
  37. if (body.contains(key) && !body.at(key).is_null()) {
  38. try {
  39. return body.at(key);
  40. } catch (NLOHMANN_JSON_NAMESPACE::detail::type_error const &) {
  41. LOG_WRN("Wrong type supplied for parameter '%s'. Expected '%s', using default value\n", key.c_str(), json(default_value).type_name());
  42. return default_value;
  43. }
  44. } else {
  45. return default_value;
  46. }
  47. }
  48. //
  49. // tokenizer and input processing utils
  50. //
  51. static bool json_is_array_of_numbers(const json & data) {
  52. if (data.is_array()) {
  53. for (const auto & e : data) {
  54. if (!e.is_number_integer()) {
  55. return false;
  56. }
  57. }
  58. return true;
  59. }
  60. return false;
  61. }
  62. // is array having BOTH numbers & strings?
  63. static bool json_is_array_of_mixed_numbers_strings(const json & data) {
  64. bool seen_string = false;
  65. bool seen_number = false;
  66. if (data.is_array()) {
  67. for (const auto & e : data) {
  68. seen_string |= e.is_string();
  69. seen_number |= e.is_number_integer();
  70. if (seen_number && seen_string) {
  71. return true;
  72. }
  73. }
  74. }
  75. return false;
  76. }
  77. /**
  78. * this handles 2 cases:
  79. * - only string, example: "string"
  80. * - mixed string and tokens, example: [12, 34, "string", 56, 78]
  81. */
  82. static llama_tokens tokenize_mixed(const llama_context * ctx, const json & json_prompt, bool add_special, bool parse_special) {
  83. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  84. // or the first element of the json_prompt array is a string.
  85. llama_tokens prompt_tokens;
  86. if (json_prompt.is_array()) {
  87. bool first = true;
  88. for (const auto & p : json_prompt) {
  89. if (p.is_string()) {
  90. auto s = p.template get<std::string>();
  91. llama_tokens p;
  92. if (first) {
  93. p = common_tokenize(ctx, s, add_special, parse_special);
  94. first = false;
  95. } else {
  96. p = common_tokenize(ctx, s, false, parse_special);
  97. }
  98. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  99. } else {
  100. if (first) {
  101. first = false;
  102. }
  103. prompt_tokens.push_back(p.template get<llama_token>());
  104. }
  105. }
  106. } else {
  107. auto s = json_prompt.template get<std::string>();
  108. prompt_tokens = common_tokenize(ctx, s, add_special, parse_special);
  109. }
  110. return prompt_tokens;
  111. }
  112. /**
  113. * break the input "prompt" object into multiple prompt if needed, then tokenize them
  114. * this supports these cases:
  115. * - "prompt": "string"
  116. * - "prompt": [12, 34, 56]
  117. * - "prompt": [12, 34, "string", 56, 78]
  118. * and multiple prompts (multi-tasks):
  119. * - "prompt": ["string1", "string2"]
  120. * - "prompt": ["string1", [12, 34, 56]]
  121. * - "prompt": [[12, 34, "string", 56, 78], [12, 34, 56]]
  122. */
  123. static std::vector<llama_tokens> tokenize_input_prompts(llama_context * ctx, const json & json_prompt, bool add_special, bool parse_special) {
  124. std::vector<llama_tokens> result;
  125. if (json_prompt.is_string() || json_is_array_of_mixed_numbers_strings(json_prompt)) {
  126. // string or mixed
  127. result.push_back(tokenize_mixed(ctx, json_prompt, add_special, parse_special));
  128. } else if (json_is_array_of_numbers(json_prompt)) {
  129. // array of tokens
  130. result.push_back(json_prompt.get<llama_tokens>());
  131. } else if (json_prompt.is_array()) {
  132. // array of prompts
  133. result.reserve(json_prompt.size());
  134. for (const auto & p : json_prompt) {
  135. if (p.is_string() || json_is_array_of_mixed_numbers_strings(p)) {
  136. result.push_back(tokenize_mixed(ctx, p, add_special, parse_special));
  137. } else if (json_is_array_of_numbers(p)) {
  138. // array of tokens
  139. result.push_back(p.get<llama_tokens>());
  140. } else {
  141. throw std::runtime_error("element of \"prompt\" must be a string, an list of tokens, or a list of mixed strings & tokens");
  142. }
  143. }
  144. } else {
  145. throw std::runtime_error("\"prompt\" must be a string, an list of tokens, a list of mixed strings & tokens, or a list of prompts");
  146. }
  147. return result;
  148. }
  149. //
  150. // template utils
  151. //
  152. // format rerank task: [BOS]query[EOS][SEP]doc[EOS]
  153. static llama_tokens format_rerank(const struct llama_model * model, const llama_tokens & query, const llama_tokens & doc) {
  154. llama_tokens result;
  155. result.reserve(doc.size() + query.size() + 4);
  156. result.push_back(llama_token_bos(model));
  157. result.insert(result.end(), query.begin(), query.end());
  158. result.push_back(llama_token_eos(model));
  159. result.push_back(llama_token_sep(model));
  160. result.insert(result.end(), doc.begin(), doc.end());
  161. result.push_back(llama_token_eos(model));
  162. return result;
  163. }
  164. // format infill task
  165. static llama_tokens format_infill(
  166. const llama_context * ctx,
  167. const json & input_prefix,
  168. const json & input_suffix,
  169. const json & input_extra,
  170. const int n_batch,
  171. const int n_predict,
  172. const int n_ctx,
  173. const bool spm_infill,
  174. const llama_tokens & tokens_prompt
  175. ) {
  176. // TODO: optimize this block by reducing memory allocations and movement
  177. // use FIM repo-level pattern:
  178. // ref: https://arxiv.org/pdf/2409.12186
  179. //
  180. // [FIM_REP]myproject
  181. // [FIM_SEP]filename0
  182. // extra chunk 0
  183. // [FIM_SEP]filename1
  184. // extra chunk 1
  185. // ...
  186. // [FIM_SEP]filename
  187. // [FIM_PRE]prefix[FIM_SUF]suffix[FIM_MID]prompt
  188. //
  189. llama_tokens extra_tokens;
  190. extra_tokens.reserve(n_ctx);
  191. auto model = llama_get_model(ctx);
  192. auto tokens_prefix = tokenize_mixed(ctx, input_prefix, false, false);
  193. auto tokens_suffix = tokenize_mixed(ctx, input_suffix, false, false);
  194. if (llama_token_fim_rep(model) != LLAMA_TOKEN_NULL) {
  195. // TODO: make project name an input
  196. static const auto k_fim_repo = common_tokenize(ctx, "myproject\n", false, false);
  197. extra_tokens.push_back(llama_token_fim_rep(model));
  198. extra_tokens.insert(extra_tokens.end(), k_fim_repo.begin(), k_fim_repo.end());
  199. }
  200. for (const auto & chunk : input_extra) {
  201. // { "text": string, "filename": string }
  202. const std::string text = json_value(chunk, "text", std::string());
  203. const std::string filename = json_value(chunk, "filename", std::string("tmp"));
  204. if (llama_token_fim_sep(model) != LLAMA_TOKEN_NULL) {
  205. const auto k_fim_file = common_tokenize(ctx, filename + "\n", false, false);
  206. extra_tokens.insert(extra_tokens.end(), llama_token_fim_sep(model));
  207. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  208. } else {
  209. // chunk separator in binary form to avoid confusing the AI
  210. 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};
  211. static const auto k_chunk_prefix_tokens = common_tokenize(ctx, k_chunk_prefix_str, false, false);
  212. extra_tokens.insert(extra_tokens.end(), k_chunk_prefix_tokens.begin(), k_chunk_prefix_tokens.end());
  213. }
  214. const auto chunk_tokens = common_tokenize(ctx, text, false, false);
  215. extra_tokens.insert(extra_tokens.end(), chunk_tokens.begin(), chunk_tokens.end());
  216. }
  217. if (llama_token_fim_sep(model) != LLAMA_TOKEN_NULL) {
  218. // TODO: current filename
  219. static const auto k_fim_file = common_tokenize(ctx, "filename\n", false, false);
  220. extra_tokens.insert(extra_tokens.end(), llama_token_fim_sep(model));
  221. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  222. }
  223. // for now pick FIM context to fit in a batch (ratio prefix:suffix = 3:1, TODO: configurable?)
  224. const int n_prefix_take = std::min<int>(tokens_prefix.size(), 3*(n_batch/4));
  225. const int n_suffix_take = std::min<int>(tokens_suffix.size(), std::max<int>(0, (n_batch/4) - (2 + tokens_prompt.size())));
  226. 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));
  227. // fill the rest of the context with extra chunks
  228. const int n_extra_take = std::min<int>(std::max<int>(0, n_ctx - (n_batch) - 2*n_predict), extra_tokens.size());
  229. tokens_prefix.erase(tokens_prefix.begin(), tokens_prefix.begin() + tokens_prefix.size() - n_prefix_take);
  230. tokens_suffix.resize(n_suffix_take);
  231. tokens_prefix.insert(tokens_prefix.begin(), llama_token_fim_pre(model));
  232. tokens_prefix.insert(tokens_prefix.end(), tokens_prompt.begin(), tokens_prompt.end());
  233. tokens_suffix.insert(tokens_suffix.begin(), llama_token_fim_suf(model));
  234. auto embd_inp = spm_infill ? tokens_suffix : tokens_prefix;
  235. auto embd_end = spm_infill ? tokens_prefix : tokens_suffix;
  236. if (llama_add_bos_token(model)) {
  237. embd_inp.insert(embd_inp.begin(), llama_token_bos(model));
  238. }
  239. SRV_DBG("extra: n_ctx = %d, n_extra_take = %d, n_extra = %d\n", n_ctx, n_extra_take, (int) extra_tokens.size());
  240. // put the extra context before the FIM prefix
  241. embd_inp.insert(embd_inp.begin(), extra_tokens.end() - n_extra_take, extra_tokens.end());
  242. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  243. embd_inp.push_back(llama_token_fim_mid(model));
  244. return embd_inp;
  245. }
  246. // Format given chat. If tmpl is empty, we take the template from model metadata
  247. inline std::string format_chat(const struct llama_model * model, const std::string & tmpl, const std::vector<json> & messages) {
  248. std::vector<common_chat_msg> chat;
  249. for (size_t i = 0; i < messages.size(); ++i) {
  250. const auto & curr_msg = messages[i];
  251. std::string role = json_value(curr_msg, "role", std::string(""));
  252. std::string content;
  253. if (curr_msg.contains("content")) {
  254. if (curr_msg["content"].is_string()) {
  255. content = curr_msg["content"].get<std::string>();
  256. } else if (curr_msg["content"].is_array()) {
  257. for (const auto & part : curr_msg["content"]) {
  258. if (part.contains("text")) {
  259. content += "\n" + part["text"].get<std::string>();
  260. }
  261. }
  262. } else {
  263. throw std::runtime_error("Invalid 'content' type (ref: https://github.com/ggerganov/llama.cpp/issues/8367)");
  264. }
  265. } else {
  266. throw std::runtime_error("Missing 'content' (ref: https://github.com/ggerganov/llama.cpp/issues/8367)");
  267. }
  268. chat.push_back({role, content});
  269. }
  270. const auto formatted_chat = common_chat_apply_template(model, tmpl, chat, true);
  271. LOG_DBG("formatted_chat: '%s'\n", formatted_chat.c_str());
  272. return formatted_chat;
  273. }
  274. static std::string llama_get_chat_template(const struct llama_model * model) {
  275. std::string template_key = "tokenizer.chat_template";
  276. // call with NULL buffer to get the total size of the string
  277. int32_t res = llama_model_meta_val_str(model, template_key.c_str(), NULL, 0);
  278. if (res < 0) {
  279. return "";
  280. } else {
  281. std::vector<char> model_template(res, 0);
  282. llama_model_meta_val_str(model, template_key.c_str(), model_template.data(), model_template.size());
  283. return std::string(model_template.data(), model_template.size());
  284. }
  285. }
  286. //
  287. // base64 utils (TODO: move to common in the future)
  288. //
  289. static const std::string base64_chars =
  290. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  291. "abcdefghijklmnopqrstuvwxyz"
  292. "0123456789+/";
  293. static inline bool is_base64(uint8_t c) {
  294. return (isalnum(c) || (c == '+') || (c == '/'));
  295. }
  296. static inline std::vector<uint8_t> base64_decode(const std::string & encoded_string) {
  297. int i = 0;
  298. int j = 0;
  299. int in_ = 0;
  300. int in_len = encoded_string.size();
  301. uint8_t char_array_4[4];
  302. uint8_t char_array_3[3];
  303. std::vector<uint8_t> ret;
  304. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  305. char_array_4[i++] = encoded_string[in_]; in_++;
  306. if (i == 4) {
  307. for (i = 0; i < 4; i++) {
  308. char_array_4[i] = base64_chars.find(char_array_4[i]);
  309. }
  310. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  311. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  312. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  313. for (i = 0; (i < 3); i++) {
  314. ret.push_back(char_array_3[i]);
  315. }
  316. i = 0;
  317. }
  318. }
  319. if (i) {
  320. for (j = i; j < 4; j++) {
  321. char_array_4[j] = 0;
  322. }
  323. for (j = 0; j < 4; j++) {
  324. char_array_4[j] = base64_chars.find(char_array_4[j]);
  325. }
  326. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  327. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  328. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  329. for (j = 0; j < i - 1; j++) {
  330. ret.push_back(char_array_3[j]);
  331. }
  332. }
  333. return ret;
  334. }
  335. //
  336. // random string / id
  337. //
  338. static std::string random_string() {
  339. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  340. std::random_device rd;
  341. std::mt19937 generator(rd());
  342. std::string result(32, ' ');
  343. for (int i = 0; i < 32; ++i) {
  344. result[i] = str[generator() % str.size()];
  345. }
  346. return result;
  347. }
  348. static std::string gen_chatcmplid() {
  349. return "chatcmpl-" + random_string();
  350. }
  351. //
  352. // other common utils
  353. //
  354. static bool ends_with(const std::string & str, const std::string & suffix) {
  355. return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  356. }
  357. static size_t find_partial_stop_string(const std::string &stop, const std::string &text) {
  358. if (!text.empty() && !stop.empty()) {
  359. const char text_last_char = text.back();
  360. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
  361. if (stop[char_index] == text_last_char) {
  362. const std::string current_partial = stop.substr(0, char_index + 1);
  363. if (ends_with(text, current_partial)) {
  364. return text.size() - char_index - 1;
  365. }
  366. }
  367. }
  368. }
  369. return std::string::npos;
  370. }
  371. // TODO: reuse llama_detokenize
  372. template <class Iter>
  373. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  374. std::string ret;
  375. for (; begin != end; ++begin) {
  376. ret += common_token_to_piece(ctx, *begin);
  377. }
  378. return ret;
  379. }
  380. // format incomplete utf-8 multibyte character for output
  381. static std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  382. std::string out = token == -1 ? "" : common_token_to_piece(ctx, token);
  383. // if the size is 1 and first bit is 1, meaning it's a partial character
  384. // (size > 1 meaning it's already a known token)
  385. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  386. std::stringstream ss;
  387. ss << std::hex << (out[0] & 0xff);
  388. std::string res(ss.str());
  389. out = "byte: \\x" + res;
  390. }
  391. return out;
  392. }
  393. static bool server_sent_event(httplib::DataSink & sink, const char * event, const json & data) {
  394. const std::string str =
  395. std::string(event) + ": " +
  396. data.dump(-1, ' ', false, json::error_handler_t::replace) +
  397. "\n\n"; // required by RFC 8895 - A message is terminated by a blank line (two line terminators in a row).
  398. LOG_DBG("data stream, to_send: %s", str.c_str());
  399. return sink.write(str.c_str(), str.size());
  400. }
  401. //
  402. // OAI utils
  403. //
  404. static json oaicompat_completion_params_parse(
  405. const struct llama_model * model,
  406. const json & body, /* openai api json semantics */
  407. const std::string & chat_template) {
  408. json llama_params;
  409. llama_params["__oaicompat"] = true;
  410. // Apply chat template to the list of messages
  411. llama_params["prompt"] = format_chat(model, chat_template, body.at("messages"));
  412. // Handle "stop" field
  413. if (body.contains("stop") && body.at("stop").is_string()) {
  414. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  415. } else {
  416. llama_params["stop"] = json_value(body, "stop", json::array());
  417. }
  418. // Handle "response_format" field
  419. if (body.contains("response_format")) {
  420. json response_format = json_value(body, "response_format", json::object());
  421. std::string response_type = json_value(response_format, "type", std::string());
  422. if (response_type == "json_object") {
  423. llama_params["json_schema"] = json_value(response_format, "schema", json::object());
  424. } else if (response_type == "json_schema") {
  425. json json_schema = json_value(response_format, "json_schema", json::object());
  426. llama_params["json_schema"] = json_value(json_schema, "schema", json::object());
  427. } else if (!response_type.empty() && response_type != "text") {
  428. throw std::runtime_error("response_format type must be one of \"text\" or \"json_object\", but got: " + response_type);
  429. }
  430. }
  431. // Handle "n" field
  432. int n_choices = json_value(body, "n", 1);
  433. if (n_choices != 1) {
  434. throw std::runtime_error("Only one completion choice is allowed");
  435. }
  436. // Handle "logprobs" field
  437. // 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
  438. if (json_value(body, "logprobs", false)) {
  439. llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
  440. } else if (body.contains("top_logprobs") && !body.at("top_logprobs").is_null()) {
  441. throw std::runtime_error("top_logprobs requires logprobs to be set to true");
  442. }
  443. // Params supported by OAI but unsupported by llama.cpp
  444. static const std::vector<std::string> unsupported_params { "tools", "tool_choice" };
  445. for (const auto & param : unsupported_params) {
  446. if (body.contains(param)) {
  447. throw std::runtime_error("Unsupported param: " + param);
  448. }
  449. }
  450. // Copy remaining properties to llama_params
  451. // This allows user to use llama.cpp-specific params like "mirostat", ... via OAI endpoint.
  452. // See "launch_slot_with_task()" for a complete list of params supported by llama.cpp
  453. for (const auto & item : body.items()) {
  454. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  455. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  456. llama_params[item.key()] = item.value();
  457. }
  458. }
  459. return llama_params;
  460. }
  461. static json format_embeddings_response_oaicompat(const json & request, const json & embeddings) {
  462. json data = json::array();
  463. int i = 0;
  464. for (const auto & elem : embeddings) {
  465. data.push_back(json{
  466. {"embedding", json_value(elem, "embedding", json::array())},
  467. {"index", i++},
  468. {"object", "embedding"}
  469. });
  470. }
  471. json res = json {
  472. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  473. {"object", "list"},
  474. {"usage", json { // TODO: fill
  475. {"prompt_tokens", 0},
  476. {"total_tokens", 0}
  477. }},
  478. {"data", data}
  479. };
  480. return res;
  481. }
  482. static json format_response_rerank(const json & request, const json & ranks) {
  483. json data = json::array();
  484. int i = 0;
  485. for (const auto & rank : ranks) {
  486. data.push_back(json{
  487. {"index", i++},
  488. {"relevance_score", json_value(rank, "score", 0.0)},
  489. });
  490. }
  491. json res = json {
  492. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  493. {"object", "list"},
  494. {"usage", json { // TODO: fill
  495. {"prompt_tokens", 0},
  496. {"total_tokens", 0}
  497. }},
  498. {"results", data}
  499. };
  500. return res;
  501. }
  502. static bool is_valid_utf8(const std::string & str) {
  503. const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data());
  504. const unsigned char* end = bytes + str.length();
  505. while (bytes < end) {
  506. if (*bytes <= 0x7F) {
  507. // 1-byte sequence (0xxxxxxx)
  508. bytes++;
  509. } else if ((*bytes & 0xE0) == 0xC0) {
  510. // 2-byte sequence (110xxxxx 10xxxxxx)
  511. if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80)
  512. return false;
  513. bytes += 2;
  514. } else if ((*bytes & 0xF0) == 0xE0) {
  515. // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx)
  516. if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80)
  517. return false;
  518. bytes += 3;
  519. } else if ((*bytes & 0xF8) == 0xF0) {
  520. // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
  521. if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 ||
  522. (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80)
  523. return false;
  524. bytes += 4;
  525. } else {
  526. // Invalid UTF-8 lead byte
  527. return false;
  528. }
  529. }
  530. return true;
  531. }
  532. static json format_tokenizer_response(const json & tokens) {
  533. return json {
  534. {"tokens", tokens}
  535. };
  536. }
  537. static json format_detokenized_response(const std::string & content) {
  538. return json {
  539. {"content", content}
  540. };
  541. }