server-common.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  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 convert_anthropic_to_oai(const json & body) {
  917. json oai_body;
  918. // Convert system prompt
  919. json oai_messages = json::array();
  920. auto system_param = json_value(body, "system", json());
  921. if (!system_param.is_null()) {
  922. std::string system_content;
  923. if (system_param.is_string()) {
  924. system_content = system_param.get<std::string>();
  925. } else if (system_param.is_array()) {
  926. for (const auto & block : system_param) {
  927. if (json_value(block, "type", std::string()) == "text") {
  928. system_content += json_value(block, "text", std::string());
  929. }
  930. }
  931. }
  932. oai_messages.push_back({
  933. {"role", "system"},
  934. {"content", system_content}
  935. });
  936. }
  937. // Convert messages
  938. if (!body.contains("messages")) {
  939. throw std::runtime_error("'messages' is required");
  940. }
  941. const json & messages = body.at("messages");
  942. if (messages.is_array()) {
  943. for (const auto & msg : messages) {
  944. std::string role = json_value(msg, "role", std::string());
  945. if (!msg.contains("content")) {
  946. if (role == "assistant") {
  947. continue;
  948. }
  949. oai_messages.push_back(msg);
  950. continue;
  951. }
  952. const json & content = msg.at("content");
  953. if (content.is_string()) {
  954. oai_messages.push_back(msg);
  955. continue;
  956. }
  957. if (!content.is_array()) {
  958. oai_messages.push_back(msg);
  959. continue;
  960. }
  961. json tool_calls = json::array();
  962. json converted_content = json::array();
  963. json tool_results = json::array();
  964. bool has_tool_calls = false;
  965. for (const auto & block : content) {
  966. std::string type = json_value(block, "type", std::string());
  967. if (type == "text") {
  968. converted_content.push_back(block);
  969. } else if (type == "image") {
  970. json source = json_value(block, "source", json::object());
  971. std::string source_type = json_value(source, "type", std::string());
  972. if (source_type == "base64") {
  973. std::string media_type = json_value(source, "media_type", std::string("image/jpeg"));
  974. std::string data = json_value(source, "data", std::string());
  975. std::ostringstream ss;
  976. ss << "data:" << media_type << ";base64," << data;
  977. converted_content.push_back({
  978. {"type", "image_url"},
  979. {"image_url", {
  980. {"url", ss.str()}
  981. }}
  982. });
  983. } else if (source_type == "url") {
  984. std::string url = json_value(source, "url", std::string());
  985. converted_content.push_back({
  986. {"type", "image_url"},
  987. {"image_url", {
  988. {"url", url}
  989. }}
  990. });
  991. }
  992. } else if (type == "tool_use") {
  993. tool_calls.push_back({
  994. {"id", json_value(block, "id", std::string())},
  995. {"type", "function"},
  996. {"function", {
  997. {"name", json_value(block, "name", std::string())},
  998. {"arguments", json_value(block, "input", json::object()).dump()}
  999. }}
  1000. });
  1001. has_tool_calls = true;
  1002. } else if (type == "tool_result") {
  1003. std::string tool_use_id = json_value(block, "tool_use_id", std::string());
  1004. auto result_content = json_value(block, "content", json());
  1005. std::string result_text;
  1006. if (result_content.is_string()) {
  1007. result_text = result_content.get<std::string>();
  1008. } else if (result_content.is_array()) {
  1009. for (const auto & c : result_content) {
  1010. if (json_value(c, "type", std::string()) == "text") {
  1011. result_text += json_value(c, "text", std::string());
  1012. }
  1013. }
  1014. }
  1015. tool_results.push_back({
  1016. {"role", "tool"},
  1017. {"tool_call_id", tool_use_id},
  1018. {"content", result_text}
  1019. });
  1020. }
  1021. }
  1022. if (!converted_content.empty() || has_tool_calls) {
  1023. json new_msg = {{"role", role}};
  1024. if (!converted_content.empty()) {
  1025. new_msg["content"] = converted_content;
  1026. } else if (has_tool_calls) {
  1027. new_msg["content"] = "";
  1028. }
  1029. if (!tool_calls.empty()) {
  1030. new_msg["tool_calls"] = tool_calls;
  1031. }
  1032. oai_messages.push_back(new_msg);
  1033. }
  1034. for (const auto & tool_msg : tool_results) {
  1035. oai_messages.push_back(tool_msg);
  1036. }
  1037. }
  1038. }
  1039. oai_body["messages"] = oai_messages;
  1040. // Convert tools
  1041. if (body.contains("tools")) {
  1042. const json & tools = body.at("tools");
  1043. if (tools.is_array()) {
  1044. json oai_tools = json::array();
  1045. for (const auto & tool : tools) {
  1046. oai_tools.push_back({
  1047. {"type", "function"},
  1048. {"function", {
  1049. {"name", json_value(tool, "name", std::string())},
  1050. {"description", json_value(tool, "description", std::string())},
  1051. {"parameters", tool.contains("input_schema") ? tool.at("input_schema") : json::object()}
  1052. }}
  1053. });
  1054. }
  1055. oai_body["tools"] = oai_tools;
  1056. }
  1057. }
  1058. // Convert tool_choice
  1059. if (body.contains("tool_choice")) {
  1060. const json & tc = body.at("tool_choice");
  1061. if (tc.is_object()) {
  1062. std::string type = json_value(tc, "type", std::string());
  1063. if (type == "auto") {
  1064. oai_body["tool_choice"] = "auto";
  1065. } else if (type == "any" || type == "tool") {
  1066. oai_body["tool_choice"] = "required";
  1067. }
  1068. }
  1069. }
  1070. // Convert stop_sequences to stop
  1071. if (body.contains("stop_sequences")) {
  1072. oai_body["stop"] = body.at("stop_sequences");
  1073. }
  1074. // Handle max_tokens (required in Anthropic, but we're permissive)
  1075. if (body.contains("max_tokens")) {
  1076. oai_body["max_tokens"] = body.at("max_tokens");
  1077. } else {
  1078. oai_body["max_tokens"] = 4096;
  1079. }
  1080. // Pass through common params
  1081. for (const auto & key : {"temperature", "top_p", "top_k", "stream"}) {
  1082. if (body.contains(key)) {
  1083. oai_body[key] = body.at(key);
  1084. }
  1085. }
  1086. // Handle Anthropic-specific thinking param
  1087. if (body.contains("thinking")) {
  1088. json thinking = json_value(body, "thinking", json::object());
  1089. std::string thinking_type = json_value(thinking, "type", std::string());
  1090. if (thinking_type == "enabled") {
  1091. int budget_tokens = json_value(thinking, "budget_tokens", 10000);
  1092. oai_body["thinking_budget_tokens"] = budget_tokens;
  1093. }
  1094. }
  1095. // Handle Anthropic-specific metadata param
  1096. if (body.contains("metadata")) {
  1097. json metadata = json_value(body, "metadata", json::object());
  1098. std::string user_id = json_value(metadata, "user_id", std::string());
  1099. if (!user_id.empty()) {
  1100. oai_body["__metadata_user_id"] = user_id;
  1101. }
  1102. }
  1103. return oai_body;
  1104. }
  1105. json format_embeddings_response_oaicompat(const json & request, const json & embeddings, bool use_base64) {
  1106. json data = json::array();
  1107. int32_t n_tokens = 0;
  1108. int i = 0;
  1109. for (const auto & elem : embeddings) {
  1110. json embedding_obj;
  1111. if (use_base64) {
  1112. const auto& vec = json_value(elem, "embedding", json::array()).get<std::vector<float>>();
  1113. const char* data_ptr = reinterpret_cast<const char*>(vec.data());
  1114. size_t data_size = vec.size() * sizeof(float);
  1115. embedding_obj = {
  1116. {"embedding", base64::encode(data_ptr, data_size)},
  1117. {"index", i++},
  1118. {"object", "embedding"},
  1119. {"encoding_format", "base64"}
  1120. };
  1121. } else {
  1122. embedding_obj = {
  1123. {"embedding", json_value(elem, "embedding", json::array())},
  1124. {"index", i++},
  1125. {"object", "embedding"}
  1126. };
  1127. }
  1128. data.push_back(embedding_obj);
  1129. n_tokens += json_value(elem, "tokens_evaluated", 0);
  1130. }
  1131. json res = json {
  1132. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  1133. {"object", "list"},
  1134. {"usage", json {
  1135. {"prompt_tokens", n_tokens},
  1136. {"total_tokens", n_tokens}
  1137. }},
  1138. {"data", data}
  1139. };
  1140. return res;
  1141. }
  1142. json format_response_rerank(
  1143. const json & request,
  1144. const json & ranks,
  1145. bool is_tei_format,
  1146. std::vector<std::string> & texts,
  1147. int top_n) {
  1148. int32_t n_tokens = 0;
  1149. bool return_text = is_tei_format && json_value(request, "return_text", false);
  1150. std::vector<json> elements; // Temporary vector to hold unsorted elements
  1151. std::string score_label = is_tei_format ? "score" : "relevance_score";
  1152. for (const auto & rank : ranks) {
  1153. int index = json_value(rank, "index", 0);
  1154. json elem = json{
  1155. {"index", index},
  1156. {score_label, json_value(rank, "score", 0.0)},
  1157. };
  1158. n_tokens += json_value(rank, "tokens_evaluated", 0);
  1159. if (return_text) {
  1160. elem["text"] = std::move(texts[index]);
  1161. }
  1162. elements.push_back(elem);
  1163. }
  1164. std::sort(elements.begin(), elements.end(), [score_label](const json& a, const json& b) {
  1165. return json_value(a, score_label, 0.0) > json_value(b, score_label, 0.0);
  1166. });
  1167. elements.resize(std::min(top_n, (int)elements.size()));
  1168. json results = elements;
  1169. if (is_tei_format) return results;
  1170. json res = json{
  1171. {"model", json_value(request, "model", std::string(DEFAULT_OAICOMPAT_MODEL))},
  1172. {"object", "list"},
  1173. {"usage", json{
  1174. {"prompt_tokens", n_tokens},
  1175. {"total_tokens", n_tokens}
  1176. }},
  1177. {"results", results}
  1178. };
  1179. return res;
  1180. }
  1181. //
  1182. // other utils
  1183. //
  1184. std::vector<llama_token_data> get_token_probabilities(llama_context * ctx, int idx) {
  1185. std::vector<llama_token_data> cur;
  1186. const auto * logits = llama_get_logits_ith(ctx, idx);
  1187. const llama_model * model = llama_get_model(ctx);
  1188. const llama_vocab * vocab = llama_model_get_vocab(model);
  1189. const int n_vocab = llama_vocab_n_tokens(vocab);
  1190. cur.resize(n_vocab);
  1191. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  1192. cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
  1193. }
  1194. // sort tokens by logits
  1195. std::sort(cur.begin(), cur.end(), [](const llama_token_data & a, const llama_token_data & b) {
  1196. return a.logit > b.logit;
  1197. });
  1198. // apply softmax
  1199. float max_l = cur[0].logit;
  1200. float cum_sum = 0.0f;
  1201. for (size_t i = 0; i < cur.size(); ++i) {
  1202. float p = expf(cur[i].logit - max_l);
  1203. cur[i].p = p;
  1204. cum_sum += p;
  1205. }
  1206. for (size_t i = 0; i < cur.size(); ++i) {
  1207. cur[i].p /= cum_sum;
  1208. }
  1209. return cur;
  1210. }
  1211. std::string safe_json_to_str(const json & data) {
  1212. return data.dump(-1, ' ', false, json::error_handler_t::replace);
  1213. }
  1214. // TODO: reuse llama_detokenize
  1215. template <class Iter>
  1216. static std::string tokens_to_str(llama_context * ctx, Iter begin, Iter end) {
  1217. std::string ret;
  1218. for (; begin != end; ++begin) {
  1219. ret += common_token_to_piece(ctx, *begin);
  1220. }
  1221. return ret;
  1222. }
  1223. std::string tokens_to_str(llama_context * ctx, const llama_tokens & tokens) {
  1224. return tokens_to_str(ctx, tokens.begin(), tokens.end());
  1225. }
  1226. // format incomplete utf-8 multibyte character for output
  1227. std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  1228. std::string out = token == LLAMA_TOKEN_NULL ? "" : common_token_to_piece(ctx, token);
  1229. // if the size is 1 and first bit is 1, meaning it's a partial character
  1230. // (size > 1 meaning it's already a known token)
  1231. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  1232. std::stringstream ss;
  1233. ss << std::hex << (out[0] & 0xff);
  1234. std::string res(ss.str());
  1235. out = "byte: \\x" + res;
  1236. }
  1237. return out;
  1238. }
  1239. // format server-sent event (SSE), return the formatted string to send
  1240. // note: if data is a json array, it will be sent as multiple events, one per item
  1241. std::string format_oai_sse(const json & data) {
  1242. std::ostringstream ss;
  1243. auto send_single = [&ss](const json & data) {
  1244. ss << "data: " <<
  1245. safe_json_to_str(data) <<
  1246. "\n\n"; // required by RFC 8895 - A message is terminated by a blank line (two line terminators in a row).
  1247. };
  1248. if (data.is_array()) {
  1249. for (const auto & item : data) {
  1250. send_single(item);
  1251. }
  1252. } else {
  1253. send_single(data);
  1254. }
  1255. return ss.str();
  1256. }
  1257. std::string format_anthropic_sse(const json & data) {
  1258. std::ostringstream ss;
  1259. auto send_event = [&ss](const json & event_obj) {
  1260. if (event_obj.contains("event") && event_obj.contains("data")) {
  1261. ss << "event: " << event_obj.at("event").get<std::string>() << "\n";
  1262. ss << "data: " << safe_json_to_str(event_obj.at("data")) << "\n\n";
  1263. } else {
  1264. ss << "data: " << safe_json_to_str(event_obj) << "\n\n";
  1265. }
  1266. };
  1267. if (data.is_array()) {
  1268. for (const auto & event : data) {
  1269. send_event(event);
  1270. }
  1271. } else {
  1272. send_event(data);
  1273. }
  1274. return ss.str();
  1275. }
  1276. bool is_valid_utf8(const std::string & str) {
  1277. const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data());
  1278. const unsigned char* end = bytes + str.length();
  1279. while (bytes < end) {
  1280. if (*bytes <= 0x7F) {
  1281. // 1-byte sequence (0xxxxxxx)
  1282. bytes++;
  1283. } else if ((*bytes & 0xE0) == 0xC0) {
  1284. // 2-byte sequence (110xxxxx 10xxxxxx)
  1285. if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80)
  1286. return false;
  1287. bytes += 2;
  1288. } else if ((*bytes & 0xF0) == 0xE0) {
  1289. // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx)
  1290. if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80)
  1291. return false;
  1292. bytes += 3;
  1293. } else if ((*bytes & 0xF8) == 0xF0) {
  1294. // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
  1295. if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 ||
  1296. (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80)
  1297. return false;
  1298. bytes += 4;
  1299. } else {
  1300. // Invalid UTF-8 lead byte
  1301. return false;
  1302. }
  1303. }
  1304. return true;
  1305. }
  1306. llama_tokens format_prompt_infill(
  1307. const llama_vocab * vocab,
  1308. const json & input_prefix,
  1309. const json & input_suffix,
  1310. const json & input_extra,
  1311. const int n_batch,
  1312. const int n_predict,
  1313. const int n_ctx,
  1314. const bool spm_infill,
  1315. const llama_tokens & tokens_prompt
  1316. ) {
  1317. // TODO: optimize this block by reducing memory allocations and movement
  1318. // use FIM repo-level pattern:
  1319. // ref: https://arxiv.org/pdf/2409.12186
  1320. //
  1321. // [FIM_REP]myproject
  1322. // [FIM_SEP]filename0
  1323. // extra chunk 0
  1324. // [FIM_SEP]filename1
  1325. // extra chunk 1
  1326. // ...
  1327. // [FIM_SEP]filename
  1328. // [FIM_PRE]prefix[FIM_SUF]suffix[FIM_MID]prompt
  1329. //
  1330. llama_tokens extra_tokens;
  1331. extra_tokens.reserve(n_ctx);
  1332. auto tokens_prefix = tokenize_mixed(vocab, input_prefix, false, false);
  1333. auto tokens_suffix = tokenize_mixed(vocab, input_suffix, false, false);
  1334. if (llama_vocab_fim_rep(vocab) != LLAMA_TOKEN_NULL) {
  1335. // TODO: make project name an input
  1336. static const auto k_fim_repo = common_tokenize(vocab, "myproject\n", false, false);
  1337. extra_tokens.push_back(llama_vocab_fim_rep(vocab));
  1338. extra_tokens.insert(extra_tokens.end(), k_fim_repo.begin(), k_fim_repo.end());
  1339. }
  1340. for (const auto & chunk : input_extra) {
  1341. // { "text": string, "filename": string }
  1342. const std::string text = json_value(chunk, "text", std::string());
  1343. const std::string filename = json_value(chunk, "filename", std::string("tmp"));
  1344. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  1345. const auto k_fim_file = common_tokenize(vocab, filename + "\n", false, false);
  1346. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  1347. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  1348. } else {
  1349. // chunk separator in binary form to avoid confusing the AI
  1350. 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};
  1351. static const auto k_chunk_prefix_tokens = common_tokenize(vocab, k_chunk_prefix_str, false, false);
  1352. extra_tokens.insert(extra_tokens.end(), k_chunk_prefix_tokens.begin(), k_chunk_prefix_tokens.end());
  1353. }
  1354. const auto chunk_tokens = common_tokenize(vocab, text, false, false);
  1355. extra_tokens.insert(extra_tokens.end(), chunk_tokens.begin(), chunk_tokens.end());
  1356. }
  1357. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  1358. // TODO: current filename
  1359. static const auto k_fim_file = common_tokenize(vocab, "filename\n", false, false);
  1360. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  1361. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  1362. }
  1363. // for now pick FIM context to fit in a batch (ratio prefix:suffix = 3:1, TODO: configurable?)
  1364. const int n_prefix_take = std::min<int>(tokens_prefix.size(), 3*(n_batch/4));
  1365. const int n_suffix_take = std::min<int>(tokens_suffix.size(), std::max<int>(0, (n_batch/4) - (2 + tokens_prompt.size())));
  1366. 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));
  1367. // fill the rest of the context with extra chunks
  1368. const int n_extra_take = std::min<int>(std::max<int>(0, n_ctx - (n_batch) - 2*n_predict), extra_tokens.size());
  1369. tokens_prefix.erase(tokens_prefix.begin(), tokens_prefix.begin() + tokens_prefix.size() - n_prefix_take);
  1370. tokens_suffix.resize(n_suffix_take);
  1371. tokens_prefix.insert(tokens_prefix.begin(), llama_vocab_fim_pre(vocab));
  1372. tokens_prefix.insert(tokens_prefix.end(), tokens_prompt.begin(), tokens_prompt.end());
  1373. tokens_suffix.insert(tokens_suffix.begin(), llama_vocab_fim_suf(vocab));
  1374. auto embd_inp = spm_infill ? tokens_suffix : tokens_prefix;
  1375. auto embd_end = spm_infill ? tokens_prefix : tokens_suffix;
  1376. if (llama_vocab_get_add_bos(vocab)) {
  1377. embd_inp.insert(embd_inp.begin(), llama_vocab_bos(vocab));
  1378. }
  1379. SRV_DBG("extra: n_ctx = %d, n_extra_take = %d, n_extra = %d\n", n_ctx, n_extra_take, (int) extra_tokens.size());
  1380. // put the extra context before the FIM prefix
  1381. embd_inp.insert(embd_inp.begin(), extra_tokens.end() - n_extra_take, extra_tokens.end());
  1382. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  1383. embd_inp.push_back(llama_vocab_fim_mid(vocab));
  1384. return embd_inp;
  1385. }
  1386. server_tokens format_prompt_rerank(
  1387. const struct llama_model * model,
  1388. const struct llama_vocab * vocab,
  1389. mtmd_context * mctx,
  1390. const std::string & query,
  1391. const std::string & doc) {
  1392. server_tokens result = {};
  1393. const char * rerank_prompt = llama_model_chat_template(model, "rerank");
  1394. if (rerank_prompt != nullptr) {
  1395. std::string prompt = rerank_prompt;
  1396. string_replace_all(prompt, "{query}" , query);
  1397. string_replace_all(prompt, "{document}", doc );
  1398. server_tokens tokens = tokenize_input_subprompt(vocab, mctx, prompt, false, true);
  1399. result.push_back(tokens);
  1400. } else {
  1401. // Get EOS token - use SEP token as fallback if EOS is not available
  1402. server_tokens query_tokens = tokenize_input_subprompt(vocab, mctx, query, false, false);
  1403. server_tokens doc_tokens = tokenize_input_subprompt(vocab, mctx, doc, false, false);
  1404. llama_token eos_token = llama_vocab_eos(vocab);
  1405. if (eos_token == LLAMA_TOKEN_NULL) {
  1406. eos_token = llama_vocab_sep(vocab);
  1407. }
  1408. if (llama_vocab_get_add_bos(vocab)) {
  1409. result.push_back(llama_vocab_bos(vocab));
  1410. }
  1411. result.push_back(query_tokens);
  1412. if (llama_vocab_get_add_eos(vocab)) {
  1413. result.push_back(eos_token);
  1414. }
  1415. if (llama_vocab_get_add_sep(vocab)) {
  1416. result.push_back(llama_vocab_sep(vocab));
  1417. }
  1418. result.push_back(doc_tokens);
  1419. if (llama_vocab_get_add_eos(vocab)) {
  1420. result.push_back(eos_token);
  1421. }
  1422. }
  1423. return result;
  1424. }