server-common.cpp 59 KB

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