utils.hpp 26 KB

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