server-common.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  1. #include "common.h"
  2. #include "log.h"
  3. #include "llama.h"
  4. #include "mtmd.h"
  5. #include "mtmd-helper.h"
  6. #include "chat.h"
  7. #include "arg.h" // for common_remote_get_content; TODO: use download.h only
  8. #include "base64.hpp"
  9. #include "server-common.h"
  10. #include <random>
  11. #include <sstream>
  12. json format_error_response(const std::string & message, const enum error_type type) {
  13. std::string type_str;
  14. int code = 500;
  15. switch (type) {
  16. case ERROR_TYPE_INVALID_REQUEST:
  17. type_str = "invalid_request_error";
  18. code = 400;
  19. break;
  20. case ERROR_TYPE_AUTHENTICATION:
  21. type_str = "authentication_error";
  22. code = 401;
  23. break;
  24. case ERROR_TYPE_NOT_FOUND:
  25. type_str = "not_found_error";
  26. code = 404;
  27. break;
  28. case ERROR_TYPE_SERVER:
  29. type_str = "server_error";
  30. code = 500;
  31. break;
  32. case ERROR_TYPE_PERMISSION:
  33. type_str = "permission_error";
  34. code = 403;
  35. break;
  36. case ERROR_TYPE_NOT_SUPPORTED:
  37. type_str = "not_supported_error";
  38. code = 501;
  39. break;
  40. case ERROR_TYPE_UNAVAILABLE:
  41. type_str = "unavailable_error";
  42. code = 503;
  43. break;
  44. case ERROR_TYPE_EXCEED_CONTEXT_SIZE:
  45. type_str = "exceed_context_size_error";
  46. code = 400;
  47. break;
  48. }
  49. return json {
  50. {"code", code},
  51. {"message", message},
  52. {"type", type_str},
  53. };
  54. }
  55. //
  56. // random string / id
  57. //
  58. std::string random_string() {
  59. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  60. std::random_device rd;
  61. std::mt19937 generator(rd());
  62. std::string result(32, ' ');
  63. for (int i = 0; i < 32; ++i) {
  64. result[i] = str[generator() % str.size()];
  65. }
  66. return result;
  67. }
  68. std::string gen_chatcmplid() {
  69. return "chatcmpl-" + random_string();
  70. }
  71. std::string gen_tool_call_id() {
  72. return random_string();
  73. }
  74. //
  75. // lora utils
  76. //
  77. bool lora_all_alora(const std::vector<common_adapter_lora_info> & loras) {
  78. bool found_alora = false;
  79. for (const auto & lora : loras) {
  80. if (lora.scale != 0) {
  81. if (llama_adapter_get_alora_n_invocation_tokens(lora.ptr) == 0) {
  82. return false;
  83. }
  84. found_alora = true;
  85. }
  86. }
  87. return found_alora;
  88. }
  89. bool lora_should_clear_cache(
  90. const std::vector<common_adapter_lora_info> & current,
  91. const std::vector<common_adapter_lora_info> & next) {
  92. // This should always be called after determining that the two sets are
  93. // _not_ equal. This assert is therefore some slightly wasted work and
  94. // should be safe to remove as long as this method is called correctly.
  95. GGML_ASSERT(!are_lora_equal(current, next));
  96. return (
  97. !(lora_get_enabled_ids(current).empty() || lora_all_alora(current)) ||
  98. !lora_all_alora(next));
  99. }
  100. std::vector<common_adapter_lora_info> parse_lora_request(
  101. const std::vector<common_adapter_lora_info> & lora_base,
  102. const json & data) {
  103. std::vector<common_adapter_lora_info> lora(lora_base);
  104. int max_idx = lora.size();
  105. // clear existing value
  106. for (auto & entry : lora) {
  107. entry.scale = 0.0f;
  108. }
  109. // set value
  110. for (const auto & entry : data) {
  111. int id = json_value(entry, "id", -1);
  112. float scale = json_value(entry, "scale", 0.0f);
  113. if (0 <= id && id < max_idx) {
  114. lora[id].scale = scale;
  115. } else {
  116. throw std::runtime_error("invalid adapter id");
  117. }
  118. }
  119. return lora;
  120. }
  121. bool are_lora_equal(
  122. const std::vector<common_adapter_lora_info> & l1,
  123. const std::vector<common_adapter_lora_info> & l2) {
  124. if (l1.size() != l2.size()) {
  125. return false;
  126. }
  127. for (size_t i = 0; i < l1.size(); ++i) {
  128. // we don't check lora.path to reduce the time complexity
  129. if (l1[i].scale != l2[i].scale || l1[i].ptr != l2[i].ptr) {
  130. return false;
  131. }
  132. }
  133. return true;
  134. }
  135. std::vector<size_t> lora_get_enabled_ids(const std::vector<common_adapter_lora_info> & loras) {
  136. std::vector<size_t> enabled_ids;
  137. for (size_t i = 0; i < loras.size(); ++i) {
  138. if (loras[i].scale > 0) {
  139. enabled_ids.push_back(i);
  140. }
  141. }
  142. return enabled_ids;
  143. }
  144. //
  145. // base64 utils (TODO: use the base64::decode from base64.hpp)
  146. //
  147. static const std::string base64_chars =
  148. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  149. "abcdefghijklmnopqrstuvwxyz"
  150. "0123456789+/";
  151. static inline bool is_base64(uint8_t c) {
  152. return (isalnum(c) || (c == '+') || (c == '/'));
  153. }
  154. static inline raw_buffer base64_decode(const std::string & encoded_string) {
  155. int i = 0;
  156. int j = 0;
  157. int in_ = 0;
  158. int in_len = encoded_string.size();
  159. uint8_t char_array_4[4];
  160. uint8_t char_array_3[3];
  161. raw_buffer ret;
  162. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  163. char_array_4[i++] = encoded_string[in_]; in_++;
  164. if (i == 4) {
  165. for (i = 0; i < 4; i++) {
  166. char_array_4[i] = base64_chars.find(char_array_4[i]);
  167. }
  168. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  169. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  170. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  171. for (i = 0; (i < 3); i++) {
  172. ret.push_back(char_array_3[i]);
  173. }
  174. i = 0;
  175. }
  176. }
  177. if (i) {
  178. for (j = i; j < 4; j++) {
  179. char_array_4[j] = 0;
  180. }
  181. for (j = 0; j < 4; j++) {
  182. char_array_4[j] = base64_chars.find(char_array_4[j]);
  183. }
  184. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  185. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  186. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  187. for (j = 0; j < i - 1; j++) {
  188. ret.push_back(char_array_3[j]);
  189. }
  190. }
  191. return ret;
  192. }
  193. //
  194. // server_tokens implementation
  195. //
  196. server_tokens::server_tokens(mtmd::input_chunks & mtmd_chunks, bool has_mtmd) : has_mtmd(has_mtmd) {
  197. for (size_t i = 0; i < mtmd_chunks.size(); ++i) {
  198. push_back(mtmd_chunks[i]);
  199. }
  200. }
  201. server_tokens::server_tokens(const llama_tokens & tokens, bool has_mtmd) : has_mtmd(has_mtmd), tokens(tokens) {
  202. }
  203. llama_pos server_tokens::pos_next() const {
  204. if (!has_mtmd) {
  205. return tokens.size();
  206. }
  207. llama_pos res = tokens.size();
  208. for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ++it) {
  209. const auto & chunk = it->second;
  210. res += mtmd_input_chunk_get_n_pos(chunk.get()) - mtmd_input_chunk_get_n_tokens(chunk.get());
  211. }
  212. return res;
  213. }
  214. std::string server_tokens::str() const {
  215. std::ostringstream oss;
  216. oss << "tokens: ";
  217. for (size_t idx = 0; idx < tokens.size(); ++idx) {
  218. llama_token t = tokens[idx];
  219. oss << "idx:" << idx << " ";
  220. if (t == LLAMA_TOKEN_NULL) {
  221. oss << "<embd> ";
  222. } else {
  223. oss << t << " ";
  224. }
  225. }
  226. oss << "\n";
  227. oss << "image idx: ";
  228. for (const auto & it : map_idx_to_media) {
  229. oss << it.first << ", ";
  230. }
  231. return oss.str();
  232. }
  233. const mtmd::input_chunk_ptr & server_tokens::find_chunk(size_t idx) const {
  234. auto it = map_idx_to_media.find(idx);
  235. if (it != map_idx_to_media.end()) {
  236. return it->second;
  237. }
  238. throw std::runtime_error("Chunk not found");
  239. }
  240. void server_tokens::push_back(llama_token tok) {
  241. if (tok == LLAMA_TOKEN_NULL) {
  242. throw std::runtime_error("Invalid token");
  243. }
  244. tokens.emplace_back(tok);
  245. }
  246. void server_tokens::push_back(const mtmd_input_chunk * chunk) {
  247. auto type = mtmd_input_chunk_get_type(chunk);
  248. if (type == MTMD_INPUT_CHUNK_TYPE_IMAGE || type == MTMD_INPUT_CHUNK_TYPE_AUDIO) {
  249. GGML_ASSERT(has_mtmd);
  250. const size_t n_tokens = mtmd_input_chunk_get_n_tokens(chunk);
  251. size_t start_idx = tokens.size();
  252. for (size_t i = 0; i < n_tokens; ++i) {
  253. tokens.emplace_back(LLAMA_TOKEN_NULL);
  254. }
  255. mtmd::input_chunk_ptr new_chunk(mtmd_input_chunk_copy(chunk));
  256. map_idx_to_media[start_idx] = std::move(new_chunk);
  257. } else if (type == MTMD_INPUT_CHUNK_TYPE_TEXT) {
  258. size_t n_tokens;
  259. const auto * text_tokens = mtmd_input_chunk_get_tokens_text(chunk, &n_tokens);
  260. for (size_t i = 0; i < n_tokens; ++i) {
  261. push_back(text_tokens[i]);
  262. }
  263. } else {
  264. GGML_ABORT("Invalid chunk type");
  265. }
  266. }
  267. void server_tokens::push_back(server_tokens & tokens) {
  268. size_t start_idx = size();
  269. for (size_t i = 0; i < tokens.size(); i++) {
  270. push_back(tokens[i]);
  271. }
  272. if (tokens.has_mtmd) {
  273. // Assert if we are copying MTMD chunks to a server_tokens that does not have mtmd.
  274. // We could also just check, but this will prevent silently dropping MTMD data.
  275. GGML_ASSERT(has_mtmd);
  276. for (auto it = tokens.map_idx_to_media.begin(); it != tokens.map_idx_to_media.end(); ) {
  277. auto * chunk = tokens.map_idx_to_media[it->first].get();
  278. mtmd::input_chunk_ptr new_chunk(mtmd_input_chunk_copy(chunk));
  279. map_idx_to_media[start_idx + it->first] = std::move(new_chunk);
  280. }
  281. }
  282. }
  283. void server_tokens::insert(const llama_tokens & inp_tokens) {
  284. GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
  285. tokens.insert(tokens.end(), inp_tokens.begin(), inp_tokens.end());
  286. }
  287. const llama_tokens & server_tokens::get_text_tokens() const {
  288. GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
  289. return tokens;
  290. }
  291. void server_tokens::set_token(llama_pos pos, llama_token id) {
  292. GGML_ASSERT(!has_mtmd); // only allow this if mtmd is disabled
  293. tokens[pos] = id;
  294. }
  295. void server_tokens::keep_first(size_t n) {
  296. GGML_ASSERT(n <= tokens.size());
  297. if (has_mtmd) {
  298. if (n == tokens.size()) {
  299. return; // nothing to do
  300. }
  301. // we throw an error if we try to remove a token in the middle of an image
  302. // for ex. with input of 5 text tokens and 2 images:
  303. // [0] [1] [2] [3] [4] [img0] [img0] [img0] [img1] [img1]
  304. // n 1 2 3 4 5 6 7 8 9 10
  305. // allowed to resize ^ ^
  306. // disallowed to resize ^ ^ ^
  307. if (n > 0) {
  308. // make sure we never remove tokens in the middle of an image
  309. // note that the case where we keep a full image at the end is allowed:
  310. // tokens[n - 1] == LLAMA_TOKEN_NULL && tokens[n] != LLAMA_TOKEN_NULL
  311. if (tokens[n - 1] == LLAMA_TOKEN_NULL && tokens[n] == LLAMA_TOKEN_NULL) {
  312. find_chunk(n - 1); // will throw an error if the token is not begin-of-chunk
  313. }
  314. }
  315. // remove all image chunks that are not used anymore
  316. for (auto it = map_idx_to_media.begin(); it != map_idx_to_media.end(); ) {
  317. size_t idx = it->first;
  318. if (idx >= n) {
  319. it = map_idx_to_media.erase(it);
  320. } else {
  321. ++it;
  322. }
  323. }
  324. }
  325. tokens.resize(n);
  326. }
  327. std::string server_tokens::detokenize(const llama_context * ctx, bool special) const {
  328. llama_tokens text_tokens;
  329. text_tokens.reserve(tokens.size());
  330. for (const auto & t : tokens) {
  331. if (t != LLAMA_TOKEN_NULL) {
  332. text_tokens.push_back(t);
  333. }
  334. }
  335. return common_detokenize(ctx, text_tokens, special);
  336. }
  337. size_t server_tokens::get_common_prefix(const server_tokens & b) const {
  338. const size_t max_idx = std::min(tokens.size(), b.tokens.size());
  339. if (!has_mtmd) {
  340. for (size_t i = 0; i < max_idx; ++i) {
  341. if (tokens[i] == b.tokens[i]) {
  342. continue;
  343. }
  344. return i;
  345. }
  346. return max_idx;
  347. }
  348. for (size_t i = 0; i < max_idx; ++i) {
  349. const llama_token ai = tokens[i];
  350. const llama_token bi = b.tokens[i];
  351. if (ai == LLAMA_TOKEN_NULL && bi == LLAMA_TOKEN_NULL) {
  352. const auto & a_chunk = find_chunk(i);
  353. const auto & b_chunk = b.find_chunk(i);
  354. GGML_ASSERT(a_chunk && b_chunk);
  355. const std::string id_ai = mtmd_input_chunk_get_id(a_chunk.get());
  356. const std::string id_bi = mtmd_input_chunk_get_id(b_chunk.get());
  357. const size_t n_tok_a = mtmd_input_chunk_get_n_tokens(a_chunk.get());
  358. const size_t n_tok_b = mtmd_input_chunk_get_n_tokens(b_chunk.get());
  359. if (id_ai == id_bi && n_tok_a == n_tok_b) {
  360. GGML_ASSERT(n_tok_a > 0 && "Invalid media chunk"); // should never happen
  361. i += n_tok_a - 1; // will be +1 by the for loop
  362. continue;
  363. }
  364. return i;
  365. }
  366. if (ai == bi) {
  367. continue;
  368. }
  369. return i;
  370. }
  371. return max_idx; // all tokens are equal
  372. }
  373. bool server_tokens::validate(const struct llama_context * ctx) const {
  374. const llama_model * model = llama_get_model(ctx);
  375. const llama_vocab * vocab = llama_model_get_vocab(model);
  376. const int32_t n_vocab = llama_vocab_n_tokens(vocab);
  377. for (size_t i = 0; i < tokens.size(); ++i) {
  378. const auto & t = tokens[i];
  379. if (t == LLAMA_TOKEN_NULL) {
  380. try {
  381. const auto & chunk = find_chunk(i);
  382. size_t n_tokens = mtmd_input_chunk_get_n_tokens(chunk.get());
  383. i += n_tokens - 1; // will be +1 by the for loop
  384. } catch (const std::exception & e) {
  385. return false;
  386. }
  387. } else if (t < 0 || t >= n_vocab) {
  388. return false;
  389. }
  390. }
  391. return true;
  392. }
  393. int32_t server_tokens::process_chunk(
  394. llama_context * ctx,
  395. mtmd_context * mctx,
  396. size_t idx,
  397. llama_pos pos,
  398. int32_t seq_id,
  399. size_t & n_tokens_out) const {
  400. const auto & chunk = find_chunk(idx);
  401. const char * name = mtmd_input_chunk_get_type(chunk.get()) == MTMD_INPUT_CHUNK_TYPE_IMAGE
  402. ? "image" : "audio";
  403. SRV_INF("processing %s...\n", name);
  404. int32_t n_batch = llama_n_batch(ctx);
  405. int64_t t0 = ggml_time_ms();
  406. llama_pos new_n_past; // unused for now
  407. int32_t result = mtmd_helper_eval_chunk_single(mctx, ctx,
  408. chunk.get(),
  409. pos,
  410. seq_id,
  411. n_batch,
  412. true, // logits last
  413. &new_n_past);
  414. SRV_INF("%s processed in %" PRId64 " ms\n", name, ggml_time_ms() - t0);
  415. if (result != 0) {
  416. LOG_ERR("mtmd_helper_eval failed with status %d", result);
  417. n_tokens_out = 0;
  418. return result;
  419. }
  420. n_tokens_out = mtmd_input_chunk_get_n_tokens(chunk.get());
  421. return 0;
  422. }
  423. //
  424. // tokenizer and input processing utils
  425. //
  426. bool json_is_array_of_numbers(const json & data) {
  427. if (data.is_array()) {
  428. for (const auto & e : data) {
  429. if (!e.is_number_integer()) {
  430. return false;
  431. }
  432. }
  433. return true;
  434. }
  435. return false;
  436. }
  437. bool json_is_array_of_mixed_numbers_strings(const json & data) {
  438. bool seen_string = false;
  439. bool seen_number = false;
  440. if (data.is_array()) {
  441. for (const auto & e : data) {
  442. seen_string |= e.is_string();
  443. seen_number |= e.is_number_integer();
  444. if (seen_number && seen_string) {
  445. return true;
  446. }
  447. }
  448. }
  449. return false;
  450. }
  451. bool json_is_array_and_contains_numbers(const json & data) {
  452. if (data.is_array()) {
  453. for (const auto & e : data) {
  454. if (e.is_number_integer()) {
  455. return true;
  456. }
  457. }
  458. return false;
  459. }
  460. return false;
  461. }
  462. json json_get_nested_values(const std::vector<std::string> & paths, const json & js) {
  463. json result = json::object();
  464. for (const std::string & path : paths) {
  465. json current = js;
  466. const auto keys = string_split<std::string>(path, /*separator*/ '/');
  467. bool valid_path = true;
  468. for (const std::string & k : keys) {
  469. if (valid_path && current.is_object() && current.contains(k)) {
  470. current = current[k];
  471. } else {
  472. valid_path = false;
  473. }
  474. }
  475. if (valid_path) {
  476. result[path] = current;
  477. }
  478. }
  479. return result;
  480. }
  481. llama_tokens tokenize_mixed(const llama_vocab * vocab, const json & json_prompt, bool add_special, bool parse_special) {
  482. // If `add_bos` is true, we only add BOS, when json_prompt is a string,
  483. // or the first element of the json_prompt array is a string.
  484. llama_tokens prompt_tokens;
  485. if (json_prompt.is_array()) {
  486. bool first = true;
  487. for (const auto & p : json_prompt) {
  488. if (p.is_string()) {
  489. auto s = p.template get<std::string>();
  490. llama_tokens p;
  491. if (first) {
  492. p = common_tokenize(vocab, s, add_special, parse_special);
  493. first = false;
  494. } else {
  495. p = common_tokenize(vocab, s, false, parse_special);
  496. }
  497. prompt_tokens.insert(prompt_tokens.end(), p.begin(), p.end());
  498. } else {
  499. if (first) {
  500. first = false;
  501. }
  502. prompt_tokens.push_back(p.template get<llama_token>());
  503. }
  504. }
  505. } else {
  506. auto s = json_prompt.template get<std::string>();
  507. prompt_tokens = common_tokenize(vocab, s, add_special, parse_special);
  508. }
  509. return prompt_tokens;
  510. }
  511. size_t validate_utf8(const std::string& text) {
  512. size_t len = text.size();
  513. if (len == 0) return 0;
  514. // Check the last few bytes to see if a multi-byte character is cut off
  515. for (size_t i = 1; i <= 4 && i <= len; ++i) {
  516. unsigned char c = text[len - i];
  517. // Check for start of a multi-byte sequence from the end
  518. if ((c & 0xE0) == 0xC0) {
  519. // 2-byte character start: 110xxxxx
  520. // Needs at least 2 bytes
  521. if (i < 2) return len - i;
  522. } else if ((c & 0xF0) == 0xE0) {
  523. // 3-byte character start: 1110xxxx
  524. // Needs at least 3 bytes
  525. if (i < 3) return len - i;
  526. } else if ((c & 0xF8) == 0xF0) {
  527. // 4-byte character start: 11110xxx
  528. // Needs at least 4 bytes
  529. if (i < 4) return len - i;
  530. }
  531. }
  532. // If no cut-off multi-byte character is found, return full length
  533. return len;
  534. }
  535. // Computes FNV-1a hash of the data
  536. static std::string fnv_hash(const uint8_t * data, size_t len) {
  537. const uint64_t fnv_prime = 0x100000001b3ULL;
  538. uint64_t hash = 0xcbf29ce484222325ULL;
  539. for (size_t i = 0; i < len; ++i) {
  540. hash ^= data[i];
  541. hash *= fnv_prime;
  542. }
  543. return std::to_string(hash);
  544. }
  545. server_tokens process_mtmd_prompt(mtmd_context * mctx, std::string prompt, std::vector<raw_buffer> files) {
  546. mtmd::bitmaps bitmaps;
  547. for (auto & file : files) {
  548. mtmd::bitmap bmp(mtmd_helper_bitmap_init_from_buf(mctx, file.data(), file.size()));
  549. if (!bmp.ptr) {
  550. throw std::runtime_error("Failed to load image or audio file");
  551. }
  552. // calculate bitmap hash (for KV caching)
  553. std::string hash = fnv_hash(bmp.data(), bmp.n_bytes());
  554. bmp.set_id(hash.c_str());
  555. bitmaps.entries.push_back(std::move(bmp));
  556. }
  557. // process prompt
  558. std::vector<server_tokens> inputs;
  559. // multimodal
  560. mtmd_input_text inp_txt = {
  561. prompt.c_str(),
  562. /* add_special */ true,
  563. /* parse_special */ true,
  564. };
  565. mtmd::input_chunks chunks(mtmd_input_chunks_init());
  566. auto bitmaps_c_ptr = bitmaps.c_ptr();
  567. int32_t tokenized = mtmd_tokenize(mctx,
  568. chunks.ptr.get(),
  569. &inp_txt,
  570. bitmaps_c_ptr.data(),
  571. bitmaps_c_ptr.size());
  572. if (tokenized != 0) {
  573. throw std::runtime_error("Failed to tokenize prompt");
  574. }
  575. auto result = server_tokens(chunks, true);
  576. return result;
  577. }
  578. /**
  579. * break the input "prompt" object into multiple prompt if needed, then tokenize them
  580. * use tokenize_input_prompts() if the input could be an array.
  581. * this supports these cases:
  582. * - "prompt": "string"
  583. * - "prompt": [12, 34, 56]
  584. * - "prompt": [12, 34, "string", 56, 78]
  585. * - "prompt": { "prompt_string": "string", "multimodal_data": [ "base64" ] }
  586. */
  587. static server_tokens tokenize_input_subprompt(const llama_vocab * vocab, mtmd_context * mctx, const json & json_prompt, bool add_special, bool parse_special) {
  588. constexpr char JSON_STRING_PROMPT_KEY[] = "prompt_string";
  589. constexpr char JSON_MTMD_DATA_KEY[] = "multimodal_data";
  590. const bool has_mtmd = mctx != nullptr;
  591. if (json_prompt.is_string() || json_is_array_of_mixed_numbers_strings(json_prompt)) {
  592. // string or mixed
  593. llama_tokens tmp = tokenize_mixed(vocab, json_prompt, add_special, parse_special);
  594. return server_tokens(tmp, false);
  595. } else if (json_is_array_of_numbers(json_prompt)) {
  596. // array of tokens
  597. llama_tokens tmp = json_prompt.get<llama_tokens>();
  598. return server_tokens(tmp, false);
  599. } else if (json_prompt.contains(JSON_STRING_PROMPT_KEY)) {
  600. // JSON object with prompt key.
  601. if (json_prompt.contains(JSON_MTMD_DATA_KEY)) {
  602. if (!has_mtmd)
  603. throw std::runtime_error("Multimodal data provided, but model does not support multimodal requests.");
  604. // JSON object with prompt and multimodal key.
  605. std::vector<raw_buffer> files;
  606. for (const auto & entry : json_prompt.at(JSON_MTMD_DATA_KEY)) {
  607. files.push_back(base64_decode(entry));
  608. }
  609. return process_mtmd_prompt(mctx, json_prompt.at(JSON_STRING_PROMPT_KEY), files);
  610. } else {
  611. // Not multimodal, but contains a subobject.
  612. llama_tokens tmp = tokenize_mixed(vocab, json_prompt.at(JSON_STRING_PROMPT_KEY), add_special, parse_special);
  613. return server_tokens(tmp, false);
  614. }
  615. } else {
  616. throw std::runtime_error("\"prompt\" elements must be a string, a list of tokens, a JSON object containing a prompt string, or a list of mixed strings & tokens.");
  617. }
  618. }
  619. std::vector<server_tokens> tokenize_input_prompts(const llama_vocab * vocab, mtmd_context * mctx, const json & json_prompt, bool add_special, bool parse_special) {
  620. std::vector<server_tokens> result;
  621. if (json_prompt.is_array() && !json_is_array_and_contains_numbers(json_prompt)) {
  622. result.reserve(json_prompt.size());
  623. for (const auto & p : json_prompt) {
  624. result.push_back(tokenize_input_subprompt(vocab, mctx, p,add_special, parse_special));
  625. }
  626. } else {
  627. result.push_back(tokenize_input_subprompt(vocab, mctx, json_prompt, add_special, parse_special));
  628. }
  629. if (result.empty()) {
  630. throw std::runtime_error("\"prompt\" must not be empty");
  631. }
  632. return result;
  633. }
  634. //
  635. // OAI utils
  636. //
  637. // used by /completions endpoint
  638. json oaicompat_completion_params_parse(const json & body) {
  639. json llama_params;
  640. if (!body.contains("prompt")) {
  641. throw std::runtime_error("\"prompt\" is required");
  642. }
  643. // Handle "stop" field
  644. if (body.contains("stop") && body.at("stop").is_string()) {
  645. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  646. } else {
  647. llama_params["stop"] = json_value(body, "stop", json::array());
  648. }
  649. // Handle "n" field
  650. int n_choices = json_value(body, "n", 1);
  651. if (n_choices != 1) {
  652. throw std::runtime_error("Only one completion choice is allowed");
  653. }
  654. // Handle "echo" field
  655. if (json_value(body, "echo", false)) {
  656. throw std::runtime_error("Only no echo is supported");
  657. }
  658. // Params supported by OAI but unsupported by llama.cpp
  659. static const std::vector<std::string> unsupported_params { "best_of", "suffix" };
  660. for (const auto & param : unsupported_params) {
  661. if (body.contains(param)) {
  662. throw std::runtime_error("Unsupported param: " + param);
  663. }
  664. }
  665. // Copy remaining properties to llama_params
  666. for (const auto & item : body.items()) {
  667. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  668. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  669. llama_params[item.key()] = item.value();
  670. }
  671. }
  672. return llama_params;
  673. }
  674. // used by /chat/completions endpoint
  675. json oaicompat_chat_params_parse(
  676. json & body, /* openai api json semantics */
  677. const oaicompat_parser_options & opt,
  678. std::vector<raw_buffer> & out_files)
  679. {
  680. json llama_params;
  681. auto tools = json_value(body, "tools", json());
  682. auto has_tools = tools.is_array() && !tools.empty();
  683. auto stream = json_value(body, "stream", false);
  684. auto tool_choice = json_value(body, "tool_choice", std::string("auto"));
  685. if (!opt.use_jinja) {
  686. if (has_tools) {
  687. throw std::runtime_error("tools param requires --jinja flag");
  688. }
  689. if (tool_choice != "auto") {
  690. throw std::runtime_error("tool_choice param requires --jinja flag");
  691. }
  692. }
  693. // Handle "stop" field
  694. if (body.contains("stop") && body.at("stop").is_string()) {
  695. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  696. } else {
  697. llama_params["stop"] = json_value(body, "stop", json::array());
  698. }
  699. auto json_schema = json_value(body, "json_schema", json());
  700. auto grammar = json_value(body, "grammar", std::string());
  701. if (!json_schema.is_null() && !grammar.empty()) {
  702. throw std::runtime_error("Cannot use both json_schema and grammar");
  703. }
  704. // Handle "response_format" field
  705. if (body.contains("response_format")) {
  706. json response_format = json_value(body, "response_format", json::object());
  707. std::string response_type = json_value(response_format, "type", std::string());
  708. if (response_type == "json_object") {
  709. json_schema = json_value(response_format, "schema", json::object());
  710. } else if (response_type == "json_schema") {
  711. auto schema_wrapper = json_value(response_format, "json_schema", json::object());
  712. json_schema = json_value(schema_wrapper, "schema", json::object());
  713. } else if (!response_type.empty() && response_type != "text") {
  714. throw std::runtime_error("response_format type must be one of \"text\" or \"json_object\", but got: " + response_type);
  715. }
  716. }
  717. // get input files
  718. if (!body.contains("messages")) {
  719. throw std::runtime_error("'messages' is required");
  720. }
  721. json & messages = body.at("messages");
  722. if (!messages.is_array()) {
  723. throw std::runtime_error("Expected 'messages' to be an array");
  724. }
  725. for (auto & msg : messages) {
  726. std::string role = json_value(msg, "role", std::string());
  727. if (role != "assistant" && !msg.contains("content")) {
  728. throw std::runtime_error("All non-assistant messages must contain 'content'");
  729. }
  730. if (role == "assistant") {
  731. if (!msg.contains("content") && !msg.contains("tool_calls")) {
  732. throw std::runtime_error("Assistant message must contain either 'content' or 'tool_calls'!");
  733. }
  734. if (!msg.contains("content")) {
  735. continue; // avoid errors with no content
  736. }
  737. }
  738. json & content = msg.at("content");
  739. if (content.is_string() || content.is_null()) {
  740. continue;
  741. }
  742. if (!content.is_array()) {
  743. throw std::runtime_error("Expected 'content' to be a string or an array");
  744. }
  745. for (auto & p : content) {
  746. std::string type = json_value(p, "type", std::string());
  747. if (type == "image_url") {
  748. if (!opt.allow_image) {
  749. throw std::runtime_error("image input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
  750. }
  751. json image_url = json_value(p, "image_url", json::object());
  752. std::string url = json_value(image_url, "url", std::string());
  753. if (string_starts_with(url, "http")) {
  754. // download remote image
  755. // TODO @ngxson : maybe make these params configurable
  756. common_remote_params params;
  757. params.headers.push_back("User-Agent: llama.cpp/" + build_info);
  758. params.max_size = 1024 * 1024 * 10; // 10MB
  759. params.timeout = 10; // seconds
  760. SRV_INF("downloading image from '%s'\n", url.c_str());
  761. auto res = common_remote_get_content(url, params);
  762. if (200 <= res.first && res.first < 300) {
  763. SRV_INF("downloaded %ld bytes\n", res.second.size());
  764. raw_buffer data;
  765. data.insert(data.end(), res.second.begin(), res.second.end());
  766. out_files.push_back(data);
  767. } else {
  768. throw std::runtime_error("Failed to download image");
  769. }
  770. } else {
  771. // try to decode base64 image
  772. std::vector<std::string> parts = string_split<std::string>(url, /*separator*/ ',');
  773. if (parts.size() != 2) {
  774. throw std::runtime_error("Invalid image_url.url value");
  775. } else if (!string_starts_with(parts[0], "data:image/")) {
  776. throw std::runtime_error("Invalid image_url.url format: " + parts[0]);
  777. } else if (!string_ends_with(parts[0], "base64")) {
  778. throw std::runtime_error("image_url.url must be base64 encoded");
  779. } else {
  780. auto base64_data = parts[1];
  781. auto decoded_data = base64_decode(base64_data);
  782. out_files.push_back(decoded_data);
  783. }
  784. }
  785. // replace this chunk with a marker
  786. p["type"] = "text";
  787. p["text"] = mtmd_default_marker();
  788. p.erase("image_url");
  789. } else if (type == "input_audio") {
  790. if (!opt.allow_audio) {
  791. throw std::runtime_error("audio input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
  792. }
  793. json input_audio = json_value(p, "input_audio", json::object());
  794. std::string data = json_value(input_audio, "data", std::string());
  795. std::string format = json_value(input_audio, "format", std::string());
  796. // while we also support flac, we don't allow it here so we matches the OAI spec
  797. if (format != "wav" && format != "mp3") {
  798. throw std::runtime_error("input_audio.format must be either 'wav' or 'mp3'");
  799. }
  800. auto decoded_data = base64_decode(data); // expected to be base64 encoded
  801. out_files.push_back(decoded_data);
  802. // replace this chunk with a marker
  803. p["type"] = "text";
  804. p["text"] = mtmd_default_marker();
  805. p.erase("input_audio");
  806. } else if (type != "text") {
  807. throw std::runtime_error("unsupported content[].type");
  808. }
  809. }
  810. }
  811. common_chat_templates_inputs inputs;
  812. inputs.messages = common_chat_msgs_parse_oaicompat(messages);
  813. inputs.tools = common_chat_tools_parse_oaicompat(tools);
  814. inputs.tool_choice = common_chat_tool_choice_parse_oaicompat(tool_choice);
  815. inputs.json_schema = json_schema.is_null() ? "" : json_schema.dump();
  816. inputs.grammar = grammar;
  817. inputs.use_jinja = opt.use_jinja;
  818. inputs.parallel_tool_calls = json_value(body, "parallel_tool_calls", false);
  819. inputs.add_generation_prompt = json_value(body, "add_generation_prompt", true);
  820. inputs.reasoning_format = opt.reasoning_format;
  821. inputs.enable_thinking = opt.enable_thinking;
  822. if (!inputs.tools.empty() && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
  823. if (body.contains("grammar")) {
  824. throw std::runtime_error("Cannot use custom grammar constraints with tools.");
  825. }
  826. llama_params["parse_tool_calls"] = true;
  827. }
  828. // merge the template args provided from command line with the args provided in the user request
  829. auto chat_template_kwargs_object = json_value(body, "chat_template_kwargs", json::object());
  830. inputs.chat_template_kwargs = opt.chat_template_kwargs;
  831. for (const auto & item : chat_template_kwargs_object.items()) {
  832. inputs.chat_template_kwargs[item.key()] = item.value().dump();
  833. }
  834. // parse the "enable_thinking" kwarg to override the default value
  835. auto enable_thinking_kwarg = json_value(inputs.chat_template_kwargs, "enable_thinking", std::string(""));
  836. if (enable_thinking_kwarg == "true") {
  837. inputs.enable_thinking = true;
  838. } else if (enable_thinking_kwarg == "false") {
  839. inputs.enable_thinking = false;
  840. } else if (!enable_thinking_kwarg.empty() && enable_thinking_kwarg[0] == '"') {
  841. throw std::runtime_error("invalid type for \"enable_thinking\" (expected boolean, got string)");
  842. }
  843. // if the assistant message appears at the end of list, we do not add end-of-turn token
  844. // for ex. this can be useful to modify the reasoning process in reasoning models
  845. bool prefill_assistant_message = !inputs.messages.empty() && inputs.messages.back().role == "assistant" && opt.prefill_assistant;
  846. common_chat_msg last_message;
  847. if (prefill_assistant_message) {
  848. last_message = inputs.messages.back();
  849. inputs.messages.pop_back();
  850. /* sanity check, max one assistant message at the end of the list */
  851. if (!inputs.messages.empty() && inputs.messages.back().role == "assistant"){
  852. throw std::runtime_error("Cannot have 2 or more assistant messages at the end of the list.");
  853. }
  854. /* TODO: test this properly */
  855. inputs.reasoning_format = COMMON_REASONING_FORMAT_NONE;
  856. if ( inputs.enable_thinking ) {
  857. throw std::runtime_error("Assistant response prefill is incompatible with enable_thinking.");
  858. }
  859. inputs.add_generation_prompt = true;
  860. }
  861. // Apply chat template to the list of messages
  862. auto chat_params = common_chat_templates_apply(opt.tmpls, inputs);
  863. /* Append assistant prefilled message */
  864. if (prefill_assistant_message) {
  865. if (!last_message.content_parts.empty()) {
  866. for (auto & p : last_message.content_parts) {
  867. chat_params.prompt += p.text;
  868. }
  869. } else {
  870. chat_params.prompt += last_message.content;
  871. }
  872. }
  873. llama_params["chat_format"] = static_cast<int>(chat_params.format);
  874. llama_params["prompt"] = chat_params.prompt;
  875. if (!chat_params.grammar.empty()) {
  876. llama_params["grammar"] = chat_params.grammar;
  877. }
  878. llama_params["grammar_lazy"] = chat_params.grammar_lazy;
  879. auto grammar_triggers = json::array();
  880. for (const auto & trigger : chat_params.grammar_triggers) {
  881. server_grammar_trigger ct(trigger);
  882. grammar_triggers.push_back(ct.to_json());
  883. }
  884. llama_params["grammar_triggers"] = grammar_triggers;
  885. llama_params["preserved_tokens"] = chat_params.preserved_tokens;
  886. llama_params["thinking_forced_open"] = chat_params.thinking_forced_open;
  887. for (const auto & stop : chat_params.additional_stops) {
  888. llama_params["stop"].push_back(stop);
  889. }
  890. // Handle "n" field
  891. int n_choices = json_value(body, "n", 1);
  892. if (n_choices != 1) {
  893. throw std::runtime_error("Only one completion choice is allowed");
  894. }
  895. // Handle "logprobs" field
  896. // 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
  897. if (json_value(body, "logprobs", false)) {
  898. if (has_tools && stream) {
  899. throw std::runtime_error("logprobs is not supported with tools + stream");
  900. }
  901. llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
  902. } else if (body.contains("top_logprobs") && !body.at("top_logprobs").is_null()) {
  903. throw std::runtime_error("top_logprobs requires logprobs to be set to true");
  904. }
  905. // Copy remaining properties to llama_params
  906. // This allows user to use llama.cpp-specific params like "mirostat", ... via OAI endpoint.
  907. // See "launch_slot_with_task()" for a complete list of params supported by llama.cpp
  908. for (const auto & item : body.items()) {
  909. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  910. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  911. llama_params[item.key()] = item.value();
  912. }
  913. }
  914. return llama_params;
  915. }
  916. json format_embeddings_response_oaicompat(const json & request, const json & embeddings, bool use_base64) {
  917. json data = json::array();
  918. int32_t n_tokens = 0;
  919. int i = 0;
  920. for (const auto & elem : embeddings) {
  921. json embedding_obj;
  922. if (use_base64) {
  923. const auto& vec = json_value(elem, "embedding", json::array()).get<std::vector<float>>();
  924. const char* data_ptr = reinterpret_cast<const char*>(vec.data());
  925. size_t data_size = vec.size() * sizeof(float);
  926. embedding_obj = {
  927. {"embedding", base64::encode(data_ptr, data_size)},
  928. {"index", i++},
  929. {"object", "embedding"},
  930. {"encoding_format", "base64"}
  931. };
  932. } else {
  933. embedding_obj = {
  934. {"embedding", json_value(elem, "embedding", json::array())},
  935. {"index", i++},
  936. {"object", "embedding"}
  937. };
  938. }
  939. data.push_back(embedding_obj);
  940. n_tokens += json_value(elem, "tokens_evaluated", 0);
  941. }
  942. json res = json {
  943. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  944. {"object", "list"},
  945. {"usage", json {
  946. {"prompt_tokens", n_tokens},
  947. {"total_tokens", n_tokens}
  948. }},
  949. {"data", data}
  950. };
  951. return res;
  952. }
  953. json format_response_rerank(
  954. const json & request,
  955. const json & ranks,
  956. bool is_tei_format,
  957. std::vector<std::string> & texts,
  958. int top_n) {
  959. int32_t n_tokens = 0;
  960. bool return_text = is_tei_format && json_value(request, "return_text", false);
  961. std::vector<json> elements; // Temporary vector to hold unsorted elements
  962. std::string score_label = is_tei_format ? "score" : "relevance_score";
  963. for (const auto & rank : ranks) {
  964. int index = json_value(rank, "index", 0);
  965. json elem = json{
  966. {"index", index},
  967. {score_label, json_value(rank, "score", 0.0)},
  968. };
  969. n_tokens += json_value(rank, "tokens_evaluated", 0);
  970. if (return_text) {
  971. elem["text"] = std::move(texts[index]);
  972. }
  973. elements.push_back(elem);
  974. }
  975. std::sort(elements.begin(), elements.end(), [score_label](const json& a, const json& b) {
  976. return json_value(a, score_label, 0.0) > json_value(b, score_label, 0.0);
  977. });
  978. elements.resize(std::min(top_n, (int)elements.size()));
  979. json results = elements;
  980. if (is_tei_format) return results;
  981. json res = json{
  982. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  983. {"object", "list"},
  984. {"usage", json{
  985. {"prompt_tokens", n_tokens},
  986. {"total_tokens", n_tokens}
  987. }},
  988. {"results", results}
  989. };
  990. return res;
  991. }
  992. //
  993. // other utils
  994. //
  995. std::vector<llama_token_data> get_token_probabilities(llama_context * ctx, int idx) {
  996. std::vector<llama_token_data> cur;
  997. const auto * logits = llama_get_logits_ith(ctx, idx);
  998. const llama_model * model = llama_get_model(ctx);
  999. const llama_vocab * vocab = llama_model_get_vocab(model);
  1000. const int n_vocab = llama_vocab_n_tokens(vocab);
  1001. cur.resize(n_vocab);
  1002. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  1003. cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
  1004. }
  1005. // sort tokens by logits
  1006. std::sort(cur.begin(), cur.end(), [](const llama_token_data & a, const llama_token_data & b) {
  1007. return a.logit > b.logit;
  1008. });
  1009. // apply softmax
  1010. float max_l = cur[0].logit;
  1011. float cum_sum = 0.0f;
  1012. for (size_t i = 0; i < cur.size(); ++i) {
  1013. float p = expf(cur[i].logit - max_l);
  1014. cur[i].p = p;
  1015. cum_sum += p;
  1016. }
  1017. for (size_t i = 0; i < cur.size(); ++i) {
  1018. cur[i].p /= cum_sum;
  1019. }
  1020. return cur;
  1021. }
  1022. std::string safe_json_to_str(const json & data) {
  1023. return data.dump(-1, ' ', false, json::error_handler_t::replace);
  1024. }
  1025. // TODO: reuse llama_detokenize
  1026. template <class Iter>
  1027. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  1028. std::string ret;
  1029. for (; begin != end; ++begin) {
  1030. ret += common_token_to_piece(ctx, *begin);
  1031. }
  1032. return ret;
  1033. }
  1034. std::string tokens_to_str(llama_context * ctx, const llama_tokens & tokens) {
  1035. return tokens_to_str(ctx, tokens.begin(), tokens.end());
  1036. }
  1037. // format incomplete utf-8 multibyte character for output
  1038. std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  1039. std::string out = token == LLAMA_TOKEN_NULL ? "" : common_token_to_piece(ctx, token);
  1040. // if the size is 1 and first bit is 1, meaning it's a partial character
  1041. // (size > 1 meaning it's already a known token)
  1042. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  1043. std::stringstream ss;
  1044. ss << std::hex << (out[0] & 0xff);
  1045. std::string res(ss.str());
  1046. out = "byte: \\x" + res;
  1047. }
  1048. return out;
  1049. }
  1050. // format server-sent event (SSE), return the formatted string to send
  1051. // note: if data is a json array, it will be sent as multiple events, one per item
  1052. std::string format_sse(const json & data) {
  1053. std::ostringstream ss;
  1054. auto send_single = [&ss](const json & data) {
  1055. ss << "data: " <<
  1056. safe_json_to_str(data) <<
  1057. "\n\n"; // required by RFC 8895 - A message is terminated by a blank line (two line terminators in a row).
  1058. };
  1059. if (data.is_array()) {
  1060. for (const auto & item : data) {
  1061. send_single(item);
  1062. }
  1063. } else {
  1064. send_single(data);
  1065. }
  1066. return ss.str();
  1067. }
  1068. bool is_valid_utf8(const std::string & str) {
  1069. const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data());
  1070. const unsigned char* end = bytes + str.length();
  1071. while (bytes < end) {
  1072. if (*bytes <= 0x7F) {
  1073. // 1-byte sequence (0xxxxxxx)
  1074. bytes++;
  1075. } else if ((*bytes & 0xE0) == 0xC0) {
  1076. // 2-byte sequence (110xxxxx 10xxxxxx)
  1077. if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80)
  1078. return false;
  1079. bytes += 2;
  1080. } else if ((*bytes & 0xF0) == 0xE0) {
  1081. // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx)
  1082. if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80)
  1083. return false;
  1084. bytes += 3;
  1085. } else if ((*bytes & 0xF8) == 0xF0) {
  1086. // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
  1087. if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 ||
  1088. (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80)
  1089. return false;
  1090. bytes += 4;
  1091. } else {
  1092. // Invalid UTF-8 lead byte
  1093. return false;
  1094. }
  1095. }
  1096. return true;
  1097. }
  1098. llama_tokens format_prompt_infill(
  1099. const llama_vocab * vocab,
  1100. const json & input_prefix,
  1101. const json & input_suffix,
  1102. const json & input_extra,
  1103. const int n_batch,
  1104. const int n_predict,
  1105. const int n_ctx,
  1106. const bool spm_infill,
  1107. const llama_tokens & tokens_prompt
  1108. ) {
  1109. // TODO: optimize this block by reducing memory allocations and movement
  1110. // use FIM repo-level pattern:
  1111. // ref: https://arxiv.org/pdf/2409.12186
  1112. //
  1113. // [FIM_REP]myproject
  1114. // [FIM_SEP]filename0
  1115. // extra chunk 0
  1116. // [FIM_SEP]filename1
  1117. // extra chunk 1
  1118. // ...
  1119. // [FIM_SEP]filename
  1120. // [FIM_PRE]prefix[FIM_SUF]suffix[FIM_MID]prompt
  1121. //
  1122. llama_tokens extra_tokens;
  1123. extra_tokens.reserve(n_ctx);
  1124. auto tokens_prefix = tokenize_mixed(vocab, input_prefix, false, false);
  1125. auto tokens_suffix = tokenize_mixed(vocab, input_suffix, false, false);
  1126. if (llama_vocab_fim_rep(vocab) != LLAMA_TOKEN_NULL) {
  1127. // TODO: make project name an input
  1128. static const auto k_fim_repo = common_tokenize(vocab, "myproject\n", false, false);
  1129. extra_tokens.push_back(llama_vocab_fim_rep(vocab));
  1130. extra_tokens.insert(extra_tokens.end(), k_fim_repo.begin(), k_fim_repo.end());
  1131. }
  1132. for (const auto & chunk : input_extra) {
  1133. // { "text": string, "filename": string }
  1134. const std::string text = json_value(chunk, "text", std::string());
  1135. const std::string filename = json_value(chunk, "filename", std::string("tmp"));
  1136. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  1137. const auto k_fim_file = common_tokenize(vocab, filename + "\n", false, false);
  1138. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  1139. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  1140. } else {
  1141. // chunk separator in binary form to avoid confusing the AI
  1142. 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};
  1143. static const auto k_chunk_prefix_tokens = common_tokenize(vocab, k_chunk_prefix_str, false, false);
  1144. extra_tokens.insert(extra_tokens.end(), k_chunk_prefix_tokens.begin(), k_chunk_prefix_tokens.end());
  1145. }
  1146. const auto chunk_tokens = common_tokenize(vocab, text, false, false);
  1147. extra_tokens.insert(extra_tokens.end(), chunk_tokens.begin(), chunk_tokens.end());
  1148. }
  1149. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  1150. // TODO: current filename
  1151. static const auto k_fim_file = common_tokenize(vocab, "filename\n", false, false);
  1152. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  1153. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  1154. }
  1155. // for now pick FIM context to fit in a batch (ratio prefix:suffix = 3:1, TODO: configurable?)
  1156. const int n_prefix_take = std::min<int>(tokens_prefix.size(), 3*(n_batch/4));
  1157. const int n_suffix_take = std::min<int>(tokens_suffix.size(), std::max<int>(0, (n_batch/4) - (2 + tokens_prompt.size())));
  1158. 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));
  1159. // fill the rest of the context with extra chunks
  1160. const int n_extra_take = std::min<int>(std::max<int>(0, n_ctx - (n_batch) - 2*n_predict), extra_tokens.size());
  1161. tokens_prefix.erase(tokens_prefix.begin(), tokens_prefix.begin() + tokens_prefix.size() - n_prefix_take);
  1162. tokens_suffix.resize(n_suffix_take);
  1163. tokens_prefix.insert(tokens_prefix.begin(), llama_vocab_fim_pre(vocab));
  1164. tokens_prefix.insert(tokens_prefix.end(), tokens_prompt.begin(), tokens_prompt.end());
  1165. tokens_suffix.insert(tokens_suffix.begin(), llama_vocab_fim_suf(vocab));
  1166. auto embd_inp = spm_infill ? tokens_suffix : tokens_prefix;
  1167. auto embd_end = spm_infill ? tokens_prefix : tokens_suffix;
  1168. if (llama_vocab_get_add_bos(vocab)) {
  1169. embd_inp.insert(embd_inp.begin(), llama_vocab_bos(vocab));
  1170. }
  1171. SRV_DBG("extra: n_ctx = %d, n_extra_take = %d, n_extra = %d\n", n_ctx, n_extra_take, (int) extra_tokens.size());
  1172. // put the extra context before the FIM prefix
  1173. embd_inp.insert(embd_inp.begin(), extra_tokens.end() - n_extra_take, extra_tokens.end());
  1174. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  1175. embd_inp.push_back(llama_vocab_fim_mid(vocab));
  1176. return embd_inp;
  1177. }
  1178. server_tokens format_prompt_rerank(
  1179. const struct llama_model * model,
  1180. const struct llama_vocab * vocab,
  1181. mtmd_context * mctx,
  1182. const std::string & query,
  1183. const std::string & doc) {
  1184. server_tokens result = {};
  1185. const char * rerank_prompt = llama_model_chat_template(model, "rerank");
  1186. if (rerank_prompt != nullptr) {
  1187. std::string prompt = rerank_prompt;
  1188. string_replace_all(prompt, "{query}" , query);
  1189. string_replace_all(prompt, "{document}", doc );
  1190. server_tokens tokens = tokenize_input_subprompt(vocab, mctx, prompt, false, true);
  1191. result.push_back(tokens);
  1192. } else {
  1193. // Get EOS token - use SEP token as fallback if EOS is not available
  1194. server_tokens query_tokens = tokenize_input_subprompt(vocab, mctx, query, false, false);
  1195. server_tokens doc_tokens = tokenize_input_subprompt(vocab, mctx, doc, false, false);
  1196. llama_token eos_token = llama_vocab_eos(vocab);
  1197. if (eos_token == LLAMA_TOKEN_NULL) {
  1198. eos_token = llama_vocab_sep(vocab);
  1199. }
  1200. if (llama_vocab_get_add_bos(vocab)) {
  1201. result.push_back(llama_vocab_bos(vocab));
  1202. }
  1203. result.push_back(query_tokens);
  1204. if (llama_vocab_get_add_eos(vocab)) {
  1205. result.push_back(eos_token);
  1206. }
  1207. if (llama_vocab_get_add_sep(vocab)) {
  1208. result.push_back(llama_vocab_sep(vocab));
  1209. }
  1210. result.push_back(doc_tokens);
  1211. if (llama_vocab_get_add_eos(vocab)) {
  1212. result.push_back(eos_token);
  1213. }
  1214. }
  1215. return result;
  1216. }