utils.hpp 32 KB

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