server-task.cpp 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986
  1. #include "server-common.h"
  2. #include "server-task.h"
  3. #include "common.h"
  4. #include "llama.h"
  5. #include "chat.h"
  6. #include "sampling.h"
  7. #include "json-schema-to-grammar.h"
  8. using json = nlohmann::ordered_json;
  9. //
  10. // task_params
  11. //
  12. json task_params::format_logit_bias(const std::vector<llama_logit_bias> & logit_bias) const {
  13. json data = json::array();
  14. for (const auto & lb : logit_bias) {
  15. data.push_back(json{
  16. {"bias", lb.bias},
  17. {"token", lb.token},
  18. });
  19. }
  20. return data;
  21. }
  22. json task_params::to_json(bool only_metrics) const {
  23. std::vector<std::string> samplers;
  24. samplers.reserve(sampling.samplers.size());
  25. for (const auto & sampler : sampling.samplers) {
  26. samplers.emplace_back(common_sampler_type_to_str(sampler));
  27. }
  28. json lora = json::array();
  29. for (auto & it : this->lora) {
  30. lora.push_back({{"id", it.first}, {"scale", it.second}});
  31. }
  32. if (only_metrics) {
  33. return json {
  34. {"seed", sampling.seed},
  35. {"temperature", sampling.temp},
  36. {"dynatemp_range", sampling.dynatemp_range},
  37. {"dynatemp_exponent", sampling.dynatemp_exponent},
  38. {"top_k", sampling.top_k},
  39. {"top_p", sampling.top_p},
  40. {"min_p", sampling.min_p},
  41. {"top_n_sigma", sampling.top_n_sigma},
  42. {"xtc_probability", sampling.xtc_probability},
  43. {"xtc_threshold", sampling.xtc_threshold},
  44. {"typical_p", sampling.typ_p},
  45. {"repeat_last_n", sampling.penalty_last_n},
  46. {"repeat_penalty", sampling.penalty_repeat},
  47. {"presence_penalty", sampling.penalty_present},
  48. {"frequency_penalty", sampling.penalty_freq},
  49. {"dry_multiplier", sampling.dry_multiplier},
  50. {"dry_base", sampling.dry_base},
  51. {"dry_allowed_length", sampling.dry_allowed_length},
  52. {"dry_penalty_last_n", sampling.dry_penalty_last_n},
  53. {"mirostat", sampling.mirostat},
  54. {"mirostat_tau", sampling.mirostat_tau},
  55. {"mirostat_eta", sampling.mirostat_eta},
  56. {"max_tokens", n_predict},
  57. {"n_predict", n_predict}, // TODO: deduplicate?
  58. {"n_keep", n_keep},
  59. {"n_discard", n_discard},
  60. {"ignore_eos", sampling.ignore_eos},
  61. {"stream", stream},
  62. {"n_probs", sampling.n_probs},
  63. {"min_keep", sampling.min_keep},
  64. {"chat_format", common_chat_format_name(chat_parser_params.format)},
  65. {"reasoning_format", common_reasoning_format_name(chat_parser_params.reasoning_format)},
  66. {"reasoning_in_content", chat_parser_params.reasoning_in_content},
  67. {"thinking_forced_open", chat_parser_params.thinking_forced_open},
  68. {"samplers", samplers},
  69. {"speculative.n_max", speculative.n_max},
  70. {"speculative.n_min", speculative.n_min},
  71. {"speculative.p_min", speculative.p_min},
  72. {"timings_per_token", timings_per_token},
  73. {"post_sampling_probs", post_sampling_probs},
  74. {"backend_sampling", sampling.backend_sampling},
  75. {"lora", lora},
  76. };
  77. }
  78. auto grammar_triggers = json::array();
  79. for (const auto & trigger : sampling.grammar_triggers) {
  80. server_grammar_trigger ct(trigger);
  81. grammar_triggers.push_back(ct.to_json());
  82. }
  83. return json {
  84. {"seed", sampling.seed},
  85. {"temperature", sampling.temp},
  86. {"dynatemp_range", sampling.dynatemp_range},
  87. {"dynatemp_exponent", sampling.dynatemp_exponent},
  88. {"top_k", sampling.top_k},
  89. {"top_p", sampling.top_p},
  90. {"min_p", sampling.min_p},
  91. {"top_n_sigma", sampling.top_n_sigma},
  92. {"xtc_probability", sampling.xtc_probability},
  93. {"xtc_threshold", sampling.xtc_threshold},
  94. {"typical_p", sampling.typ_p},
  95. {"repeat_last_n", sampling.penalty_last_n},
  96. {"repeat_penalty", sampling.penalty_repeat},
  97. {"presence_penalty", sampling.penalty_present},
  98. {"frequency_penalty", sampling.penalty_freq},
  99. {"dry_multiplier", sampling.dry_multiplier},
  100. {"dry_base", sampling.dry_base},
  101. {"dry_allowed_length", sampling.dry_allowed_length},
  102. {"dry_penalty_last_n", sampling.dry_penalty_last_n},
  103. {"dry_sequence_breakers", sampling.dry_sequence_breakers},
  104. {"mirostat", sampling.mirostat},
  105. {"mirostat_tau", sampling.mirostat_tau},
  106. {"mirostat_eta", sampling.mirostat_eta},
  107. {"stop", antiprompt},
  108. {"max_tokens", n_predict},
  109. {"n_predict", n_predict}, // TODO: deduplicate?
  110. {"n_keep", n_keep},
  111. {"n_discard", n_discard},
  112. {"ignore_eos", sampling.ignore_eos},
  113. {"stream", stream},
  114. {"logit_bias", format_logit_bias(sampling.logit_bias)},
  115. {"n_probs", sampling.n_probs},
  116. {"min_keep", sampling.min_keep},
  117. {"grammar", sampling.grammar},
  118. {"grammar_lazy", sampling.grammar_lazy},
  119. {"grammar_triggers", grammar_triggers},
  120. {"preserved_tokens", sampling.preserved_tokens},
  121. {"chat_format", common_chat_format_name(chat_parser_params.format)},
  122. {"reasoning_format", common_reasoning_format_name(chat_parser_params.reasoning_format)},
  123. {"reasoning_in_content", chat_parser_params.reasoning_in_content},
  124. {"thinking_forced_open", chat_parser_params.thinking_forced_open},
  125. {"samplers", samplers},
  126. {"speculative.n_max", speculative.n_max},
  127. {"speculative.n_min", speculative.n_min},
  128. {"speculative.p_min", speculative.p_min},
  129. {"timings_per_token", timings_per_token},
  130. {"post_sampling_probs", post_sampling_probs},
  131. {"backend_sampling", sampling.backend_sampling},
  132. {"lora", lora},
  133. };
  134. }
  135. //
  136. // task_result_state
  137. //
  138. common_chat_msg task_result_state::update_chat_msg(
  139. const std::string & text_added,
  140. bool is_partial,
  141. std::vector<common_chat_msg_diff> & diffs) {
  142. generated_text += text_added;
  143. auto msg_prv_copy = chat_msg;
  144. SRV_DBG("Parsing chat message: %s\n", generated_text.c_str());
  145. auto new_msg = common_chat_parse(
  146. generated_text,
  147. is_partial,
  148. chat_parser_params);
  149. if (!new_msg.empty()) {
  150. new_msg.set_tool_call_ids(generated_tool_call_ids, gen_tool_call_id);
  151. chat_msg = new_msg;
  152. diffs = common_chat_msg_diff::compute_diffs(msg_prv_copy, new_msg.empty() ? msg_prv_copy : new_msg);
  153. }
  154. return chat_msg;
  155. }
  156. //
  157. // server_task
  158. //
  159. task_params server_task::params_from_json_cmpl(
  160. const llama_vocab * vocab,
  161. const common_params & params_base,
  162. const int n_ctx_slot,
  163. const json & data) {
  164. task_params params;
  165. // Sampling parameter defaults are loaded from the global server context (but individual requests can still them)
  166. task_params defaults;
  167. defaults.sampling = params_base.sampling;
  168. defaults.speculative = params_base.speculative;
  169. defaults.n_keep = params_base.n_keep;
  170. defaults.n_predict = params_base.n_predict;
  171. defaults.n_cache_reuse = params_base.n_cache_reuse;
  172. defaults.cache_prompt = params_base.cache_prompt;
  173. defaults.antiprompt = params_base.antiprompt;
  174. // enabling this will output extra debug information in the HTTP responses from the server
  175. params.verbose = params_base.verbosity > 9;
  176. params.timings_per_token = json_value(data, "timings_per_token", false);
  177. params.stream = json_value(data, "stream", false);
  178. auto stream_opt = json_value(data, "stream_options", json::object());
  179. params.include_usage = json_value(stream_opt, "include_usage", false);
  180. params.cache_prompt = json_value(data, "cache_prompt", defaults.cache_prompt);
  181. params.return_tokens = json_value(data, "return_tokens", false);
  182. params.return_progress = json_value(data, "return_progress", false);
  183. params.n_predict = json_value(data, "n_predict", json_value(data, "max_tokens", defaults.n_predict));
  184. params.n_indent = json_value(data, "n_indent", defaults.n_indent);
  185. params.n_keep = json_value(data, "n_keep", defaults.n_keep);
  186. params.n_discard = json_value(data, "n_discard", defaults.n_discard);
  187. params.n_cmpl = json_value(data, "n_cmpl", json_value(data, "n", 1));
  188. params.n_cache_reuse = json_value(data, "n_cache_reuse", defaults.n_cache_reuse);
  189. //params.t_max_prompt_ms = json_value(data, "t_max_prompt_ms", defaults.t_max_prompt_ms); // TODO: implement
  190. params.t_max_predict_ms = json_value(data, "t_max_predict_ms", defaults.t_max_predict_ms);
  191. params.response_fields = json_value(data, "response_fields", std::vector<std::string>());
  192. params.sampling.top_k = json_value(data, "top_k", defaults.sampling.top_k);
  193. params.sampling.top_p = json_value(data, "top_p", defaults.sampling.top_p);
  194. params.sampling.min_p = json_value(data, "min_p", defaults.sampling.min_p);
  195. params.sampling.top_n_sigma = json_value(data, "top_n_sigma", defaults.sampling.top_n_sigma);
  196. params.sampling.xtc_probability = json_value(data, "xtc_probability", defaults.sampling.xtc_probability);
  197. params.sampling.xtc_threshold = json_value(data, "xtc_threshold", defaults.sampling.xtc_threshold);
  198. params.sampling.typ_p = json_value(data, "typical_p", defaults.sampling.typ_p);
  199. params.sampling.temp = json_value(data, "temperature", defaults.sampling.temp);
  200. params.sampling.dynatemp_range = json_value(data, "dynatemp_range", defaults.sampling.dynatemp_range);
  201. params.sampling.dynatemp_exponent = json_value(data, "dynatemp_exponent", defaults.sampling.dynatemp_exponent);
  202. params.sampling.penalty_last_n = json_value(data, "repeat_last_n", defaults.sampling.penalty_last_n);
  203. params.sampling.penalty_repeat = json_value(data, "repeat_penalty", defaults.sampling.penalty_repeat);
  204. params.sampling.penalty_freq = json_value(data, "frequency_penalty", defaults.sampling.penalty_freq);
  205. params.sampling.penalty_present = json_value(data, "presence_penalty", defaults.sampling.penalty_present);
  206. params.sampling.dry_multiplier = json_value(data, "dry_multiplier", defaults.sampling.dry_multiplier);
  207. params.sampling.dry_base = json_value(data, "dry_base", defaults.sampling.dry_base);
  208. params.sampling.dry_allowed_length = json_value(data, "dry_allowed_length", defaults.sampling.dry_allowed_length);
  209. params.sampling.dry_penalty_last_n = json_value(data, "dry_penalty_last_n", defaults.sampling.dry_penalty_last_n);
  210. params.sampling.mirostat = json_value(data, "mirostat", defaults.sampling.mirostat);
  211. params.sampling.mirostat_tau = json_value(data, "mirostat_tau", defaults.sampling.mirostat_tau);
  212. params.sampling.mirostat_eta = json_value(data, "mirostat_eta", defaults.sampling.mirostat_eta);
  213. params.sampling.adaptive_target = json_value(data, "adaptive_target", defaults.sampling.adaptive_target);
  214. params.sampling.adaptive_decay = json_value(data, "adaptive_decay", defaults.sampling.adaptive_decay);
  215. params.sampling.seed = json_value(data, "seed", defaults.sampling.seed);
  216. params.sampling.n_probs = json_value(data, "n_probs", defaults.sampling.n_probs);
  217. params.sampling.min_keep = json_value(data, "min_keep", defaults.sampling.min_keep);
  218. params.sampling.backend_sampling = json_value(data, "backend_sampling", defaults.sampling.backend_sampling);
  219. params.post_sampling_probs = json_value(data, "post_sampling_probs", defaults.post_sampling_probs);
  220. params.speculative.n_min = json_value(data, "speculative.n_min", defaults.speculative.n_min);
  221. params.speculative.n_max = json_value(data, "speculative.n_max", defaults.speculative.n_max);
  222. params.speculative.p_min = json_value(data, "speculative.p_min", defaults.speculative.p_min);
  223. params.speculative.n_min = std::min(params.speculative.n_max, params.speculative.n_min);
  224. params.speculative.n_min = std::max(params.speculative.n_min, 0);
  225. params.speculative.n_max = std::max(params.speculative.n_max, 0);
  226. // Use OpenAI API logprobs only if n_probs wasn't provided
  227. if (data.contains("logprobs") && params.sampling.n_probs == defaults.sampling.n_probs){
  228. params.sampling.n_probs = json_value(data, "logprobs", defaults.sampling.n_probs);
  229. }
  230. if (data.contains("lora")) {
  231. if (data.at("lora").is_array()) {
  232. params.lora = parse_lora_request(data.at("lora"));
  233. } else {
  234. throw std::runtime_error("Error: 'lora' must be an array of objects with 'id' and 'scale' fields");
  235. }
  236. } else {
  237. params.lora = {};
  238. }
  239. // TODO: add more sanity checks for the input parameters
  240. if (params.sampling.penalty_last_n < -1) {
  241. throw std::runtime_error("Error: repeat_last_n must be >= -1");
  242. }
  243. if (params.sampling.dry_penalty_last_n < -1) {
  244. throw std::runtime_error("Error: dry_penalty_last_n must be >= -1");
  245. }
  246. if (params.sampling.penalty_last_n == -1) {
  247. // note: should be the slot's context and not the full context, but it's ok
  248. params.sampling.penalty_last_n = n_ctx_slot;
  249. }
  250. if (params.sampling.dry_penalty_last_n == -1) {
  251. params.sampling.dry_penalty_last_n = n_ctx_slot;
  252. }
  253. if (params.sampling.dry_base < 1.0f) {
  254. params.sampling.dry_base = defaults.sampling.dry_base;
  255. }
  256. // sequence breakers for DRY
  257. {
  258. // Currently, this is not compatible with TextGen WebUI, Koboldcpp and SillyTavern format
  259. // Ref: https://github.com/oobabooga/text-generation-webui/blob/d1af7a41ade7bd3c3a463bfa640725edb818ebaf/extensions/openai/typing.py#L39
  260. if (data.contains("dry_sequence_breakers")) {
  261. params.sampling.dry_sequence_breakers = json_value(data, "dry_sequence_breakers", std::vector<std::string>());
  262. if (params.sampling.dry_sequence_breakers.empty()) {
  263. throw std::runtime_error("Error: dry_sequence_breakers must be a non-empty array of strings");
  264. }
  265. }
  266. }
  267. // process "json_schema" and "grammar"
  268. if (data.contains("json_schema") && !data.contains("grammar")) {
  269. try {
  270. auto schema = json_value(data, "json_schema", json::object());
  271. SRV_DBG("JSON schema: %s\n", schema.dump(2).c_str());
  272. params.sampling.grammar = json_schema_to_grammar(schema);
  273. SRV_DBG("Converted grammar: %s\n", params.sampling.grammar.c_str());
  274. } catch (const std::exception & e) {
  275. throw std::runtime_error(std::string("\"json_schema\": ") + e.what());
  276. }
  277. } else {
  278. params.sampling.grammar = json_value(data, "grammar", defaults.sampling.grammar);
  279. SRV_DBG("Grammar: %s\n", params.sampling.grammar.c_str());
  280. params.sampling.grammar_lazy = json_value(data, "grammar_lazy", defaults.sampling.grammar_lazy);
  281. SRV_DBG("Grammar lazy: %s\n", params.sampling.grammar_lazy ? "true" : "false");
  282. }
  283. {
  284. auto it = data.find("chat_format");
  285. if (it != data.end()) {
  286. params.chat_parser_params.format = static_cast<common_chat_format>(it->get<int>());
  287. SRV_INF("Chat format: %s\n", common_chat_format_name(params.chat_parser_params.format));
  288. } else {
  289. params.chat_parser_params.format = defaults.chat_parser_params.format;
  290. }
  291. common_reasoning_format reasoning_format = params_base.reasoning_format;
  292. if (data.contains("reasoning_format")) {
  293. reasoning_format = common_reasoning_format_from_name(data.at("reasoning_format").get<std::string>());
  294. }
  295. params.chat_parser_params.reasoning_format = reasoning_format;
  296. params.chat_parser_params.reasoning_in_content = params.stream && (reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY);
  297. params.chat_parser_params.thinking_forced_open = json_value(data, "thinking_forced_open", false);
  298. params.chat_parser_params.parse_tool_calls = json_value(data, "parse_tool_calls", false);
  299. if (data.contains("chat_parser")) {
  300. params.chat_parser_params.parser.load(data.at("chat_parser").get<std::string>());
  301. }
  302. }
  303. {
  304. const auto preserved_tokens = data.find("preserved_tokens");
  305. if (preserved_tokens != data.end()) {
  306. for (const auto & t : *preserved_tokens) {
  307. auto ids = common_tokenize(vocab, t.get<std::string>(), /* add_special= */ false, /* parse_special= */ true);
  308. if (ids.size() == 1) {
  309. SRV_DBG("Preserved token: %d\n", ids[0]);
  310. params.sampling.preserved_tokens.insert(ids[0]);
  311. } else {
  312. // This may happen when using a tool call style meant for a model with special tokens to preserve on a model without said tokens.
  313. SRV_DBG("Not preserved because more than 1 token: %s\n", t.get<std::string>().c_str());
  314. }
  315. }
  316. }
  317. const auto grammar_triggers = data.find("grammar_triggers");
  318. if (grammar_triggers != data.end()) {
  319. for (const auto & t : *grammar_triggers) {
  320. server_grammar_trigger ct(t);
  321. if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_WORD) {
  322. const auto & word = ct.value.value;
  323. auto ids = common_tokenize(vocab, word, /* add_special= */ false, /* parse_special= */ true);
  324. if (ids.size() == 1) {
  325. auto token = ids[0];
  326. if (std::find(params.sampling.preserved_tokens.begin(), params.sampling.preserved_tokens.end(), (llama_token) token) == params.sampling.preserved_tokens.end()) {
  327. throw std::runtime_error("Grammar trigger word should be marked as preserved token: " + word);
  328. }
  329. SRV_DBG("Grammar trigger token: %d (`%s`)\n", token, word.c_str());
  330. common_grammar_trigger trigger;
  331. trigger.type = COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN;
  332. trigger.value = word;
  333. trigger.token = token;
  334. params.sampling.grammar_triggers.push_back(std::move(trigger));
  335. } else {
  336. SRV_DBG("Grammar trigger word: `%s`\n", word.c_str());
  337. params.sampling.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, word});
  338. }
  339. } else {
  340. if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN) {
  341. SRV_DBG("Grammar trigger pattern: `%s`\n", ct.value.value.c_str());
  342. } else if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL) {
  343. SRV_DBG("Grammar trigger pattern full: `%s`\n", ct.value.value.c_str());
  344. } else {
  345. throw std::runtime_error("Unknown grammar trigger type");
  346. }
  347. params.sampling.grammar_triggers.emplace_back(std::move(ct.value));
  348. }
  349. }
  350. }
  351. if (params.sampling.grammar_lazy && params.sampling.grammar_triggers.empty()) {
  352. throw std::runtime_error("Error: no triggers set for lazy grammar!");
  353. }
  354. }
  355. {
  356. params.sampling.logit_bias.clear();
  357. const auto & logit_bias = data.find("logit_bias");
  358. if (logit_bias != data.end() && logit_bias->is_array()) {
  359. const int n_vocab = llama_vocab_n_tokens(vocab);
  360. for (const auto & el : *logit_bias) {
  361. // TODO: we may want to throw errors here, in case "el" is incorrect
  362. if (el.is_array() && el.size() == 2) {
  363. float bias;
  364. if (el[1].is_number()) {
  365. bias = el[1].get<float>();
  366. } else if (el[1].is_boolean() && !el[1].get<bool>()) {
  367. bias = -INFINITY;
  368. } else {
  369. continue;
  370. }
  371. if (el[0].is_number_integer()) {
  372. llama_token tok = el[0].get<llama_token>();
  373. if (tok >= 0 && tok < n_vocab) {
  374. params.sampling.logit_bias.push_back({tok, bias});
  375. }
  376. } else if (el[0].is_string()) {
  377. auto toks = common_tokenize(vocab, el[0].get<std::string>(), false);
  378. for (auto tok : toks) {
  379. params.sampling.logit_bias.push_back({tok, bias});
  380. }
  381. }
  382. }
  383. }
  384. } else if (logit_bias != data.end() && logit_bias->is_object()) {
  385. const int n_vocab = llama_vocab_n_tokens(vocab);
  386. for (const auto & el : logit_bias->items()) {
  387. float bias;
  388. const auto & key = el.key();
  389. const auto & value = el.value();
  390. if (value.is_number()) {
  391. bias = value.get<float>();
  392. } else if (value.is_boolean() && !value.get<bool>()) {
  393. bias = -INFINITY;
  394. } else {
  395. continue;
  396. }
  397. char *end;
  398. llama_token tok = strtol(key.c_str(), &end, 10);
  399. if (*end == 0) {
  400. if (tok >= 0 && tok < n_vocab) {
  401. params.sampling.logit_bias.push_back({tok, bias});
  402. }
  403. } else {
  404. auto toks = common_tokenize(vocab, key, false);
  405. for (auto tok : toks) {
  406. params.sampling.logit_bias.push_back({tok, bias});
  407. }
  408. }
  409. }
  410. }
  411. params.sampling.ignore_eos = json_value(data, "ignore_eos", params_base.sampling.ignore_eos);
  412. if (params.sampling.ignore_eos) {
  413. params.sampling.logit_bias.insert(
  414. params.sampling.logit_bias.end(),
  415. defaults.sampling.logit_bias_eog.begin(), defaults.sampling.logit_bias_eog.end());
  416. }
  417. }
  418. {
  419. params.antiprompt.clear();
  420. const auto & stop = data.find("stop");
  421. if (stop != data.end() && stop->is_array()) {
  422. for (const auto & word : *stop) {
  423. if (!word.empty()) {
  424. params.antiprompt.push_back(word);
  425. }
  426. }
  427. }
  428. // set reverse prompt from cli args if not set in the request
  429. if (params.antiprompt.empty()) {
  430. params.antiprompt = defaults.antiprompt;
  431. }
  432. }
  433. {
  434. const auto samplers = data.find("samplers");
  435. if (samplers != data.end()) {
  436. if (samplers->is_array()) {
  437. params.sampling.samplers = common_sampler_types_from_names(*samplers, false);
  438. } else if (samplers->is_string()){
  439. params.sampling.samplers = common_sampler_types_from_chars(samplers->get<std::string>());
  440. }
  441. } else {
  442. params.sampling.samplers = defaults.sampling.samplers;
  443. }
  444. }
  445. if (params.n_cmpl > params_base.n_parallel) {
  446. throw std::runtime_error("n_cmpl cannot be greater than the number of slots, please increase -np");
  447. }
  448. return params;
  449. }
  450. //
  451. // result_timings
  452. //
  453. json result_timings::to_json() const {
  454. json base = {
  455. {"cache_n", cache_n},
  456. {"prompt_n", prompt_n},
  457. {"prompt_ms", prompt_ms},
  458. {"prompt_per_token_ms", prompt_per_token_ms},
  459. {"prompt_per_second", prompt_per_second},
  460. {"predicted_n", predicted_n},
  461. {"predicted_ms", predicted_ms},
  462. {"predicted_per_token_ms", predicted_per_token_ms},
  463. {"predicted_per_second", predicted_per_second},
  464. };
  465. if (draft_n > 0) {
  466. base["draft_n"] = draft_n;
  467. base["draft_n_accepted"] = draft_n_accepted;
  468. }
  469. return base;
  470. }
  471. //
  472. // result_prompt_progress
  473. //
  474. json result_prompt_progress::to_json() const {
  475. return json {
  476. {"total", total},
  477. {"cache", cache},
  478. {"processed", processed},
  479. {"time_ms", time_ms},
  480. };
  481. }
  482. static inline std::string stop_type_to_str(stop_type type) {
  483. switch (type) {
  484. case STOP_TYPE_EOS: return "eos";
  485. case STOP_TYPE_WORD: return "word";
  486. case STOP_TYPE_LIMIT: return "limit";
  487. default: return "none";
  488. }
  489. }
  490. //
  491. // completion_token_output
  492. //
  493. json completion_token_output::to_json(bool post_sampling_probs) const {
  494. json probs_for_token = json::array();
  495. for (const auto & p : probs) {
  496. std::string txt(p.txt);
  497. txt.resize(validate_utf8(txt));
  498. probs_for_token.push_back(json {
  499. {"id", p.tok},
  500. {"token", txt},
  501. {"bytes", str_to_bytes(p.txt)},
  502. {
  503. post_sampling_probs ? "prob" : "logprob",
  504. post_sampling_probs ? p.prob : logarithm(p.prob)
  505. },
  506. });
  507. }
  508. return probs_for_token;
  509. }
  510. json completion_token_output::probs_vector_to_json(const std::vector<completion_token_output> & probs, bool post_sampling_probs) {
  511. json out = json::array();
  512. for (const auto & p : probs) {
  513. std::string txt(p.text_to_send);
  514. txt.resize(validate_utf8(txt));
  515. out.push_back(json {
  516. {"id", p.tok},
  517. {"token", txt},
  518. {"bytes", str_to_bytes(p.text_to_send)},
  519. {
  520. post_sampling_probs ? "prob" : "logprob",
  521. post_sampling_probs ? p.prob : logarithm(p.prob)
  522. },
  523. {
  524. post_sampling_probs ? "top_probs" : "top_logprobs",
  525. p.to_json(post_sampling_probs)
  526. },
  527. });
  528. }
  529. return out;
  530. }
  531. float completion_token_output::logarithm(float x) {
  532. // nlohmann::json converts -inf to null, so we need to prevent that
  533. return x == 0.0f ? std::numeric_limits<float>::lowest() : std::log(x);
  534. }
  535. std::vector<unsigned char> completion_token_output::str_to_bytes(const std::string & str) {
  536. std::vector<unsigned char> bytes;
  537. for (unsigned char c : str) {
  538. bytes.push_back(c);
  539. }
  540. return bytes;
  541. }
  542. //
  543. // server_task_result_cmpl_final
  544. //
  545. json server_task_result_cmpl_final::to_json() {
  546. GGML_ASSERT(is_updated && "update() must be called before to_json()");
  547. switch (res_type) {
  548. case TASK_RESPONSE_TYPE_NONE:
  549. return to_json_non_oaicompat();
  550. case TASK_RESPONSE_TYPE_OAI_CMPL:
  551. return to_json_oaicompat();
  552. case TASK_RESPONSE_TYPE_OAI_CHAT:
  553. return stream ? to_json_oaicompat_chat_stream() : to_json_oaicompat_chat();
  554. case TASK_RESPONSE_TYPE_OAI_RESP:
  555. return stream ? to_json_oaicompat_resp_stream() : to_json_oaicompat_resp();
  556. case TASK_RESPONSE_TYPE_ANTHROPIC:
  557. return stream ? to_json_anthropic_stream() : to_json_anthropic();
  558. default:
  559. GGML_ASSERT(false && "Invalid task_response_type");
  560. }
  561. }
  562. json server_task_result_cmpl_final::to_json_non_oaicompat() {
  563. json res = json {
  564. {"index", index},
  565. {"content", content},
  566. {"tokens", tokens},
  567. {"id_slot", id_slot},
  568. {"stop", true},
  569. {"model", oaicompat_model},
  570. {"tokens_predicted", n_decoded},
  571. {"tokens_evaluated", n_prompt_tokens},
  572. {"generation_settings", generation_params.to_json()},
  573. {"prompt", prompt},
  574. {"has_new_line", has_new_line},
  575. {"truncated", truncated},
  576. {"stop_type", stop_type_to_str(stop)},
  577. {"stopping_word", stopping_word},
  578. {"tokens_cached", n_tokens_cached},
  579. {"timings", timings.to_json()},
  580. };
  581. if (!stream && !probs_output.empty()) {
  582. res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs);
  583. }
  584. return response_fields.empty() ? res : json_get_nested_values(response_fields, res);
  585. }
  586. json server_task_result_cmpl_final::to_json_oaicompat() {
  587. std::time_t t = std::time(0);
  588. json logprobs = json(nullptr); // OAI default to null
  589. if (!stream && probs_output.size() > 0) {
  590. logprobs = json{
  591. {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
  592. };
  593. }
  594. json finish_reason = "length";
  595. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  596. finish_reason = "stop";
  597. }
  598. json res = json {
  599. {"choices", json::array({
  600. json{
  601. {"text", content},
  602. {"index", index},
  603. {"logprobs", logprobs},
  604. {"finish_reason", finish_reason},
  605. }
  606. })},
  607. {"created", t},
  608. {"model", oaicompat_model},
  609. {"system_fingerprint", build_info},
  610. {"object", "text_completion"},
  611. {"usage", json {
  612. {"completion_tokens", n_decoded},
  613. {"prompt_tokens", n_prompt_tokens},
  614. {"total_tokens", n_decoded + n_prompt_tokens}
  615. }},
  616. {"id", oaicompat_cmpl_id}
  617. };
  618. // extra fields for debugging purposes
  619. if (verbose) {
  620. res["__verbose"] = to_json_non_oaicompat();
  621. }
  622. if (timings.prompt_n >= 0) {
  623. res.push_back({"timings", timings.to_json()});
  624. }
  625. return res;
  626. }
  627. json server_task_result_cmpl_final::to_json_oaicompat_chat() {
  628. std::string finish_reason = "length";
  629. common_chat_msg msg;
  630. if (!oaicompat_msg.empty()) {
  631. msg = oaicompat_msg;
  632. } else {
  633. msg.role = "assistant";
  634. msg.content = content;
  635. }
  636. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  637. finish_reason = msg.tool_calls.empty() ? "stop" : "tool_calls";
  638. }
  639. json choice {
  640. {"finish_reason", finish_reason},
  641. {"index", index},
  642. {"message", msg.to_json_oaicompat<json>()},
  643. };
  644. if (!stream && probs_output.size() > 0) {
  645. choice["logprobs"] = json{
  646. {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
  647. };
  648. }
  649. std::time_t t = std::time(0);
  650. json res = json {
  651. {"choices", json::array({choice})},
  652. {"created", t},
  653. {"model", oaicompat_model},
  654. {"system_fingerprint", build_info},
  655. {"object", "chat.completion"},
  656. {"usage", json {
  657. {"completion_tokens", n_decoded},
  658. {"prompt_tokens", n_prompt_tokens},
  659. {"total_tokens", n_decoded + n_prompt_tokens}
  660. }},
  661. {"id", oaicompat_cmpl_id}
  662. };
  663. // extra fields for debugging purposes
  664. if (verbose) {
  665. res["__verbose"] = to_json_non_oaicompat();
  666. }
  667. if (timings.prompt_n >= 0) {
  668. res.push_back({"timings", timings.to_json()});
  669. }
  670. return res;
  671. }
  672. json server_task_result_cmpl_final::to_json_oaicompat_chat_stream() {
  673. std::time_t t = std::time(0);
  674. std::string finish_reason = "length";
  675. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  676. finish_reason = oaicompat_msg.tool_calls.empty() ? "stop" : "tool_calls";
  677. }
  678. json deltas = json::array();
  679. for (const auto & diff : oaicompat_msg_diffs) {
  680. deltas.push_back({
  681. {"choices", json::array({
  682. json {
  683. {"finish_reason", nullptr},
  684. {"index", 0},
  685. {"delta", common_chat_msg_diff_to_json_oaicompat<json>(diff)},
  686. },
  687. })},
  688. {"created", t},
  689. {"id", oaicompat_cmpl_id},
  690. {"model", oaicompat_model},
  691. {"system_fingerprint", build_info},
  692. {"object", "chat.completion.chunk"},
  693. });
  694. }
  695. deltas.push_back({
  696. {"choices", json::array({
  697. json {
  698. {"finish_reason", finish_reason},
  699. {"index", 0},
  700. {"delta", json::object()},
  701. },
  702. })},
  703. {"created", t},
  704. {"id", oaicompat_cmpl_id},
  705. {"model", oaicompat_model},
  706. {"system_fingerprint", build_info},
  707. {"object", "chat.completion.chunk"},
  708. });
  709. if (include_usage) {
  710. // OpenAI API spec for chat.completion.chunks specifies an empty `choices` array for the last chunk when including usage
  711. // https://platform.openai.com/docs/api-reference/chat_streaming/streaming#chat_streaming/streaming-choices
  712. deltas.push_back({
  713. {"choices", json::array()},
  714. {"created", t},
  715. {"id", oaicompat_cmpl_id},
  716. {"model", oaicompat_model},
  717. {"system_fingerprint", build_info},
  718. {"object", "chat.completion.chunk"},
  719. {"usage", json {
  720. {"completion_tokens", n_decoded},
  721. {"prompt_tokens", n_prompt_tokens},
  722. {"total_tokens", n_decoded + n_prompt_tokens},
  723. }},
  724. });
  725. }
  726. if (timings.prompt_n >= 0) {
  727. deltas.back().push_back({"timings", timings.to_json()});
  728. }
  729. // extra fields for debugging purposes
  730. if (verbose && !deltas.empty()) {
  731. deltas.front()["__verbose"] = to_json_non_oaicompat();
  732. }
  733. return deltas;
  734. }
  735. json server_task_result_cmpl_final::to_json_oaicompat_resp() {
  736. common_chat_msg msg;
  737. if (!oaicompat_msg.empty()) {
  738. msg = oaicompat_msg;
  739. } else {
  740. msg.role = "assistant";
  741. msg.content = content;
  742. }
  743. std::vector<json> output;
  744. if (msg.reasoning_content != "") {
  745. output.push_back(json {
  746. {"id", "rs_" + random_string()},
  747. {"summary", json::array()},
  748. {"type", "reasoning"},
  749. {"content", json::array({ json {
  750. {"text", msg.reasoning_content},
  751. {"type", "reasoning_text"},
  752. }})},
  753. {"encrypted_content", ""},
  754. {"status", "completed"},
  755. });
  756. }
  757. if (msg.content != "") {
  758. output.push_back(json {
  759. {"content", json::array({ json {
  760. {"type", "output_text"},
  761. {"annotations", json::array()},
  762. {"logprobs", json::array()},
  763. {"text", msg.content},
  764. }})},
  765. {"id", "msg_" + random_string()},
  766. {"role", msg.role},
  767. {"status", "completed"},
  768. {"type", "message"},
  769. });
  770. }
  771. for (const common_chat_tool_call & tool_call : oaicompat_msg.tool_calls) {
  772. output.push_back(json {
  773. {"type", "function_call"},
  774. {"status", "completed"},
  775. {"arguments", tool_call.arguments},
  776. {"call_id", "fc_" + tool_call.id},
  777. {"name", tool_call.name},
  778. });
  779. }
  780. std::time_t t = std::time(0);
  781. json res = {
  782. {"completed_at", t},
  783. {"created_at", t},
  784. {"id", oai_resp_id},
  785. {"model", oaicompat_model},
  786. {"object", "response"},
  787. {"output", output},
  788. {"status", "completed"},
  789. {"usage", json {
  790. {"input_tokens", n_prompt_tokens},
  791. {"output_tokens", n_decoded},
  792. {"total_tokens", n_decoded + n_prompt_tokens},
  793. }},
  794. };
  795. return res;
  796. }
  797. json server_task_result_cmpl_final::to_json_oaicompat_resp_stream() {
  798. std::vector<json> server_sent_events;
  799. std::vector<json> output;
  800. if (oaicompat_msg.reasoning_content != "") {
  801. const json output_item = json {
  802. {"id", oai_resp_reasoning_id},
  803. {"summary", json::array()},
  804. {"type", "reasoning"},
  805. {"content", json::array({ json {
  806. {"text", oaicompat_msg.reasoning_content},
  807. {"type", "reasoning_text"},
  808. }})},
  809. {"encrypted_content", ""},
  810. };
  811. server_sent_events.push_back(json {
  812. {"event", "response.output_item.done"},
  813. {"data", json {
  814. {"type", "response.output_item.done"},
  815. {"item", output_item}
  816. }}
  817. });
  818. output.push_back(output_item);
  819. }
  820. if (oaicompat_msg.content != "") {
  821. server_sent_events.push_back(json {
  822. {"event", "response.output_text.done"},
  823. {"data", json {
  824. {"type", "response.output_text.done"},
  825. {"item_id", oai_resp_message_id},
  826. {"text", oaicompat_msg.content}
  827. }}
  828. });
  829. const json content_part = {
  830. {"type", "output_text"},
  831. {"annotations", json::array()},
  832. {"logprobs", json::array()},
  833. {"text", oaicompat_msg.content}
  834. };
  835. server_sent_events.push_back(json {
  836. {"event", "response.content_part.done"},
  837. {"data", json {
  838. {"type", "response.content_part.done"},
  839. {"item_id", oai_resp_message_id},
  840. {"part", content_part}
  841. }}
  842. });
  843. const json output_item = {
  844. {"type", "message"},
  845. {"status", "completed"},
  846. {"id", oai_resp_message_id},
  847. {"content", json::array({content_part})},
  848. {"role", "assistant"}
  849. };
  850. server_sent_events.push_back(json {
  851. {"event", "response.output_item.done"},
  852. {"data", json {
  853. {"type", "response.output_item.done"},
  854. {"item", output_item}
  855. }}
  856. });
  857. output.push_back(output_item);
  858. }
  859. for (const common_chat_tool_call & tool_call : oaicompat_msg.tool_calls) {
  860. const json output_item = {
  861. {"type", "function_call"},
  862. {"status", "completed"},
  863. {"arguments", tool_call.arguments},
  864. {"call_id", "fc_" + tool_call.id},
  865. {"name", tool_call.name}
  866. };
  867. server_sent_events.push_back(json {
  868. {"event", "response.output_item.done"},
  869. {"data", json {
  870. {"type", "response.output_item.done"},
  871. {"item", output_item}
  872. }}
  873. });
  874. output.push_back(output_item);
  875. }
  876. std::time_t t = std::time(0);
  877. server_sent_events.push_back(json {
  878. {"event", "response.completed"},
  879. {"data", json {
  880. {"type", "response.completed"},
  881. {"response", json {
  882. {"id", oai_resp_id},
  883. {"object", "response"},
  884. {"created_at", t},
  885. {"status", "completed"},
  886. {"model", oaicompat_model},
  887. {"output", output},
  888. {"usage", json {
  889. {"input_tokens", n_prompt_tokens},
  890. {"output_tokens", n_decoded},
  891. {"total_tokens", n_decoded + n_prompt_tokens}
  892. }}
  893. }},
  894. }}
  895. });
  896. return server_sent_events;
  897. }
  898. json server_task_result_cmpl_final::to_json_anthropic() {
  899. std::string stop_reason = "max_tokens";
  900. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  901. stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
  902. }
  903. json content_blocks = json::array();
  904. common_chat_msg msg;
  905. if (!oaicompat_msg.empty()) {
  906. msg = oaicompat_msg;
  907. } else {
  908. msg.role = "assistant";
  909. msg.content = content;
  910. }
  911. // thinking block comes first (Anthropic extended thinking format)
  912. if (!msg.reasoning_content.empty()) {
  913. content_blocks.push_back({
  914. {"type", "thinking"},
  915. {"thinking", msg.reasoning_content},
  916. {"signature", ""} // empty signature for local models (no cryptographic verification)
  917. });
  918. }
  919. if (!msg.content.empty()) {
  920. content_blocks.push_back({
  921. {"type", "text"},
  922. {"text", msg.content}
  923. });
  924. }
  925. for (const auto & tool_call : msg.tool_calls) {
  926. json tool_use_block = {
  927. {"type", "tool_use"},
  928. {"id", tool_call.id},
  929. {"name", tool_call.name}
  930. };
  931. try {
  932. tool_use_block["input"] = json::parse(tool_call.arguments);
  933. } catch (const std::exception &) {
  934. tool_use_block["input"] = json::object();
  935. }
  936. content_blocks.push_back(tool_use_block);
  937. }
  938. json res = {
  939. {"id", oaicompat_cmpl_id},
  940. {"type", "message"},
  941. {"role", "assistant"},
  942. {"content", content_blocks},
  943. {"model", oaicompat_model},
  944. {"stop_reason", stop_reason},
  945. {"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)},
  946. {"usage", {
  947. {"input_tokens", n_prompt_tokens},
  948. {"output_tokens", n_decoded}
  949. }}
  950. };
  951. return res;
  952. }
  953. json server_task_result_cmpl_final::to_json_anthropic_stream() {
  954. json events = json::array();
  955. std::string stop_reason = "max_tokens";
  956. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  957. stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
  958. }
  959. bool has_thinking = !oaicompat_msg.reasoning_content.empty();
  960. bool has_text = !oaicompat_msg.content.empty();
  961. size_t num_tool_calls = oaicompat_msg.tool_calls.size();
  962. // content block indices: thinking (0) -> text (0 or 1) -> tool_use (n+)
  963. size_t thinking_block_index = 0;
  964. size_t text_block_index = has_thinking ? 1 : 0;
  965. bool thinking_block_started = false;
  966. bool text_block_started = false;
  967. std::unordered_set<size_t> tool_calls_started;
  968. for (const auto & diff : oaicompat_msg_diffs) {
  969. // handle thinking/reasoning content
  970. if (!diff.reasoning_content_delta.empty()) {
  971. if (!thinking_block_started) {
  972. events.push_back({
  973. {"event", "content_block_start"},
  974. {"data", {
  975. {"type", "content_block_start"},
  976. {"index", thinking_block_index},
  977. {"content_block", {
  978. {"type", "thinking"},
  979. {"thinking", ""}
  980. }}
  981. }}
  982. });
  983. thinking_block_started = true;
  984. }
  985. events.push_back({
  986. {"event", "content_block_delta"},
  987. {"data", {
  988. {"type", "content_block_delta"},
  989. {"index", thinking_block_index},
  990. {"delta", {
  991. {"type", "thinking_delta"},
  992. {"thinking", diff.reasoning_content_delta}
  993. }}
  994. }}
  995. });
  996. }
  997. // handle regular text content
  998. if (!diff.content_delta.empty()) {
  999. if (!text_block_started) {
  1000. events.push_back({
  1001. {"event", "content_block_start"},
  1002. {"data", {
  1003. {"type", "content_block_start"},
  1004. {"index", text_block_index},
  1005. {"content_block", {
  1006. {"type", "text"},
  1007. {"text", ""}
  1008. }}
  1009. }}
  1010. });
  1011. text_block_started = true;
  1012. }
  1013. events.push_back({
  1014. {"event", "content_block_delta"},
  1015. {"data", {
  1016. {"type", "content_block_delta"},
  1017. {"index", text_block_index},
  1018. {"delta", {
  1019. {"type", "text_delta"},
  1020. {"text", diff.content_delta}
  1021. }}
  1022. }}
  1023. });
  1024. }
  1025. // handle tool calls
  1026. if (diff.tool_call_index != std::string::npos) {
  1027. size_t content_block_index = (has_thinking ? 1 : 0) + (has_text ? 1 : 0) + diff.tool_call_index;
  1028. if (tool_calls_started.find(diff.tool_call_index) == tool_calls_started.end()) {
  1029. const auto & full_tool_call = oaicompat_msg.tool_calls[diff.tool_call_index];
  1030. events.push_back({
  1031. {"event", "content_block_start"},
  1032. {"data", {
  1033. {"type", "content_block_start"},
  1034. {"index", content_block_index},
  1035. {"content_block", {
  1036. {"type", "tool_use"},
  1037. {"id", full_tool_call.id},
  1038. {"name", full_tool_call.name}
  1039. }}
  1040. }}
  1041. });
  1042. tool_calls_started.insert(diff.tool_call_index);
  1043. }
  1044. if (!diff.tool_call_delta.arguments.empty()) {
  1045. events.push_back({
  1046. {"event", "content_block_delta"},
  1047. {"data", {
  1048. {"type", "content_block_delta"},
  1049. {"index", content_block_index},
  1050. {"delta", {
  1051. {"type", "input_json_delta"},
  1052. {"partial_json", diff.tool_call_delta.arguments}
  1053. }}
  1054. }}
  1055. });
  1056. }
  1057. }
  1058. }
  1059. // close content blocks in order
  1060. if (has_thinking) {
  1061. // Anthropic API requires a signature_delta before closing thinking blocks
  1062. // We use an empty signature since we can't generate a cryptographic signature for local models
  1063. events.push_back({
  1064. {"event", "content_block_delta"},
  1065. {"data", {
  1066. {"type", "content_block_delta"},
  1067. {"index", thinking_block_index},
  1068. {"delta", {
  1069. {"type", "signature_delta"},
  1070. {"signature", ""}
  1071. }}
  1072. }}
  1073. });
  1074. events.push_back({
  1075. {"event", "content_block_stop"},
  1076. {"data", {
  1077. {"type", "content_block_stop"},
  1078. {"index", thinking_block_index}
  1079. }}
  1080. });
  1081. }
  1082. if (has_text) {
  1083. events.push_back({
  1084. {"event", "content_block_stop"},
  1085. {"data", {
  1086. {"type", "content_block_stop"},
  1087. {"index", text_block_index}
  1088. }}
  1089. });
  1090. }
  1091. for (size_t i = 0; i < num_tool_calls; i++) {
  1092. size_t content_block_index = (has_thinking ? 1 : 0) + (has_text ? 1 : 0) + i;
  1093. events.push_back({
  1094. {"event", "content_block_stop"},
  1095. {"data", {
  1096. {"type", "content_block_stop"},
  1097. {"index", content_block_index}
  1098. }}
  1099. });
  1100. }
  1101. events.push_back({
  1102. {"event", "message_delta"},
  1103. {"data", {
  1104. {"type", "message_delta"},
  1105. {"delta", {
  1106. {"stop_reason", stop_reason},
  1107. {"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)}
  1108. }},
  1109. {"usage", {
  1110. {"output_tokens", n_decoded}
  1111. }}
  1112. }}
  1113. });
  1114. events.push_back({
  1115. {"event", "message_stop"},
  1116. {"data", {
  1117. {"type", "message_stop"}
  1118. }}
  1119. });
  1120. return events;
  1121. }
  1122. //
  1123. // server_task_result_cmpl_partial
  1124. //
  1125. void server_task_result_cmpl_partial::update(task_result_state & state) {
  1126. is_updated = true;
  1127. state.update_chat_msg(content, true, oaicompat_msg_diffs);
  1128. // Copy current state for use in to_json_*() (reflects state BEFORE this chunk)
  1129. thinking_block_started = state.thinking_block_started;
  1130. text_block_started = state.text_block_started;
  1131. oai_resp_id = state.oai_resp_id;
  1132. oai_resp_reasoning_id = state.oai_resp_reasoning_id;
  1133. oai_resp_message_id = state.oai_resp_message_id;
  1134. oai_resp_fc_id = state.oai_resp_fc_id;
  1135. // track if the accumulated message has any reasoning content
  1136. anthropic_has_reasoning = !state.chat_msg.reasoning_content.empty();
  1137. // Pre-compute state updates based on diffs (for next chunk)
  1138. for (const common_chat_msg_diff & diff : oaicompat_msg_diffs) {
  1139. if (!diff.reasoning_content_delta.empty() && !state.thinking_block_started) {
  1140. state.thinking_block_started = true;
  1141. }
  1142. if (!diff.content_delta.empty() && !state.text_block_started) {
  1143. state.text_block_started = true;
  1144. }
  1145. if (!diff.tool_call_delta.name.empty()) {
  1146. state.oai_resp_fc_id = diff.tool_call_delta.id;
  1147. }
  1148. }
  1149. }
  1150. json server_task_result_cmpl_partial::to_json() {
  1151. GGML_ASSERT(is_updated && "update() must be called before to_json()");
  1152. switch (res_type) {
  1153. case TASK_RESPONSE_TYPE_NONE:
  1154. return to_json_non_oaicompat();
  1155. case TASK_RESPONSE_TYPE_OAI_CMPL:
  1156. return to_json_oaicompat();
  1157. case TASK_RESPONSE_TYPE_OAI_CHAT:
  1158. return to_json_oaicompat_chat();
  1159. case TASK_RESPONSE_TYPE_OAI_RESP:
  1160. return to_json_oaicompat_resp();
  1161. case TASK_RESPONSE_TYPE_ANTHROPIC:
  1162. return to_json_anthropic();
  1163. default:
  1164. GGML_ASSERT(false && "Invalid task_response_type");
  1165. }
  1166. }
  1167. json server_task_result_cmpl_partial::to_json_non_oaicompat() {
  1168. // non-OAI-compat JSON
  1169. json res = json {
  1170. {"index", index},
  1171. {"content", content},
  1172. {"tokens", tokens},
  1173. {"stop", false},
  1174. {"id_slot", id_slot},
  1175. {"tokens_predicted", n_decoded},
  1176. {"tokens_evaluated", n_prompt_tokens},
  1177. };
  1178. // populate the timings object when needed (usually for the last response or with timings_per_token enabled)
  1179. if (timings.prompt_n > 0) {
  1180. res.push_back({"timings", timings.to_json()});
  1181. }
  1182. if (is_progress) {
  1183. res.push_back({"prompt_progress", progress.to_json()});
  1184. }
  1185. if (!prob_output.probs.empty()) {
  1186. res["completion_probabilities"] = completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs);
  1187. }
  1188. return res;
  1189. }
  1190. json server_task_result_cmpl_partial::to_json_oaicompat() {
  1191. std::time_t t = std::time(0);
  1192. json logprobs = json(nullptr); // OAI default to null
  1193. if (prob_output.probs.size() > 0) {
  1194. logprobs = json{
  1195. {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
  1196. };
  1197. }
  1198. json res = json {
  1199. {"choices", json::array({
  1200. json{
  1201. {"text", content},
  1202. {"index", index},
  1203. {"logprobs", logprobs},
  1204. {"finish_reason", nullptr},
  1205. }
  1206. })},
  1207. {"created", t},
  1208. {"model", oaicompat_model},
  1209. {"system_fingerprint", build_info},
  1210. {"object", "text_completion"},
  1211. {"id", oaicompat_cmpl_id}
  1212. };
  1213. // extra fields for debugging purposes
  1214. if (verbose) {
  1215. res["__verbose"] = to_json_non_oaicompat();
  1216. }
  1217. if (timings.prompt_n >= 0) {
  1218. res.push_back({"timings", timings.to_json()});
  1219. }
  1220. if (is_progress) {
  1221. res.push_back({"prompt_progress", progress.to_json()});
  1222. }
  1223. return res;
  1224. }
  1225. json server_task_result_cmpl_partial::to_json_oaicompat_chat() {
  1226. bool first = n_decoded == 1;
  1227. std::time_t t = std::time(0);
  1228. json choices;
  1229. std::vector<json> deltas;
  1230. auto add_delta = [&](const json & delta) {
  1231. deltas.push_back({
  1232. {"choices", json::array({
  1233. json {
  1234. {"finish_reason", nullptr},
  1235. {"index", index},
  1236. {"delta", delta},
  1237. },
  1238. })},
  1239. {"created", t},
  1240. {"id", oaicompat_cmpl_id},
  1241. {"model", oaicompat_model},
  1242. {"system_fingerprint", build_info},
  1243. {"object", "chat.completion.chunk"},
  1244. });
  1245. };
  1246. // We have to send an initial update to conform to openai behavior
  1247. if (first || is_progress) {
  1248. add_delta({
  1249. {"role", "assistant"},
  1250. {"content", nullptr},
  1251. });
  1252. }
  1253. for (const auto & diff : oaicompat_msg_diffs) {
  1254. add_delta(common_chat_msg_diff_to_json_oaicompat<json>(diff));
  1255. }
  1256. if (!deltas.empty()) {
  1257. auto & last_json = deltas[deltas.size() - 1];
  1258. GGML_ASSERT(last_json.at("choices").size() >= 1);
  1259. if (prob_output.probs.size() > 0) {
  1260. last_json.at("choices").at(0)["logprobs"] = json {
  1261. {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
  1262. };
  1263. }
  1264. if (timings.prompt_n >= 0) {
  1265. last_json.push_back({"timings", timings.to_json()});
  1266. }
  1267. if (is_progress) {
  1268. last_json.push_back({"prompt_progress", progress.to_json()});
  1269. }
  1270. }
  1271. return deltas;
  1272. }
  1273. json server_task_result_cmpl_partial::to_json_oaicompat_resp() {
  1274. std::vector<json> events;
  1275. if (n_decoded == 1) {
  1276. events.push_back(json {
  1277. {"event", "response.created"},
  1278. {"data", json {
  1279. {"type", "response.created"},
  1280. {"response", json {
  1281. {"id", oai_resp_id},
  1282. {"object", "response"},
  1283. {"status", "in_progress"},
  1284. }},
  1285. }},
  1286. });
  1287. events.push_back(json {
  1288. {"event", "response.in_progress"},
  1289. {"data", json {
  1290. {"type", "response.in_progress"},
  1291. {"response", json {
  1292. {"id", oai_resp_id},
  1293. {"object", "response"},
  1294. {"status", "in_progress"},
  1295. }},
  1296. }},
  1297. });
  1298. }
  1299. for (const common_chat_msg_diff & diff : oaicompat_msg_diffs) {
  1300. if (!diff.reasoning_content_delta.empty()) {
  1301. if (!thinking_block_started) {
  1302. events.push_back(json {
  1303. {"event", "response.output_item.added"},
  1304. {"data", json {
  1305. {"type", "response.output_item.added"},
  1306. {"item", json {
  1307. {"id", oai_resp_reasoning_id},
  1308. {"summary", json::array()},
  1309. {"type", "reasoning"},
  1310. {"content", json::array()},
  1311. {"encrypted_content", ""},
  1312. {"status", "in_progress"},
  1313. }},
  1314. }},
  1315. });
  1316. thinking_block_started = true;
  1317. }
  1318. events.push_back(json {
  1319. {"event", "response.reasoning_text.delta"},
  1320. {"data", json {
  1321. {"type", "response.reasoning_text.delta"},
  1322. {"delta", diff.reasoning_content_delta},
  1323. {"item_id", oai_resp_reasoning_id},
  1324. }},
  1325. });
  1326. }
  1327. if (!diff.content_delta.empty()) {
  1328. if (!text_block_started) {
  1329. events.push_back(json {
  1330. {"event", "response.output_item.added"},
  1331. {"data", json {
  1332. {"type", "response.output_item.added"},
  1333. {"item", json {
  1334. {"content", json::array()},
  1335. {"id", oai_resp_message_id},
  1336. {"role", "assistant"},
  1337. {"status", "in_progress"},
  1338. {"type", "message"},
  1339. }},
  1340. }},
  1341. });
  1342. events.push_back(json {
  1343. {"event", "response.content_part.added"},
  1344. {"data", json {
  1345. {"type", "response.content_part.added"},
  1346. {"item_id", oai_resp_message_id},
  1347. {"part", json {
  1348. {"type", "output_text"},
  1349. {"text", ""},
  1350. }},
  1351. }},
  1352. });
  1353. text_block_started = true;
  1354. }
  1355. events.push_back(json {
  1356. {"event", "response.output_text.delta"},
  1357. {"data", json {
  1358. {"type", "response.output_text.delta"},
  1359. {"item_id", oai_resp_message_id},
  1360. {"delta", diff.content_delta},
  1361. }},
  1362. });
  1363. }
  1364. if (!diff.tool_call_delta.name.empty()) {
  1365. events.push_back(json {
  1366. {"event", "response.output_item.added"},
  1367. {"data", json {
  1368. {"type", "response.output_item.added"},
  1369. {"item", json {
  1370. {"arguments", ""},
  1371. {"call_id", "fc_" + diff.tool_call_delta.id},
  1372. {"name", diff.tool_call_delta.name},
  1373. {"type", "function_call"},
  1374. {"status", "in_progress"},
  1375. }},
  1376. }},
  1377. });
  1378. oai_resp_fc_id = diff.tool_call_delta.id;
  1379. }
  1380. if (!diff.tool_call_delta.arguments.empty()) {
  1381. events.push_back(json {
  1382. {"event", "response.function_call_arguments.delta"},
  1383. {"data", json {
  1384. {"type", "response.function_call_arguments.delta"},
  1385. {"delta", diff.tool_call_delta.arguments},
  1386. {"item_id", "fc_" + oai_resp_fc_id},
  1387. }},
  1388. });
  1389. }
  1390. }
  1391. return events;
  1392. }
  1393. json server_task_result_cmpl_partial::to_json_anthropic() {
  1394. json events = json::array();
  1395. bool first = (n_decoded == 1);
  1396. // use member variables to track block state across streaming calls
  1397. // (anthropic_thinking_block_started, anthropic_text_block_started)
  1398. if (first) {
  1399. events.push_back({
  1400. {"event", "message_start"},
  1401. {"data", {
  1402. {"type", "message_start"},
  1403. {"message", {
  1404. {"id", oaicompat_cmpl_id},
  1405. {"type", "message"},
  1406. {"role", "assistant"},
  1407. {"content", json::array()},
  1408. {"model", oaicompat_model},
  1409. {"stop_reason", nullptr},
  1410. {"stop_sequence", nullptr},
  1411. {"usage", {
  1412. {"input_tokens", n_prompt_tokens},
  1413. {"output_tokens", 0}
  1414. }}
  1415. }}
  1416. }}
  1417. });
  1418. }
  1419. // content block indices: thinking (0) -> text (0 or 1) -> tool_use (n+)
  1420. size_t thinking_block_index = 0;
  1421. // use anthropic_has_reasoning (set in update()) to know if ANY reasoning was generated
  1422. size_t text_block_index = anthropic_has_reasoning ? 1 : 0;
  1423. // use local copies of streaming state (copied from task_result_state in update())
  1424. // these reflect the state BEFORE this chunk was processed
  1425. bool thinking_started = thinking_block_started;
  1426. bool text_started = text_block_started;
  1427. for (const auto & diff : oaicompat_msg_diffs) {
  1428. // handle thinking/reasoning content
  1429. if (!diff.reasoning_content_delta.empty()) {
  1430. if (!thinking_started) {
  1431. events.push_back({
  1432. {"event", "content_block_start"},
  1433. {"data", {
  1434. {"type", "content_block_start"},
  1435. {"index", thinking_block_index},
  1436. {"content_block", {
  1437. {"type", "thinking"},
  1438. {"thinking", ""}
  1439. }}
  1440. }}
  1441. });
  1442. thinking_started = true;
  1443. }
  1444. events.push_back({
  1445. {"event", "content_block_delta"},
  1446. {"data", {
  1447. {"type", "content_block_delta"},
  1448. {"index", thinking_block_index},
  1449. {"delta", {
  1450. {"type", "thinking_delta"},
  1451. {"thinking", diff.reasoning_content_delta}
  1452. }}
  1453. }}
  1454. });
  1455. }
  1456. // handle regular text content
  1457. if (!diff.content_delta.empty()) {
  1458. if (!text_started) {
  1459. events.push_back({
  1460. {"event", "content_block_start"},
  1461. {"data", {
  1462. {"type", "content_block_start"},
  1463. {"index", text_block_index},
  1464. {"content_block", {
  1465. {"type", "text"},
  1466. {"text", ""}
  1467. }}
  1468. }}
  1469. });
  1470. text_started = true;
  1471. }
  1472. events.push_back({
  1473. {"event", "content_block_delta"},
  1474. {"data", {
  1475. {"type", "content_block_delta"},
  1476. {"index", text_block_index},
  1477. {"delta", {
  1478. {"type", "text_delta"},
  1479. {"text", diff.content_delta}
  1480. }}
  1481. }}
  1482. });
  1483. }
  1484. // handle tool calls
  1485. if (diff.tool_call_index != std::string::npos) {
  1486. // use anthropic_has_reasoning for thinking block count (persists across calls)
  1487. size_t content_block_index = (anthropic_has_reasoning ? 1 : 0) + (text_started ? 1 : 0) + diff.tool_call_index;
  1488. if (!diff.tool_call_delta.name.empty()) {
  1489. events.push_back({
  1490. {"event", "content_block_start"},
  1491. {"data", {
  1492. {"type", "content_block_start"},
  1493. {"index", content_block_index},
  1494. {"content_block", {
  1495. {"type", "tool_use"},
  1496. {"id", diff.tool_call_delta.id},
  1497. {"name", diff.tool_call_delta.name}
  1498. }}
  1499. }}
  1500. });
  1501. }
  1502. if (!diff.tool_call_delta.arguments.empty()) {
  1503. events.push_back({
  1504. {"event", "content_block_delta"},
  1505. {"data", {
  1506. {"type", "content_block_delta"},
  1507. {"index", content_block_index},
  1508. {"delta", {
  1509. {"type", "input_json_delta"},
  1510. {"partial_json", diff.tool_call_delta.arguments}
  1511. }}
  1512. }}
  1513. });
  1514. }
  1515. }
  1516. }
  1517. return events;
  1518. }
  1519. //
  1520. // server_task_result_embd
  1521. //
  1522. json server_task_result_embd::to_json() {
  1523. return res_type == TASK_RESPONSE_TYPE_OAI_EMBD
  1524. ? to_json_oaicompat()
  1525. : to_json_non_oaicompat();
  1526. }
  1527. json server_task_result_embd::to_json_non_oaicompat() {
  1528. return json {
  1529. {"index", index},
  1530. {"embedding", embedding},
  1531. };
  1532. }
  1533. json server_task_result_embd::to_json_oaicompat() {
  1534. return json {
  1535. {"index", index},
  1536. {"embedding", embedding[0]},
  1537. {"tokens_evaluated", n_tokens},
  1538. };
  1539. }
  1540. //
  1541. // server_task_result_rerank
  1542. //
  1543. json server_task_result_rerank::to_json() {
  1544. return json {
  1545. {"index", index},
  1546. {"score", score},
  1547. {"tokens_evaluated", n_tokens},
  1548. };
  1549. }
  1550. //
  1551. // server_task_result_error
  1552. //
  1553. json server_task_result_error::to_json() {
  1554. json res = format_error_response(err_msg, err_type);
  1555. if (err_type == ERROR_TYPE_EXCEED_CONTEXT_SIZE) {
  1556. res["n_prompt_tokens"] = n_prompt_tokens;
  1557. res["n_ctx"] = n_ctx;
  1558. }
  1559. return res;
  1560. }
  1561. //
  1562. // server_task_result_metrics
  1563. //
  1564. json server_task_result_metrics::to_json() {
  1565. return json {
  1566. { "idle", n_idle_slots },
  1567. { "processing", n_processing_slots },
  1568. { "deferred", n_tasks_deferred },
  1569. { "t_start", t_start },
  1570. { "n_prompt_tokens_processed_total", n_prompt_tokens_processed_total },
  1571. { "t_tokens_generation_total", t_tokens_generation_total },
  1572. { "n_tokens_predicted_total", n_tokens_predicted_total },
  1573. { "t_prompt_processing_total", t_prompt_processing_total },
  1574. { "n_tokens_max", n_tokens_max },
  1575. { "n_prompt_tokens_processed", n_prompt_tokens_processed },
  1576. { "t_prompt_processing", t_prompt_processing },
  1577. { "n_tokens_predicted", n_tokens_predicted },
  1578. { "t_tokens_generation", t_tokens_generation },
  1579. { "n_decode_total", n_decode_total },
  1580. { "n_busy_slots_total", n_busy_slots_total },
  1581. { "slots", slots_data },
  1582. };
  1583. }
  1584. //
  1585. // server_task_result_slot_save_load
  1586. //
  1587. json server_task_result_slot_save_load::to_json() {
  1588. if (is_save) {
  1589. return json {
  1590. { "id_slot", id_slot },
  1591. { "filename", filename },
  1592. { "n_saved", n_tokens },
  1593. { "n_written", n_bytes },
  1594. { "timings", {
  1595. { "save_ms", t_ms }
  1596. }},
  1597. };
  1598. }
  1599. return json {
  1600. { "id_slot", id_slot },
  1601. { "filename", filename },
  1602. { "n_restored", n_tokens },
  1603. { "n_read", n_bytes },
  1604. { "timings", {
  1605. { "restore_ms", t_ms }
  1606. }},
  1607. };
  1608. }
  1609. //
  1610. // server_task_result_slot_erase
  1611. //
  1612. json server_task_result_slot_erase::to_json() {
  1613. return json {
  1614. { "id_slot", id_slot },
  1615. { "n_erased", n_erased },
  1616. };
  1617. }
  1618. //
  1619. // server_task_result_get_lora
  1620. //
  1621. json server_task_result_get_lora::to_json() {
  1622. json result = json::array();
  1623. for (size_t i = 0; i < loras.size(); ++i) {
  1624. auto & lora = loras[i];
  1625. json entry = {
  1626. {"id", i},
  1627. {"path", lora.info.path},
  1628. {"scale", lora.info.scale},
  1629. {"task_name", lora.info.task_name},
  1630. {"prompt_prefix", lora.info.prompt_prefix},
  1631. };
  1632. if (!lora.alora_invocation_tokens.empty()) {
  1633. entry["alora_invocation_string"] = lora.alora_invocation_string;
  1634. entry["alora_invocation_tokens"] = lora.alora_invocation_tokens;
  1635. }
  1636. result.push_back(std::move(entry));
  1637. }
  1638. return result;
  1639. }
  1640. //
  1641. // server_task_result_apply_lora
  1642. //
  1643. json server_task_result_apply_lora::to_json() {
  1644. return json {{ "success", true }};
  1645. }
  1646. //
  1647. // server_prompt_cache
  1648. //
  1649. size_t server_prompt_cache::size() const {
  1650. size_t res = 0;
  1651. for (const auto & state : states) {
  1652. res += state.size();
  1653. }
  1654. return res;
  1655. }
  1656. size_t server_prompt_cache::n_tokens() const {
  1657. size_t res = 0;
  1658. for (const auto & state : states) {
  1659. res += state.n_tokens();
  1660. }
  1661. return res;
  1662. }
  1663. server_prompt * server_prompt_cache::alloc(const server_prompt & prompt, size_t state_size) {
  1664. // first check if the current state is contained fully in the cache
  1665. for (auto it = states.begin(); it != states.end(); ++it) {
  1666. const int cur_lcp_len = it->tokens.get_common_prefix(prompt.tokens);
  1667. if (cur_lcp_len == (int) prompt.tokens.size()) {
  1668. SRV_WRN("%s", " - prompt is already in the cache, skipping\n");
  1669. return nullptr;
  1670. }
  1671. }
  1672. // next, remove any cached prompts that are fully contained in the current prompt
  1673. for (auto it = states.begin(); it != states.end();) {
  1674. const int len = it->tokens.get_common_prefix(prompt.tokens);
  1675. if (len == (int) it->tokens.size()) {
  1676. SRV_WRN(" - removing obsolete cached prompt with length %d\n", len);
  1677. it = states.erase(it);
  1678. } else {
  1679. ++it;
  1680. }
  1681. }
  1682. std::vector<uint8_t> state_data;
  1683. // check if we can allocate enough memory for the new state
  1684. try {
  1685. state_data.resize(state_size);
  1686. } catch (const std::bad_alloc & e) {
  1687. SRV_ERR("failed to allocate memory for prompt cache state: %s\n", e.what());
  1688. limit_size = std::max<size_t>(1, 0.4*size());
  1689. SRV_WRN(" - cache size limit reduced to %.3f MiB\n", limit_size / (1024.0 * 1024.0));
  1690. update();
  1691. return nullptr;
  1692. }
  1693. // TODO: for some reason we can't copy server_tokens, so we have to do this workaround
  1694. auto & cur = states.emplace_back();
  1695. cur = {
  1696. /*.tokens =*/ server_tokens(prompt.tokens.get_text_tokens(), false),
  1697. /*.data =*/ std::move(state_data),
  1698. /*.checkpoints =*/ prompt.checkpoints,
  1699. };
  1700. return &cur;
  1701. }
  1702. bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx, int32_t id_slot) {
  1703. const int lcp_best = prompt.tokens.get_common_prefix(tokens_new);
  1704. float f_keep_best = float(lcp_best) / prompt.tokens.size();
  1705. float sim_best = float(lcp_best) / tokens_new.size();
  1706. SRV_WRN(" - looking for better prompt, base f_keep = %.3f, sim = %.3f\n", f_keep_best, sim_best);
  1707. auto it_best = states.end();
  1708. // find the most similar cached prompt, that would also preserve the most context
  1709. for (auto it = states.begin(); it != states.end(); ++it) {
  1710. const int lcp_cur = it->tokens.get_common_prefix(tokens_new);
  1711. const float f_keep_cur = float(lcp_cur) / it->tokens.size();
  1712. const float sim_cur = float(lcp_cur) / tokens_new.size();
  1713. // don't trash large prompts
  1714. if (f_keep_cur < 0.25f) {
  1715. continue;
  1716. }
  1717. if (f_keep_best < f_keep_cur && sim_best < sim_cur) {
  1718. f_keep_best = f_keep_cur;
  1719. sim_best = sim_cur;
  1720. it_best = it;
  1721. }
  1722. }
  1723. if (it_best != states.end()) {
  1724. SRV_WRN(" - found better prompt with f_keep = %.3f, sim = %.3f\n", f_keep_best, sim_best);
  1725. const size_t size = it_best->data.size();
  1726. const size_t n = llama_state_seq_set_data_ext(ctx, it_best->data.data(), size, id_slot, 0);
  1727. if (n != size) {
  1728. SRV_WRN("failed to restore state with size %zu\n", size);
  1729. return false;
  1730. }
  1731. it_best->data.clear();
  1732. it_best->data.shrink_to_fit();
  1733. prompt = std::move(*it_best);
  1734. states.erase(it_best);
  1735. }
  1736. return true;
  1737. }
  1738. void server_prompt_cache::update() {
  1739. if (limit_size > 0) {
  1740. // always keep at least one state, regardless of the limits
  1741. while (states.size() > 1 && size() > limit_size) {
  1742. if (states.empty()) {
  1743. break;
  1744. }
  1745. SRV_WRN(" - cache size limit reached, removing oldest entry (size = %.3f MiB)\n", states.front().size() / (1024.0 * 1024.0));
  1746. states.pop_front();
  1747. }
  1748. }
  1749. // average size per token
  1750. const float size_per_token = std::max<float>(1.0f, float(size()) / (std::max<size_t>(1, n_tokens())));
  1751. // dynamically increase the token limit if it can fit in the memory limit
  1752. const size_t limit_tokens_cur = limit_size > 0 ? std::max<size_t>(limit_tokens, limit_size/size_per_token) : limit_tokens;
  1753. if (limit_tokens > 0) {
  1754. while (states.size() > 1 && n_tokens() > limit_tokens_cur) {
  1755. if (states.empty()) {
  1756. break;
  1757. }
  1758. SRV_WRN(" - cache token limit (%zu, est: %zu) reached, removing oldest entry (size = %.3f MiB)\n",
  1759. limit_tokens, limit_tokens_cur, states.front().size() / (1024.0 * 1024.0));
  1760. states.pop_front();
  1761. }
  1762. }
  1763. SRV_WRN(" - cache state: %zu prompts, %.3f MiB (limits: %.3f MiB, %zu tokens, %zu est)\n",
  1764. states.size(), size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0), limit_tokens, limit_tokens_cur);
  1765. for (const auto & state : states) {
  1766. SRV_WRN(" - prompt %p: %7d tokens, checkpoints: %2zu, %9.3f MiB\n",
  1767. (const void *)&state, state.n_tokens(), state.checkpoints.size(), state.size() / (1024.0 * 1024.0));
  1768. }
  1769. }