utils.hpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. #pragma once
  2. #include "common.h"
  3. #include "log.h"
  4. #include "llama.h"
  5. #include "common/base64.hpp"
  6. #ifndef NDEBUG
  7. // crash the server in debug mode, otherwise send an http 500 error
  8. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  9. #endif
  10. // increase max payload length to allow use of larger context size
  11. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 1048576
  12. #include "httplib.h"
  13. // Change JSON_ASSERT from assert() to GGML_ASSERT:
  14. #define JSON_ASSERT GGML_ASSERT
  15. #include "json.hpp"
  16. #include "minja.hpp"
  17. #include "chat-template.hpp"
  18. #include <random>
  19. #include <sstream>
  20. #include <string>
  21. #include <vector>
  22. #include <memory>
  23. #define DEFAULT_OAICOMPAT_MODEL "gpt-3.5-turbo"
  24. using json = nlohmann::ordered_json;
  25. #define SLT_INF(slot, fmt, ...) LOG_INF("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  26. #define SLT_WRN(slot, fmt, ...) LOG_WRN("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  27. #define SLT_ERR(slot, fmt, ...) LOG_ERR("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  28. #define SLT_DBG(slot, fmt, ...) LOG_DBG("slot %12.*s: id %2d | task %d | " fmt, 12, __func__, (slot).id, (slot).id_task, __VA_ARGS__)
  29. #define SRV_INF(fmt, ...) LOG_INF("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  30. #define SRV_WRN(fmt, ...) LOG_WRN("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  31. #define SRV_ERR(fmt, ...) LOG_ERR("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  32. #define SRV_DBG(fmt, ...) LOG_DBG("srv %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  33. #define QUE_INF(fmt, ...) LOG_INF("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  34. #define QUE_WRN(fmt, ...) LOG_WRN("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  35. #define QUE_ERR(fmt, ...) LOG_ERR("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  36. #define QUE_DBG(fmt, ...) LOG_DBG("que %12.*s: " fmt, 12, __func__, __VA_ARGS__)
  37. template <typename T>
  38. static T json_value(const json & body, const std::string & key, const T & default_value) {
  39. // Fallback null to default value
  40. if (body.contains(key) && !body.at(key).is_null()) {
  41. try {
  42. return body.at(key);
  43. } catch (NLOHMANN_JSON_NAMESPACE::detail::type_error const &) {
  44. LOG_WRN("Wrong type supplied for parameter '%s'. Expected '%s', using default value\n", key.c_str(), json(default_value).type_name());
  45. return default_value;
  46. }
  47. } else {
  48. return default_value;
  49. }
  50. }
  51. const static std::string build_info("b" + std::to_string(LLAMA_BUILD_NUMBER) + "-" + LLAMA_COMMIT);
  52. //
  53. // tokenizer and input processing utils
  54. //
  55. static bool json_is_array_of_numbers(const json & data) {
  56. if (data.is_array()) {
  57. for (const auto & e : data) {
  58. if (!e.is_number_integer()) {
  59. return false;
  60. }
  61. }
  62. return true;
  63. }
  64. return false;
  65. }
  66. // is array having BOTH numbers & strings?
  67. static bool json_is_array_of_mixed_numbers_strings(const json & data) {
  68. bool seen_string = false;
  69. bool seen_number = false;
  70. if (data.is_array()) {
  71. for (const auto & e : data) {
  72. seen_string |= e.is_string();
  73. seen_number |= e.is_number_integer();
  74. if (seen_number && seen_string) {
  75. return true;
  76. }
  77. }
  78. }
  79. return false;
  80. }
  81. // get value by path(key1 / key2)
  82. static json json_get_nested_values(const std::vector<std::string> & paths, const json & js) {
  83. json result = json::object();
  84. for (const std::string & path : paths) {
  85. json current = js;
  86. const auto keys = string_split<std::string>(path, /*separator*/ '/');
  87. bool valid_path = true;
  88. for (const std::string & k : keys) {
  89. if (valid_path && current.is_object() && current.contains(k)) {
  90. current = current[k];
  91. } else {
  92. valid_path = false;
  93. }
  94. }
  95. if (valid_path) {
  96. result[path] = current;
  97. }
  98. }
  99. return result;
  100. }
  101. /**
  102. * this handles 2 cases:
  103. * - only string, example: "string"
  104. * - mixed string and tokens, example: [12, 34, "string", 56, 78]
  105. */
  106. static llama_tokens tokenize_mixed(const llama_vocab * vocab, const json & json_prompt, bool add_special, bool parse_special) {
  107. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  108. // or the first element of the json_prompt array is a string.
  109. llama_tokens prompt_tokens;
  110. if (json_prompt.is_array()) {
  111. bool first = true;
  112. for (const auto & p : json_prompt) {
  113. if (p.is_string()) {
  114. auto s = p.template get<std::string>();
  115. llama_tokens p;
  116. if (first) {
  117. p = common_tokenize(vocab, s, add_special, parse_special);
  118. first = false;
  119. } else {
  120. p = common_tokenize(vocab, s, false, parse_special);
  121. }
  122. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  123. } else {
  124. if (first) {
  125. first = false;
  126. }
  127. prompt_tokens.push_back(p.template get<llama_token>());
  128. }
  129. }
  130. } else {
  131. auto s = json_prompt.template get<std::string>();
  132. prompt_tokens = common_tokenize(vocab, s, add_special, parse_special);
  133. }
  134. return prompt_tokens;
  135. }
  136. /**
  137. * break the input "prompt" object into multiple prompt if needed, then tokenize them
  138. * this supports these cases:
  139. * - "prompt": "string"
  140. * - "prompt": [12, 34, 56]
  141. * - "prompt": [12, 34, "string", 56, 78]
  142. * and multiple prompts (multi-tasks):
  143. * - "prompt": ["string1", "string2"]
  144. * - "prompt": ["string1", [12, 34, 56]]
  145. * - "prompt": [[12, 34, 56], [78, 90, 12]]
  146. * - "prompt": [[12, 34, "string", 56, 78], [12, 34, 56]]
  147. */
  148. static std::vector<llama_tokens> tokenize_input_prompts(const llama_vocab * vocab, const json & json_prompt, bool add_special, bool parse_special) {
  149. std::vector<llama_tokens> result;
  150. if (json_prompt.is_string() || json_is_array_of_mixed_numbers_strings(json_prompt)) {
  151. // string or mixed
  152. result.push_back(tokenize_mixed(vocab, json_prompt, add_special, parse_special));
  153. } else if (json_is_array_of_numbers(json_prompt)) {
  154. // array of tokens
  155. result.push_back(json_prompt.get<llama_tokens>());
  156. } else if (json_prompt.is_array()) {
  157. // array of prompts
  158. result.reserve(json_prompt.size());
  159. for (const auto & p : json_prompt) {
  160. if (p.is_string() || json_is_array_of_mixed_numbers_strings(p)) {
  161. result.push_back(tokenize_mixed(vocab, p, add_special, parse_special));
  162. } else if (json_is_array_of_numbers(p)) {
  163. // array of tokens
  164. result.push_back(p.get<llama_tokens>());
  165. } else {
  166. throw std::runtime_error("element of \"prompt\" must be a string, an list of tokens, or a list of mixed strings & tokens");
  167. }
  168. }
  169. } else {
  170. throw std::runtime_error("\"prompt\" must be a string, an list of tokens, a list of mixed strings & tokens, or a list of prompts");
  171. }
  172. if (result.empty()) {
  173. throw std::runtime_error("\"prompt\" must not be empty");
  174. }
  175. return result;
  176. }
  177. // return the last index of character that can form a valid string
  178. // if the last character is potentially cut in half, return the index before the cut
  179. // if validate_utf8(text) == text.size(), then the whole text is valid utf8
  180. static size_t validate_utf8(const std::string& text) {
  181. size_t len = text.size();
  182. if (len == 0) return 0;
  183. // Check the last few bytes to see if a multi-byte character is cut off
  184. for (size_t i = 1; i <= 4 && i <= len; ++i) {
  185. unsigned char c = text[len - i];
  186. // Check for start of a multi-byte sequence from the end
  187. if ((c & 0xE0) == 0xC0) {
  188. // 2-byte character start: 110xxxxx
  189. // Needs at least 2 bytes
  190. if (i < 2) return len - i;
  191. } else if ((c & 0xF0) == 0xE0) {
  192. // 3-byte character start: 1110xxxx
  193. // Needs at least 3 bytes
  194. if (i < 3) return len - i;
  195. } else if ((c & 0xF8) == 0xF0) {
  196. // 4-byte character start: 11110xxx
  197. // Needs at least 4 bytes
  198. if (i < 4) return len - i;
  199. }
  200. }
  201. // If no cut-off multi-byte character is found, return full length
  202. return len;
  203. }
  204. //
  205. // template utils
  206. //
  207. // format rerank task: [BOS]query[EOS][SEP]doc[EOS]
  208. static llama_tokens format_rerank(const struct llama_vocab * vocab, const llama_tokens & query, const llama_tokens & doc) {
  209. llama_tokens result;
  210. result.reserve(doc.size() + query.size() + 4);
  211. result.push_back(llama_vocab_bos(vocab));
  212. result.insert(result.end(), query.begin(), query.end());
  213. result.push_back(llama_vocab_eos(vocab));
  214. result.push_back(llama_vocab_sep(vocab));
  215. result.insert(result.end(), doc.begin(), doc.end());
  216. result.push_back(llama_vocab_eos(vocab));
  217. return result;
  218. }
  219. // format infill task
  220. static llama_tokens format_infill(
  221. const llama_vocab * vocab,
  222. const json & input_prefix,
  223. const json & input_suffix,
  224. const json & input_extra,
  225. const int n_batch,
  226. const int n_predict,
  227. const int n_ctx,
  228. const bool spm_infill,
  229. const llama_tokens & tokens_prompt
  230. ) {
  231. // TODO: optimize this block by reducing memory allocations and movement
  232. // use FIM repo-level pattern:
  233. // ref: https://arxiv.org/pdf/2409.12186
  234. //
  235. // [FIM_REP]myproject
  236. // [FIM_SEP]filename0
  237. // extra chunk 0
  238. // [FIM_SEP]filename1
  239. // extra chunk 1
  240. // ...
  241. // [FIM_SEP]filename
  242. // [FIM_PRE]prefix[FIM_SUF]suffix[FIM_MID]prompt
  243. //
  244. llama_tokens extra_tokens;
  245. extra_tokens.reserve(n_ctx);
  246. auto tokens_prefix = tokenize_mixed(vocab, input_prefix, false, false);
  247. auto tokens_suffix = tokenize_mixed(vocab, input_suffix, false, false);
  248. if (llama_vocab_fim_rep(vocab) != LLAMA_TOKEN_NULL) {
  249. // TODO: make project name an input
  250. static const auto k_fim_repo = common_tokenize(vocab, "myproject\n", false, false);
  251. extra_tokens.push_back(llama_vocab_fim_rep(vocab));
  252. extra_tokens.insert(extra_tokens.end(), k_fim_repo.begin(), k_fim_repo.end());
  253. }
  254. for (const auto & chunk : input_extra) {
  255. // { "text": string, "filename": string }
  256. const std::string text = json_value(chunk, "text", std::string());
  257. const std::string filename = json_value(chunk, "filename", std::string("tmp"));
  258. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  259. const auto k_fim_file = common_tokenize(vocab, filename + "\n", false, false);
  260. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  261. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  262. } else {
  263. // chunk separator in binary form to avoid confusing the AI
  264. 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};
  265. static const auto k_chunk_prefix_tokens = common_tokenize(vocab, k_chunk_prefix_str, false, false);
  266. extra_tokens.insert(extra_tokens.end(), k_chunk_prefix_tokens.begin(), k_chunk_prefix_tokens.end());
  267. }
  268. const auto chunk_tokens = common_tokenize(vocab, text, false, false);
  269. extra_tokens.insert(extra_tokens.end(), chunk_tokens.begin(), chunk_tokens.end());
  270. }
  271. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  272. // TODO: current filename
  273. static const auto k_fim_file = common_tokenize(vocab, "filename\n", false, false);
  274. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  275. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  276. }
  277. // for now pick FIM context to fit in a batch (ratio prefix:suffix = 3:1, TODO: configurable?)
  278. const int n_prefix_take = std::min<int>(tokens_prefix.size(), 3*(n_batch/4));
  279. const int n_suffix_take = std::min<int>(tokens_suffix.size(), std::max<int>(0, (n_batch/4) - (2 + tokens_prompt.size())));
  280. 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));
  281. // fill the rest of the context with extra chunks
  282. const int n_extra_take = std::min<int>(std::max<int>(0, n_ctx - (n_batch) - 2*n_predict), extra_tokens.size());
  283. tokens_prefix.erase(tokens_prefix.begin(), tokens_prefix.begin() + tokens_prefix.size() - n_prefix_take);
  284. tokens_suffix.resize(n_suffix_take);
  285. tokens_prefix.insert(tokens_prefix.begin(), llama_vocab_fim_pre(vocab));
  286. tokens_prefix.insert(tokens_prefix.end(), tokens_prompt.begin(), tokens_prompt.end());
  287. tokens_suffix.insert(tokens_suffix.begin(), llama_vocab_fim_suf(vocab));
  288. auto embd_inp = spm_infill ? tokens_suffix : tokens_prefix;
  289. auto embd_end = spm_infill ? tokens_prefix : tokens_suffix;
  290. if (llama_vocab_get_add_bos(vocab)) {
  291. embd_inp.insert(embd_inp.begin(), llama_vocab_bos(vocab));
  292. }
  293. SRV_DBG("extra: n_ctx = %d, n_extra_take = %d, n_extra = %d\n", n_ctx, n_extra_take, (int) extra_tokens.size());
  294. // put the extra context before the FIM prefix
  295. embd_inp.insert(embd_inp.begin(), extra_tokens.end() - n_extra_take, extra_tokens.end());
  296. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  297. embd_inp.push_back(llama_vocab_fim_mid(vocab));
  298. return embd_inp;
  299. }
  300. // Format given chat. If tmpl is empty, we take the template from model metadata
  301. inline std::string format_chat(const common_chat_template & tmpl, const std::vector<json> & messages) {
  302. std::vector<common_chat_msg> chat;
  303. for (size_t i = 0; i < messages.size(); ++i) {
  304. const auto & curr_msg = messages[i];
  305. std::string role = json_value(curr_msg, "role", std::string(""));
  306. std::string content;
  307. if (curr_msg.contains("content")) {
  308. if (curr_msg["content"].is_string()) {
  309. content = curr_msg["content"].get<std::string>();
  310. } else if (curr_msg["content"].is_array()) {
  311. for (const auto & part : curr_msg["content"]) {
  312. if (part.contains("text")) {
  313. content += "\n" + part["text"].get<std::string>();
  314. }
  315. }
  316. } else {
  317. throw std::runtime_error("Invalid 'content' type (ref: https://github.com/ggerganov/llama.cpp/issues/8367)");
  318. }
  319. } else {
  320. throw std::runtime_error("Missing 'content' (ref: https://github.com/ggerganov/llama.cpp/issues/8367)");
  321. }
  322. chat.push_back({role, content});
  323. }
  324. const auto formatted_chat = common_chat_apply_template(tmpl, chat, true, /* use_jinja= */ false);
  325. LOG_DBG("formatted_chat: '%s'\n", formatted_chat.c_str());
  326. return formatted_chat;
  327. }
  328. //
  329. // base64 utils (TODO: move to common in the future)
  330. //
  331. static const std::string base64_chars =
  332. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  333. "abcdefghijklmnopqrstuvwxyz"
  334. "0123456789+/";
  335. static inline bool is_base64(uint8_t c) {
  336. return (isalnum(c) || (c == '+') || (c == '/'));
  337. }
  338. static inline std::vector<uint8_t> base64_decode(const std::string & encoded_string) {
  339. int i = 0;
  340. int j = 0;
  341. int in_ = 0;
  342. int in_len = encoded_string.size();
  343. uint8_t char_array_4[4];
  344. uint8_t char_array_3[3];
  345. std::vector<uint8_t> ret;
  346. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  347. char_array_4[i++] = encoded_string[in_]; in_++;
  348. if (i == 4) {
  349. for (i = 0; i < 4; i++) {
  350. char_array_4[i] = base64_chars.find(char_array_4[i]);
  351. }
  352. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  353. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  354. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  355. for (i = 0; (i < 3); i++) {
  356. ret.push_back(char_array_3[i]);
  357. }
  358. i = 0;
  359. }
  360. }
  361. if (i) {
  362. for (j = i; j < 4; j++) {
  363. char_array_4[j] = 0;
  364. }
  365. for (j = 0; j < 4; j++) {
  366. char_array_4[j] = base64_chars.find(char_array_4[j]);
  367. }
  368. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  369. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  370. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  371. for (j = 0; j < i - 1; j++) {
  372. ret.push_back(char_array_3[j]);
  373. }
  374. }
  375. return ret;
  376. }
  377. //
  378. // random string / id
  379. //
  380. static std::string random_string() {
  381. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  382. std::random_device rd;
  383. std::mt19937 generator(rd());
  384. std::string result(32, ' ');
  385. for (int i = 0; i < 32; ++i) {
  386. result[i] = str[generator() % str.size()];
  387. }
  388. return result;
  389. }
  390. static std::string gen_chatcmplid() {
  391. return "chatcmpl-" + random_string();
  392. }
  393. //
  394. // other common utils
  395. //
  396. static bool ends_with(const std::string & str, const std::string & suffix) {
  397. return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  398. }
  399. static size_t find_partial_stop_string(const std::string &stop, const std::string &text) {
  400. if (!text.empty() && !stop.empty()) {
  401. const char text_last_char = text.back();
  402. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
  403. if (stop[char_index] == text_last_char) {
  404. const std::string current_partial = stop.substr(0, char_index + 1);
  405. if (ends_with(text, current_partial)) {
  406. return text.size() - char_index - 1;
  407. }
  408. }
  409. }
  410. }
  411. return std::string::npos;
  412. }
  413. // TODO: reuse llama_detokenize
  414. template <class Iter>
  415. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  416. std::string ret;
  417. for (; begin != end; ++begin) {
  418. ret += common_token_to_piece(ctx, *begin);
  419. }
  420. return ret;
  421. }
  422. // format incomplete utf-8 multibyte character for output
  423. static std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  424. std::string out = token == LLAMA_TOKEN_NULL ? "" : common_token_to_piece(ctx, token);
  425. // if the size is 1 and first bit is 1, meaning it's a partial character
  426. // (size > 1 meaning it's already a known token)
  427. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  428. std::stringstream ss;
  429. ss << std::hex << (out[0] & 0xff);
  430. std::string res(ss.str());
  431. out = "byte: \\x" + res;
  432. }
  433. return out;
  434. }
  435. static bool server_sent_event(httplib::DataSink & sink, const char * event, const json & data) {
  436. const std::string str =
  437. std::string(event) + ": " +
  438. data.dump(-1, ' ', false, json::error_handler_t::replace) +
  439. "\n\n"; // required by RFC 8895 - A message is terminated by a blank line (two line terminators in a row).
  440. LOG_DBG("data stream, to_send: %s", str.c_str());
  441. return sink.write(str.c_str(), str.size());
  442. }
  443. //
  444. // OAI utils
  445. //
  446. static json oaicompat_completion_params_parse(const json & body) {
  447. json llama_params;
  448. if (!body.contains("prompt")) {
  449. throw std::runtime_error("\"prompt\" is required");
  450. }
  451. // Handle "stop" field
  452. if (body.contains("stop") && body.at("stop").is_string()) {
  453. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  454. } else {
  455. llama_params["stop"] = json_value(body, "stop", json::array());
  456. }
  457. // Handle "n" field
  458. int n_choices = json_value(body, "n", 1);
  459. if (n_choices != 1) {
  460. throw std::runtime_error("Only one completion choice is allowed");
  461. }
  462. // Params supported by OAI but unsupported by llama.cpp
  463. static const std::vector<std::string> unsupported_params { "best_of", "echo", "suffix" };
  464. for (const auto & param : unsupported_params) {
  465. if (body.contains(param)) {
  466. throw std::runtime_error("Unsupported param: " + param);
  467. }
  468. }
  469. // Copy remaining properties to llama_params
  470. for (const auto & item : body.items()) {
  471. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  472. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  473. llama_params[item.key()] = item.value();
  474. }
  475. }
  476. return llama_params;
  477. }
  478. static json oaicompat_completion_params_parse(
  479. const json & body, /* openai api json semantics */
  480. const common_chat_template & tmpl,
  481. bool use_jinja)
  482. {
  483. json llama_params;
  484. auto tools = json_value(body, "tools", json());
  485. auto has_tools = tools.is_array() && !tools.empty();
  486. if (has_tools) {
  487. if (use_jinja) {
  488. LOG_WRN("tools param is not fully supported yet\n");
  489. } else {
  490. throw std::runtime_error("tools param requires --jinja flag");
  491. }
  492. }
  493. // Handle "stop" field
  494. if (body.contains("stop") && body.at("stop").is_string()) {
  495. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  496. } else {
  497. llama_params["stop"] = json_value(body, "stop", json::array());
  498. }
  499. // Handle "response_format" field
  500. if (body.contains("response_format")) {
  501. json response_format = json_value(body, "response_format", json::object());
  502. std::string response_type = json_value(response_format, "type", std::string());
  503. if (response_type == "json_object") {
  504. llama_params["json_schema"] = json_value(response_format, "schema", json::object());
  505. } else if (response_type == "json_schema") {
  506. json json_schema = json_value(response_format, "json_schema", json::object());
  507. llama_params["json_schema"] = json_value(json_schema, "schema", json::object());
  508. } else if (!response_type.empty() && response_type != "text") {
  509. throw std::runtime_error("response_format type must be one of \"text\" or \"json_object\", but got: " + response_type);
  510. }
  511. }
  512. // Apply chat template to the list of messages
  513. if (use_jinja) {
  514. llama_params["prompt"] = tmpl.apply(body.at("messages"), tools, /* add_generation_prompt= */ true);
  515. } else {
  516. llama_params["prompt"] = format_chat(tmpl, body.at("messages"));
  517. }
  518. // Handle "n" field
  519. int n_choices = json_value(body, "n", 1);
  520. if (n_choices != 1) {
  521. throw std::runtime_error("Only one completion choice is allowed");
  522. }
  523. // Handle "logprobs" field
  524. // 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
  525. if (json_value(body, "logprobs", false)) {
  526. llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
  527. } else if (body.contains("top_logprobs") && !body.at("top_logprobs").is_null()) {
  528. throw std::runtime_error("top_logprobs requires logprobs to be set to true");
  529. }
  530. // Params supported by OAI but unsupported by llama.cpp
  531. static const std::vector<std::string> unsupported_params { "tool_choice" };
  532. for (const auto & param : unsupported_params) {
  533. if (body.contains(param)) {
  534. throw std::runtime_error("Unsupported param: " + param);
  535. }
  536. }
  537. // Copy remaining properties to llama_params
  538. // This allows user to use llama.cpp-specific params like "mirostat", ... via OAI endpoint.
  539. // See "launch_slot_with_task()" for a complete list of params supported by llama.cpp
  540. for (const auto & item : body.items()) {
  541. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  542. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  543. llama_params[item.key()] = item.value();
  544. }
  545. }
  546. return llama_params;
  547. }
  548. static json format_embeddings_response_oaicompat(const json & request, const json & embeddings, bool use_base64 = false) {
  549. json data = json::array();
  550. int32_t n_tokens = 0;
  551. int i = 0;
  552. for (const auto & elem : embeddings) {
  553. json embedding_obj;
  554. if (use_base64) {
  555. const auto& vec = json_value(elem, "embedding", json::array()).get<std::vector<float>>();
  556. const char* data_ptr = reinterpret_cast<const char*>(vec.data());
  557. size_t data_size = vec.size() * sizeof(float);
  558. embedding_obj = {
  559. {"embedding", base64::encode(data_ptr, data_size)},
  560. {"index", i++},
  561. {"object", "embedding"},
  562. {"encoding_format", "base64"}
  563. };
  564. } else {
  565. embedding_obj = {
  566. {"embedding", json_value(elem, "embedding", json::array())},
  567. {"index", i++},
  568. {"object", "embedding"}
  569. };
  570. }
  571. data.push_back(embedding_obj);
  572. n_tokens += json_value(elem, "tokens_evaluated", 0);
  573. }
  574. json res = json {
  575. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  576. {"object", "list"},
  577. {"usage", json {
  578. {"prompt_tokens", n_tokens},
  579. {"total_tokens", n_tokens}
  580. }},
  581. {"data", data}
  582. };
  583. return res;
  584. }
  585. static json format_response_rerank(const json & request, const json & ranks) {
  586. json data = json::array();
  587. int32_t n_tokens = 0;
  588. int i = 0;
  589. for (const auto & rank : ranks) {
  590. data.push_back(json{
  591. {"index", i++},
  592. {"relevance_score", json_value(rank, "score", 0.0)},
  593. });
  594. n_tokens += json_value(rank, "tokens_evaluated", 0);
  595. }
  596. json res = json {
  597. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  598. {"object", "list"},
  599. {"usage", json {
  600. {"prompt_tokens", n_tokens},
  601. {"total_tokens", n_tokens}
  602. }},
  603. {"results", data}
  604. };
  605. return res;
  606. }
  607. static bool is_valid_utf8(const std::string & str) {
  608. const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data());
  609. const unsigned char* end = bytes + str.length();
  610. while (bytes < end) {
  611. if (*bytes <= 0x7F) {
  612. // 1-byte sequence (0xxxxxxx)
  613. bytes++;
  614. } else if ((*bytes & 0xE0) == 0xC0) {
  615. // 2-byte sequence (110xxxxx 10xxxxxx)
  616. if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80)
  617. return false;
  618. bytes += 2;
  619. } else if ((*bytes & 0xF0) == 0xE0) {
  620. // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx)
  621. if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80)
  622. return false;
  623. bytes += 3;
  624. } else if ((*bytes & 0xF8) == 0xF0) {
  625. // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
  626. if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 ||
  627. (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80)
  628. return false;
  629. bytes += 4;
  630. } else {
  631. // Invalid UTF-8 lead byte
  632. return false;
  633. }
  634. }
  635. return true;
  636. }
  637. static json format_tokenizer_response(const json & tokens) {
  638. return json {
  639. {"tokens", tokens}
  640. };
  641. }
  642. static json format_detokenized_response(const std::string & content) {
  643. return json {
  644. {"content", content}
  645. };
  646. }
  647. static json format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) {
  648. json data = json::array();
  649. for (const auto & lb : logit_bias) {
  650. data.push_back(json{
  651. {"bias", lb.bias},
  652. {"token", lb.token},
  653. });
  654. }
  655. return data;
  656. }
  657. static std::string safe_json_to_str(const json & data) {
  658. return data.dump(-1, ' ', false, json::error_handler_t::replace);
  659. }
  660. static std::vector<llama_token_data> get_token_probabilities(llama_context * ctx, int idx) {
  661. std::vector<llama_token_data> cur;
  662. const auto * logits = llama_get_logits_ith(ctx, idx);
  663. const llama_model * model = llama_get_model(ctx);
  664. const llama_vocab * vocab = llama_model_get_vocab(model);
  665. const int n_vocab = llama_vocab_n_tokens(vocab);
  666. cur.resize(n_vocab);
  667. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  668. cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
  669. }
  670. // sort tokens by logits
  671. std::sort(cur.begin(), cur.end(), [](const llama_token_data & a, const llama_token_data & b) {
  672. return a.logit > b.logit;
  673. });
  674. // apply softmax
  675. float max_l = cur[0].logit;
  676. float cum_sum = 0.0f;
  677. for (size_t i = 0; i < cur.size(); ++i) {
  678. float p = expf(cur[i].logit - max_l);
  679. cur[i].p = p;
  680. cum_sum += p;
  681. }
  682. for (size_t i = 0; i < cur.size(); ++i) {
  683. cur[i].p /= cum_sum;
  684. }
  685. return cur;
  686. }
  687. static bool are_lora_equal(
  688. const std::vector<common_adapter_lora_info> & l1,
  689. const std::vector<common_adapter_lora_info> & l2) {
  690. if (l1.size() != l2.size()) {
  691. return false;
  692. }
  693. for (size_t i = 0; i < l1.size(); ++i) {
  694. // we don't check lora.path to reduce the time complexity
  695. if (l1[i].scale != l2[i].scale || l1[i].ptr != l2[i].ptr) {
  696. return false;
  697. }
  698. }
  699. return true;
  700. }
  701. // parse lora config from JSON request, returned a copy of lora_base with updated scale
  702. static std::vector<common_adapter_lora_info> parse_lora_request(
  703. const std::vector<common_adapter_lora_info> & lora_base,
  704. const json & data) {
  705. std::vector<common_adapter_lora_info> lora(lora_base);
  706. int max_idx = lora.size();
  707. // clear existing value
  708. for (auto & entry : lora) {
  709. entry.scale = 0.0f;
  710. }
  711. // set value
  712. for (const auto & entry : data) {
  713. int id = json_value(entry, "id", -1);
  714. float scale = json_value(entry, "scale", 0.0f);
  715. if (0 <= id && id < max_idx) {
  716. lora[id].scale = scale;
  717. } else {
  718. throw std::runtime_error("invalid adapter id");
  719. }
  720. }
  721. return lora;
  722. }