utils.hpp 32 KB

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