utils.hpp 31 KB

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