utils.hpp 32 KB

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