1
0

server-common.cpp 59 KB

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