server-common.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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. //
  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 "n" field
  651. int n_choices = json_value(body, "n", 1);
  652. if (n_choices != 1) {
  653. throw std::runtime_error("Only one completion choice is allowed");
  654. }
  655. // Handle "echo" field
  656. if (json_value(body, "echo", false)) {
  657. throw std::runtime_error("Only no echo is supported");
  658. }
  659. // Params supported by OAI but unsupported by llama.cpp
  660. static const std::vector<std::string> unsupported_params { "best_of", "suffix" };
  661. for (const auto & param : unsupported_params) {
  662. if (body.contains(param)) {
  663. throw std::runtime_error("Unsupported param: " + param);
  664. }
  665. }
  666. // Copy remaining properties to llama_params
  667. for (const auto & item : body.items()) {
  668. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  669. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  670. llama_params[item.key()] = item.value();
  671. }
  672. }
  673. return llama_params;
  674. }
  675. // media_path always end with '/', see arg.cpp
  676. static void handle_media(
  677. std::vector<raw_buffer> & out_files,
  678. json & media_obj,
  679. const std::string & media_path) {
  680. std::string url = json_value(media_obj, "url", std::string());
  681. if (string_starts_with(url, "http")) {
  682. // download remote image
  683. // TODO @ngxson : maybe make these params configurable
  684. common_remote_params params;
  685. params.headers.push_back("User-Agent: llama.cpp/" + build_info);
  686. params.max_size = 1024 * 1024 * 10; // 10MB
  687. params.timeout = 10; // seconds
  688. SRV_INF("downloading image from '%s'\n", url.c_str());
  689. auto res = common_remote_get_content(url, params);
  690. if (200 <= res.first && res.first < 300) {
  691. SRV_INF("downloaded %ld bytes\n", res.second.size());
  692. raw_buffer data;
  693. data.insert(data.end(), res.second.begin(), res.second.end());
  694. out_files.push_back(data);
  695. } else {
  696. throw std::runtime_error("Failed to download image");
  697. }
  698. } else if (string_starts_with(url, "file://")) {
  699. if (media_path.empty()) {
  700. throw std::invalid_argument("file:// URLs are not allowed unless --media-path is specified");
  701. }
  702. // load local image file
  703. std::string file_path = url.substr(7); // remove "file://"
  704. raw_buffer data;
  705. if (!fs_validate_filename(file_path, true)) {
  706. throw std::invalid_argument("file path is not allowed: " + file_path);
  707. }
  708. SRV_INF("loading image from local file '%s'\n", (media_path + file_path).c_str());
  709. std::ifstream file(media_path + file_path, std::ios::binary);
  710. if (!file) {
  711. throw std::invalid_argument("file does not exist or cannot be opened: " + file_path);
  712. }
  713. data.assign((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  714. out_files.push_back(data);
  715. } else {
  716. // try to decode base64 image
  717. std::vector<std::string> parts = string_split<std::string>(url, /*separator*/ ',');
  718. if (parts.size() != 2) {
  719. throw std::runtime_error("Invalid url value");
  720. } else if (!string_starts_with(parts[0], "data:image/")) {
  721. throw std::runtime_error("Invalid url format: " + parts[0]);
  722. } else if (!string_ends_with(parts[0], "base64")) {
  723. throw std::runtime_error("url must be base64 encoded");
  724. } else {
  725. auto base64_data = parts[1];
  726. auto decoded_data = base64_decode(base64_data);
  727. out_files.push_back(decoded_data);
  728. }
  729. }
  730. }
  731. // used by /chat/completions endpoint
  732. json oaicompat_chat_params_parse(
  733. json & body, /* openai api json semantics */
  734. const oaicompat_parser_options & opt,
  735. std::vector<raw_buffer> & out_files)
  736. {
  737. json llama_params;
  738. auto tools = json_value(body, "tools", json());
  739. auto has_tools = tools.is_array() && !tools.empty();
  740. auto stream = json_value(body, "stream", false);
  741. auto tool_choice = json_value(body, "tool_choice", std::string("auto"));
  742. if (!opt.use_jinja) {
  743. if (has_tools) {
  744. throw std::runtime_error("tools param requires --jinja flag");
  745. }
  746. if (tool_choice != "auto") {
  747. throw std::runtime_error("tool_choice param requires --jinja flag");
  748. }
  749. }
  750. // Handle "stop" field
  751. if (body.contains("stop") && body.at("stop").is_string()) {
  752. llama_params["stop"] = json::array({body.at("stop").get<std::string>()});
  753. } else {
  754. llama_params["stop"] = json_value(body, "stop", json::array());
  755. }
  756. auto json_schema = json_value(body, "json_schema", json());
  757. auto grammar = json_value(body, "grammar", std::string());
  758. if (!json_schema.is_null() && !grammar.empty()) {
  759. throw std::runtime_error("Cannot use both json_schema and grammar");
  760. }
  761. // Handle "response_format" field
  762. if (body.contains("response_format")) {
  763. json response_format = json_value(body, "response_format", json::object());
  764. std::string response_type = json_value(response_format, "type", std::string());
  765. if (response_type == "json_object") {
  766. json_schema = json_value(response_format, "schema", json::object());
  767. } else if (response_type == "json_schema") {
  768. auto schema_wrapper = json_value(response_format, "json_schema", json::object());
  769. json_schema = json_value(schema_wrapper, "schema", json::object());
  770. } else if (!response_type.empty() && response_type != "text") {
  771. throw std::invalid_argument("response_format type must be one of \"text\" or \"json_object\", but got: " + response_type);
  772. }
  773. }
  774. // get input files
  775. if (!body.contains("messages")) {
  776. throw std::invalid_argument("'messages' is required");
  777. }
  778. json & messages = body.at("messages");
  779. if (!messages.is_array()) {
  780. throw std::invalid_argument("Expected 'messages' to be an array");
  781. }
  782. for (auto & msg : messages) {
  783. std::string role = json_value(msg, "role", std::string());
  784. if (role != "assistant" && !msg.contains("content")) {
  785. throw std::invalid_argument("All non-assistant messages must contain 'content'");
  786. }
  787. if (role == "assistant") {
  788. if (!msg.contains("content") && !msg.contains("tool_calls")) {
  789. throw std::invalid_argument("Assistant message must contain either 'content' or 'tool_calls'!");
  790. }
  791. if (!msg.contains("content")) {
  792. continue; // avoid errors with no content
  793. }
  794. }
  795. json & content = msg.at("content");
  796. if (content.is_string() || content.is_null()) {
  797. continue;
  798. }
  799. if (!content.is_array()) {
  800. throw std::invalid_argument("Expected 'content' to be a string or an array");
  801. }
  802. for (auto & p : content) {
  803. std::string type = json_value(p, "type", std::string());
  804. if (type == "image_url") {
  805. if (!opt.allow_image) {
  806. throw std::runtime_error("image input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
  807. }
  808. json image_url = json_value(p, "image_url", json::object());
  809. handle_media(out_files, image_url, opt.media_path);
  810. // replace this chunk with a marker
  811. p["type"] = "text";
  812. p["text"] = mtmd_default_marker();
  813. p.erase("image_url");
  814. } else if (type == "input_audio") {
  815. if (!opt.allow_audio) {
  816. throw std::runtime_error("audio input is not supported - hint: if this is unexpected, you may need to provide the mmproj");
  817. }
  818. json input_audio = json_value(p, "input_audio", json::object());
  819. std::string data = json_value(input_audio, "data", std::string());
  820. std::string format = json_value(input_audio, "format", std::string());
  821. // while we also support flac, we don't allow it here so we matches the OAI spec
  822. if (format != "wav" && format != "mp3") {
  823. throw std::invalid_argument("input_audio.format must be either 'wav' or 'mp3'");
  824. }
  825. auto decoded_data = base64_decode(data); // expected to be base64 encoded
  826. out_files.push_back(decoded_data);
  827. // TODO: add audio_url support by reusing handle_media()
  828. // replace this chunk with a marker
  829. p["type"] = "text";
  830. p["text"] = mtmd_default_marker();
  831. p.erase("input_audio");
  832. } else if (type != "text") {
  833. throw std::invalid_argument("unsupported content[].type");
  834. }
  835. }
  836. }
  837. common_chat_templates_inputs inputs;
  838. inputs.messages = common_chat_msgs_parse_oaicompat(messages);
  839. inputs.tools = common_chat_tools_parse_oaicompat(tools);
  840. inputs.tool_choice = common_chat_tool_choice_parse_oaicompat(tool_choice);
  841. inputs.json_schema = json_schema.is_null() ? "" : json_schema.dump();
  842. inputs.grammar = grammar;
  843. inputs.use_jinja = opt.use_jinja;
  844. inputs.parallel_tool_calls = json_value(body, "parallel_tool_calls", false);
  845. inputs.add_generation_prompt = json_value(body, "add_generation_prompt", true);
  846. inputs.reasoning_format = opt.reasoning_format;
  847. inputs.enable_thinking = opt.enable_thinking;
  848. if (!inputs.tools.empty() && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) {
  849. if (body.contains("grammar")) {
  850. throw std::invalid_argument("Cannot use custom grammar constraints with tools.");
  851. }
  852. llama_params["parse_tool_calls"] = true;
  853. }
  854. // merge the template args provided from command line with the args provided in the user request
  855. auto chat_template_kwargs_object = json_value(body, "chat_template_kwargs", json::object());
  856. inputs.chat_template_kwargs = opt.chat_template_kwargs;
  857. for (const auto & item : chat_template_kwargs_object.items()) {
  858. inputs.chat_template_kwargs[item.key()] = item.value().dump();
  859. }
  860. // parse the "enable_thinking" kwarg to override the default value
  861. auto enable_thinking_kwarg = json_value(inputs.chat_template_kwargs, "enable_thinking", std::string(""));
  862. if (enable_thinking_kwarg == "true") {
  863. inputs.enable_thinking = true;
  864. } else if (enable_thinking_kwarg == "false") {
  865. inputs.enable_thinking = false;
  866. } else if (!enable_thinking_kwarg.empty() && enable_thinking_kwarg[0] == '"') {
  867. throw std::invalid_argument("invalid type for \"enable_thinking\" (expected boolean, got string)");
  868. }
  869. // if the assistant message appears at the end of list, we do not add end-of-turn token
  870. // for ex. this can be useful to modify the reasoning process in reasoning models
  871. bool prefill_assistant_message = !inputs.messages.empty() && inputs.messages.back().role == "assistant" && opt.prefill_assistant;
  872. common_chat_msg last_message;
  873. if (prefill_assistant_message) {
  874. last_message = inputs.messages.back();
  875. inputs.messages.pop_back();
  876. /* sanity check, max one assistant message at the end of the list */
  877. if (!inputs.messages.empty() && inputs.messages.back().role == "assistant"){
  878. throw std::invalid_argument("Cannot have 2 or more assistant messages at the end of the list.");
  879. }
  880. /* TODO: test this properly */
  881. inputs.reasoning_format = COMMON_REASONING_FORMAT_NONE;
  882. if ( inputs.enable_thinking ) {
  883. throw std::invalid_argument("Assistant response prefill is incompatible with enable_thinking.");
  884. }
  885. inputs.add_generation_prompt = true;
  886. }
  887. // Apply chat template to the list of messages
  888. auto chat_params = common_chat_templates_apply(opt.tmpls, inputs);
  889. /* Append assistant prefilled message */
  890. if (prefill_assistant_message) {
  891. if (!last_message.content_parts.empty()) {
  892. for (auto & p : last_message.content_parts) {
  893. chat_params.prompt += p.text;
  894. }
  895. } else {
  896. chat_params.prompt += last_message.content;
  897. }
  898. }
  899. llama_params["chat_format"] = static_cast<int>(chat_params.format);
  900. llama_params["prompt"] = chat_params.prompt;
  901. if (!chat_params.grammar.empty()) {
  902. llama_params["grammar"] = chat_params.grammar;
  903. }
  904. llama_params["grammar_lazy"] = chat_params.grammar_lazy;
  905. auto grammar_triggers = json::array();
  906. for (const auto & trigger : chat_params.grammar_triggers) {
  907. server_grammar_trigger ct(trigger);
  908. grammar_triggers.push_back(ct.to_json());
  909. }
  910. llama_params["grammar_triggers"] = grammar_triggers;
  911. llama_params["preserved_tokens"] = chat_params.preserved_tokens;
  912. llama_params["thinking_forced_open"] = chat_params.thinking_forced_open;
  913. for (const auto & stop : chat_params.additional_stops) {
  914. llama_params["stop"].push_back(stop);
  915. }
  916. // Handle "n" field
  917. int n_choices = json_value(body, "n", 1);
  918. if (n_choices != 1) {
  919. throw std::invalid_argument("Only one completion choice is allowed");
  920. }
  921. // Handle "logprobs" field
  922. // 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
  923. if (json_value(body, "logprobs", false)) {
  924. if (has_tools && stream) {
  925. throw std::invalid_argument("logprobs is not supported with tools + stream");
  926. }
  927. llama_params["n_probs"] = json_value(body, "top_logprobs", 20);
  928. } else if (body.contains("top_logprobs") && !body.at("top_logprobs").is_null()) {
  929. throw std::invalid_argument("top_logprobs requires logprobs to be set to true");
  930. }
  931. // Copy remaining properties to llama_params
  932. // This allows user to use llama.cpp-specific params like "mirostat", ... via OAI endpoint.
  933. // See "launch_slot_with_task()" for a complete list of params supported by llama.cpp
  934. for (const auto & item : body.items()) {
  935. // Exception: if "n_predict" is present, we overwrite the value specified earlier by "max_tokens"
  936. if (!llama_params.contains(item.key()) || item.key() == "n_predict") {
  937. llama_params[item.key()] = item.value();
  938. }
  939. }
  940. return llama_params;
  941. }
  942. json convert_anthropic_to_oai(const json & body) {
  943. json oai_body;
  944. // Convert system prompt
  945. json oai_messages = json::array();
  946. auto system_param = json_value(body, "system", json());
  947. if (!system_param.is_null()) {
  948. std::string system_content;
  949. if (system_param.is_string()) {
  950. system_content = system_param.get<std::string>();
  951. } else if (system_param.is_array()) {
  952. for (const auto & block : system_param) {
  953. if (json_value(block, "type", std::string()) == "text") {
  954. system_content += json_value(block, "text", std::string());
  955. }
  956. }
  957. }
  958. oai_messages.push_back({
  959. {"role", "system"},
  960. {"content", system_content}
  961. });
  962. }
  963. // Convert messages
  964. if (!body.contains("messages")) {
  965. throw std::runtime_error("'messages' is required");
  966. }
  967. const json & messages = body.at("messages");
  968. if (messages.is_array()) {
  969. for (const auto & msg : messages) {
  970. std::string role = json_value(msg, "role", std::string());
  971. if (!msg.contains("content")) {
  972. if (role == "assistant") {
  973. continue;
  974. }
  975. oai_messages.push_back(msg);
  976. continue;
  977. }
  978. const json & content = msg.at("content");
  979. if (content.is_string()) {
  980. oai_messages.push_back(msg);
  981. continue;
  982. }
  983. if (!content.is_array()) {
  984. oai_messages.push_back(msg);
  985. continue;
  986. }
  987. json tool_calls = json::array();
  988. json converted_content = json::array();
  989. json tool_results = json::array();
  990. bool has_tool_calls = false;
  991. for (const auto & block : content) {
  992. std::string type = json_value(block, "type", std::string());
  993. if (type == "text") {
  994. converted_content.push_back(block);
  995. } else if (type == "image") {
  996. json source = json_value(block, "source", json::object());
  997. std::string source_type = json_value(source, "type", std::string());
  998. if (source_type == "base64") {
  999. std::string media_type = json_value(source, "media_type", std::string("image/jpeg"));
  1000. std::string data = json_value(source, "data", std::string());
  1001. std::ostringstream ss;
  1002. ss << "data:" << media_type << ";base64," << data;
  1003. converted_content.push_back({
  1004. {"type", "image_url"},
  1005. {"image_url", {
  1006. {"url", ss.str()}
  1007. }}
  1008. });
  1009. } else if (source_type == "url") {
  1010. std::string url = json_value(source, "url", std::string());
  1011. converted_content.push_back({
  1012. {"type", "image_url"},
  1013. {"image_url", {
  1014. {"url", url}
  1015. }}
  1016. });
  1017. }
  1018. } else if (type == "tool_use") {
  1019. tool_calls.push_back({
  1020. {"id", json_value(block, "id", std::string())},
  1021. {"type", "function"},
  1022. {"function", {
  1023. {"name", json_value(block, "name", std::string())},
  1024. {"arguments", json_value(block, "input", json::object()).dump()}
  1025. }}
  1026. });
  1027. has_tool_calls = true;
  1028. } else if (type == "tool_result") {
  1029. std::string tool_use_id = json_value(block, "tool_use_id", std::string());
  1030. auto result_content = json_value(block, "content", json());
  1031. std::string result_text;
  1032. if (result_content.is_string()) {
  1033. result_text = result_content.get<std::string>();
  1034. } else if (result_content.is_array()) {
  1035. for (const auto & c : result_content) {
  1036. if (json_value(c, "type", std::string()) == "text") {
  1037. result_text += json_value(c, "text", std::string());
  1038. }
  1039. }
  1040. }
  1041. tool_results.push_back({
  1042. {"role", "tool"},
  1043. {"tool_call_id", tool_use_id},
  1044. {"content", result_text}
  1045. });
  1046. }
  1047. }
  1048. if (!converted_content.empty() || has_tool_calls) {
  1049. json new_msg = {{"role", role}};
  1050. if (!converted_content.empty()) {
  1051. new_msg["content"] = converted_content;
  1052. } else if (has_tool_calls) {
  1053. new_msg["content"] = "";
  1054. }
  1055. if (!tool_calls.empty()) {
  1056. new_msg["tool_calls"] = tool_calls;
  1057. }
  1058. oai_messages.push_back(new_msg);
  1059. }
  1060. for (const auto & tool_msg : tool_results) {
  1061. oai_messages.push_back(tool_msg);
  1062. }
  1063. }
  1064. }
  1065. oai_body["messages"] = oai_messages;
  1066. // Convert tools
  1067. if (body.contains("tools")) {
  1068. const json & tools = body.at("tools");
  1069. if (tools.is_array()) {
  1070. json oai_tools = json::array();
  1071. for (const auto & tool : tools) {
  1072. oai_tools.push_back({
  1073. {"type", "function"},
  1074. {"function", {
  1075. {"name", json_value(tool, "name", std::string())},
  1076. {"description", json_value(tool, "description", std::string())},
  1077. {"parameters", tool.contains("input_schema") ? tool.at("input_schema") : json::object()}
  1078. }}
  1079. });
  1080. }
  1081. oai_body["tools"] = oai_tools;
  1082. }
  1083. }
  1084. // Convert tool_choice
  1085. if (body.contains("tool_choice")) {
  1086. const json & tc = body.at("tool_choice");
  1087. if (tc.is_object()) {
  1088. std::string type = json_value(tc, "type", std::string());
  1089. if (type == "auto") {
  1090. oai_body["tool_choice"] = "auto";
  1091. } else if (type == "any" || type == "tool") {
  1092. oai_body["tool_choice"] = "required";
  1093. }
  1094. }
  1095. }
  1096. // Convert stop_sequences to stop
  1097. if (body.contains("stop_sequences")) {
  1098. oai_body["stop"] = body.at("stop_sequences");
  1099. }
  1100. // Handle max_tokens (required in Anthropic, but we're permissive)
  1101. if (body.contains("max_tokens")) {
  1102. oai_body["max_tokens"] = body.at("max_tokens");
  1103. } else {
  1104. oai_body["max_tokens"] = 4096;
  1105. }
  1106. // Pass through common params
  1107. for (const auto & key : {"temperature", "top_p", "top_k", "stream"}) {
  1108. if (body.contains(key)) {
  1109. oai_body[key] = body.at(key);
  1110. }
  1111. }
  1112. // Handle Anthropic-specific thinking param
  1113. if (body.contains("thinking")) {
  1114. json thinking = json_value(body, "thinking", json::object());
  1115. std::string thinking_type = json_value(thinking, "type", std::string());
  1116. if (thinking_type == "enabled") {
  1117. int budget_tokens = json_value(thinking, "budget_tokens", 10000);
  1118. oai_body["thinking_budget_tokens"] = budget_tokens;
  1119. }
  1120. }
  1121. // Handle Anthropic-specific metadata param
  1122. if (body.contains("metadata")) {
  1123. json metadata = json_value(body, "metadata", json::object());
  1124. std::string user_id = json_value(metadata, "user_id", std::string());
  1125. if (!user_id.empty()) {
  1126. oai_body["__metadata_user_id"] = user_id;
  1127. }
  1128. }
  1129. return oai_body;
  1130. }
  1131. json format_embeddings_response_oaicompat(
  1132. const json & request,
  1133. const std::string & model_name,
  1134. const json & embeddings,
  1135. bool use_base64) {
  1136. json data = json::array();
  1137. int32_t n_tokens = 0;
  1138. int i = 0;
  1139. for (const auto & elem : embeddings) {
  1140. json embedding_obj;
  1141. if (use_base64) {
  1142. const auto& vec = json_value(elem, "embedding", json::array()).get<std::vector<float>>();
  1143. const char* data_ptr = reinterpret_cast<const char*>(vec.data());
  1144. size_t data_size = vec.size() * sizeof(float);
  1145. embedding_obj = {
  1146. {"embedding", base64::encode(data_ptr, data_size)},
  1147. {"index", i++},
  1148. {"object", "embedding"},
  1149. {"encoding_format", "base64"}
  1150. };
  1151. } else {
  1152. embedding_obj = {
  1153. {"embedding", json_value(elem, "embedding", json::array())},
  1154. {"index", i++},
  1155. {"object", "embedding"}
  1156. };
  1157. }
  1158. data.push_back(embedding_obj);
  1159. n_tokens += json_value(elem, "tokens_evaluated", 0);
  1160. }
  1161. json res = json {
  1162. {"model", json_value(request, "model", model_name)},
  1163. {"object", "list"},
  1164. {"usage", json {
  1165. {"prompt_tokens", n_tokens},
  1166. {"total_tokens", n_tokens}
  1167. }},
  1168. {"data", data}
  1169. };
  1170. return res;
  1171. }
  1172. json format_response_rerank(
  1173. const json & request,
  1174. const std::string & model_name,
  1175. const json & ranks,
  1176. bool is_tei_format,
  1177. std::vector<std::string> & texts,
  1178. int top_n) {
  1179. int32_t n_tokens = 0;
  1180. bool return_text = is_tei_format && json_value(request, "return_text", false);
  1181. std::vector<json> elements; // Temporary vector to hold unsorted elements
  1182. std::string score_label = is_tei_format ? "score" : "relevance_score";
  1183. for (const auto & rank : ranks) {
  1184. int index = json_value(rank, "index", 0);
  1185. json elem = json{
  1186. {"index", index},
  1187. {score_label, json_value(rank, "score", 0.0)},
  1188. };
  1189. n_tokens += json_value(rank, "tokens_evaluated", 0);
  1190. if (return_text) {
  1191. elem["text"] = std::move(texts[index]);
  1192. }
  1193. elements.push_back(elem);
  1194. }
  1195. std::sort(elements.begin(), elements.end(), [score_label](const json& a, const json& b) {
  1196. return json_value(a, score_label, 0.0) > json_value(b, score_label, 0.0);
  1197. });
  1198. elements.resize(std::min(top_n, (int)elements.size()));
  1199. json results = elements;
  1200. if (is_tei_format) return results;
  1201. json res = json{
  1202. {"model", json_value(request, "model", model_name)},
  1203. {"object", "list"},
  1204. {"usage", json{
  1205. {"prompt_tokens", n_tokens},
  1206. {"total_tokens", n_tokens}
  1207. }},
  1208. {"results", results}
  1209. };
  1210. return res;
  1211. }
  1212. //
  1213. // other utils
  1214. //
  1215. std::vector<llama_token_data> get_token_probabilities(llama_context * ctx, int idx) {
  1216. std::vector<llama_token_data> cur;
  1217. const auto * logits = llama_get_logits_ith(ctx, idx);
  1218. const llama_model * model = llama_get_model(ctx);
  1219. const llama_vocab * vocab = llama_model_get_vocab(model);
  1220. const int n_vocab = llama_vocab_n_tokens(vocab);
  1221. cur.resize(n_vocab);
  1222. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  1223. cur[token_id] = llama_token_data{token_id, logits[token_id], 0.0f};
  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(llama_context * 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. return tokens_to_str(ctx, tokens.begin(), tokens.end());
  1256. }
  1257. // format incomplete utf-8 multibyte character for output
  1258. std::string tokens_to_output_formatted_string(const llama_context * ctx, const llama_token token) {
  1259. std::string out = token == LLAMA_TOKEN_NULL ? "" : common_token_to_piece(ctx, token);
  1260. // if the size is 1 and first bit is 1, meaning it's a partial character
  1261. // (size > 1 meaning it's already a known token)
  1262. if (out.size() == 1 && (out[0] & 0x80) == 0x80) {
  1263. std::stringstream ss;
  1264. ss << std::hex << (out[0] & 0xff);
  1265. std::string res(ss.str());
  1266. out = "byte: \\x" + res;
  1267. }
  1268. return out;
  1269. }
  1270. // format server-sent event (SSE), return the formatted string to send
  1271. // note: if data is a json array, it will be sent as multiple events, one per item
  1272. std::string format_oai_sse(const json & data) {
  1273. std::ostringstream ss;
  1274. auto send_single = [&ss](const json & data) {
  1275. ss << "data: " <<
  1276. safe_json_to_str(data) <<
  1277. "\n\n"; // required by RFC 8895 - A message is terminated by a blank line (two line terminators in a row).
  1278. };
  1279. if (data.is_array()) {
  1280. for (const auto & item : data) {
  1281. send_single(item);
  1282. }
  1283. } else {
  1284. send_single(data);
  1285. }
  1286. return ss.str();
  1287. }
  1288. std::string format_anthropic_sse(const json & data) {
  1289. std::ostringstream ss;
  1290. auto send_event = [&ss](const json & event_obj) {
  1291. if (event_obj.contains("event") && event_obj.contains("data")) {
  1292. ss << "event: " << event_obj.at("event").get<std::string>() << "\n";
  1293. ss << "data: " << safe_json_to_str(event_obj.at("data")) << "\n\n";
  1294. } else {
  1295. ss << "data: " << safe_json_to_str(event_obj) << "\n\n";
  1296. }
  1297. };
  1298. if (data.is_array()) {
  1299. for (const auto & event : data) {
  1300. send_event(event);
  1301. }
  1302. } else {
  1303. send_event(data);
  1304. }
  1305. return ss.str();
  1306. }
  1307. bool is_valid_utf8(const std::string & str) {
  1308. const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data());
  1309. const unsigned char* end = bytes + str.length();
  1310. while (bytes < end) {
  1311. if (*bytes <= 0x7F) {
  1312. // 1-byte sequence (0xxxxxxx)
  1313. bytes++;
  1314. } else if ((*bytes & 0xE0) == 0xC0) {
  1315. // 2-byte sequence (110xxxxx 10xxxxxx)
  1316. if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80)
  1317. return false;
  1318. bytes += 2;
  1319. } else if ((*bytes & 0xF0) == 0xE0) {
  1320. // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx)
  1321. if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80)
  1322. return false;
  1323. bytes += 3;
  1324. } else if ((*bytes & 0xF8) == 0xF0) {
  1325. // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)
  1326. if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 ||
  1327. (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80)
  1328. return false;
  1329. bytes += 4;
  1330. } else {
  1331. // Invalid UTF-8 lead byte
  1332. return false;
  1333. }
  1334. }
  1335. return true;
  1336. }
  1337. llama_tokens format_prompt_infill(
  1338. const llama_vocab * vocab,
  1339. const json & input_prefix,
  1340. const json & input_suffix,
  1341. const json & input_extra,
  1342. const int n_batch,
  1343. const int n_predict,
  1344. const int n_ctx,
  1345. const bool spm_infill,
  1346. const llama_tokens & tokens_prompt
  1347. ) {
  1348. // TODO: optimize this block by reducing memory allocations and movement
  1349. // use FIM repo-level pattern:
  1350. // ref: https://arxiv.org/pdf/2409.12186
  1351. //
  1352. // [FIM_REP]myproject
  1353. // [FIM_SEP]filename0
  1354. // extra chunk 0
  1355. // [FIM_SEP]filename1
  1356. // extra chunk 1
  1357. // ...
  1358. // [FIM_SEP]filename
  1359. // [FIM_PRE]prefix[FIM_SUF]suffix[FIM_MID]prompt
  1360. //
  1361. llama_tokens extra_tokens;
  1362. extra_tokens.reserve(n_ctx);
  1363. auto tokens_prefix = tokenize_mixed(vocab, input_prefix, false, false);
  1364. auto tokens_suffix = tokenize_mixed(vocab, input_suffix, false, false);
  1365. if (llama_vocab_fim_rep(vocab) != LLAMA_TOKEN_NULL) {
  1366. // TODO: make project name an input
  1367. static const auto k_fim_repo = common_tokenize(vocab, "myproject\n", false, false);
  1368. extra_tokens.push_back(llama_vocab_fim_rep(vocab));
  1369. extra_tokens.insert(extra_tokens.end(), k_fim_repo.begin(), k_fim_repo.end());
  1370. }
  1371. for (const auto & chunk : input_extra) {
  1372. // { "text": string, "filename": string }
  1373. const std::string text = json_value(chunk, "text", std::string());
  1374. const std::string filename = json_value(chunk, "filename", std::string("tmp"));
  1375. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  1376. const auto k_fim_file = common_tokenize(vocab, filename + "\n", false, false);
  1377. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  1378. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  1379. } else {
  1380. // chunk separator in binary form to avoid confusing the AI
  1381. 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};
  1382. static const auto k_chunk_prefix_tokens = common_tokenize(vocab, k_chunk_prefix_str, false, false);
  1383. extra_tokens.insert(extra_tokens.end(), k_chunk_prefix_tokens.begin(), k_chunk_prefix_tokens.end());
  1384. }
  1385. const auto chunk_tokens = common_tokenize(vocab, text, false, false);
  1386. extra_tokens.insert(extra_tokens.end(), chunk_tokens.begin(), chunk_tokens.end());
  1387. }
  1388. if (llama_vocab_fim_sep(vocab) != LLAMA_TOKEN_NULL) {
  1389. // TODO: current filename
  1390. static const auto k_fim_file = common_tokenize(vocab, "filename\n", false, false);
  1391. extra_tokens.insert(extra_tokens.end(), llama_vocab_fim_sep(vocab));
  1392. extra_tokens.insert(extra_tokens.end(), k_fim_file.begin(), k_fim_file.end());
  1393. }
  1394. // for now pick FIM context to fit in a batch (ratio prefix:suffix = 3:1, TODO: configurable?)
  1395. const int n_prefix_take = std::min<int>(tokens_prefix.size(), 3*(n_batch/4));
  1396. const int n_suffix_take = std::min<int>(tokens_suffix.size(), std::max<int>(0, (n_batch/4) - (2 + tokens_prompt.size())));
  1397. 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));
  1398. // fill the rest of the context with extra chunks
  1399. const int n_extra_take = std::min<int>(std::max<int>(0, n_ctx - (n_batch) - 2*n_predict), extra_tokens.size());
  1400. tokens_prefix.erase(tokens_prefix.begin(), tokens_prefix.begin() + tokens_prefix.size() - n_prefix_take);
  1401. tokens_suffix.resize(n_suffix_take);
  1402. tokens_prefix.insert(tokens_prefix.begin(), llama_vocab_fim_pre(vocab));
  1403. tokens_prefix.insert(tokens_prefix.end(), tokens_prompt.begin(), tokens_prompt.end());
  1404. tokens_suffix.insert(tokens_suffix.begin(), llama_vocab_fim_suf(vocab));
  1405. auto embd_inp = spm_infill ? tokens_suffix : tokens_prefix;
  1406. auto embd_end = spm_infill ? tokens_prefix : tokens_suffix;
  1407. if (llama_vocab_get_add_bos(vocab)) {
  1408. embd_inp.insert(embd_inp.begin(), llama_vocab_bos(vocab));
  1409. }
  1410. SRV_DBG("extra: n_ctx = %d, n_extra_take = %d, n_extra = %d\n", n_ctx, n_extra_take, (int) extra_tokens.size());
  1411. // put the extra context before the FIM prefix
  1412. embd_inp.insert(embd_inp.begin(), extra_tokens.end() - n_extra_take, extra_tokens.end());
  1413. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  1414. embd_inp.push_back(llama_vocab_fim_mid(vocab));
  1415. return embd_inp;
  1416. }
  1417. server_tokens format_prompt_rerank(
  1418. const struct llama_model * model,
  1419. const struct llama_vocab * vocab,
  1420. mtmd_context * mctx,
  1421. const std::string & query,
  1422. const std::string & doc) {
  1423. server_tokens result = {};
  1424. const char * rerank_prompt = llama_model_chat_template(model, "rerank");
  1425. if (rerank_prompt != nullptr) {
  1426. std::string prompt = rerank_prompt;
  1427. string_replace_all(prompt, "{query}" , query);
  1428. string_replace_all(prompt, "{document}", doc );
  1429. server_tokens tokens = tokenize_input_subprompt(vocab, mctx, prompt, false, true);
  1430. result.push_back(tokens);
  1431. } else {
  1432. // Get EOS token - use SEP token as fallback if EOS is not available
  1433. server_tokens query_tokens = tokenize_input_subprompt(vocab, mctx, query, false, false);
  1434. server_tokens doc_tokens = tokenize_input_subprompt(vocab, mctx, doc, false, false);
  1435. llama_token eos_token = llama_vocab_eos(vocab);
  1436. if (eos_token == LLAMA_TOKEN_NULL) {
  1437. eos_token = llama_vocab_sep(vocab);
  1438. }
  1439. if (llama_vocab_get_add_bos(vocab)) {
  1440. result.push_back(llama_vocab_bos(vocab));
  1441. }
  1442. result.push_back(query_tokens);
  1443. if (llama_vocab_get_add_eos(vocab)) {
  1444. result.push_back(eos_token);
  1445. }
  1446. if (llama_vocab_get_add_sep(vocab)) {
  1447. result.push_back(llama_vocab_sep(vocab));
  1448. }
  1449. result.push_back(doc_tokens);
  1450. if (llama_vocab_get_add_eos(vocab)) {
  1451. result.push_back(eos_token);
  1452. }
  1453. }
  1454. return result;
  1455. }