server-task.cpp 73 KB

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