server-task.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  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 (size_t i = 0; i < this->lora.size(); ++i) {
  30. lora.push_back({{"id", i}, {"scale", this->lora[i].scale}});
  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(oaicompat_chat_syntax.format)},
  65. {"reasoning_format", common_reasoning_format_name(oaicompat_chat_syntax.reasoning_format)},
  66. {"reasoning_in_content", oaicompat_chat_syntax.reasoning_in_content},
  67. {"thinking_forced_open", oaicompat_chat_syntax.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. {"lora", lora},
  75. };
  76. }
  77. auto grammar_triggers = json::array();
  78. for (const auto & trigger : sampling.grammar_triggers) {
  79. server_grammar_trigger ct(trigger);
  80. grammar_triggers.push_back(ct.to_json());
  81. }
  82. return json {
  83. {"seed", sampling.seed},
  84. {"temperature", sampling.temp},
  85. {"dynatemp_range", sampling.dynatemp_range},
  86. {"dynatemp_exponent", sampling.dynatemp_exponent},
  87. {"top_k", sampling.top_k},
  88. {"top_p", sampling.top_p},
  89. {"min_p", sampling.min_p},
  90. {"top_n_sigma", sampling.top_n_sigma},
  91. {"xtc_probability", sampling.xtc_probability},
  92. {"xtc_threshold", sampling.xtc_threshold},
  93. {"typical_p", sampling.typ_p},
  94. {"repeat_last_n", sampling.penalty_last_n},
  95. {"repeat_penalty", sampling.penalty_repeat},
  96. {"presence_penalty", sampling.penalty_present},
  97. {"frequency_penalty", sampling.penalty_freq},
  98. {"dry_multiplier", sampling.dry_multiplier},
  99. {"dry_base", sampling.dry_base},
  100. {"dry_allowed_length", sampling.dry_allowed_length},
  101. {"dry_penalty_last_n", sampling.dry_penalty_last_n},
  102. {"dry_sequence_breakers", sampling.dry_sequence_breakers},
  103. {"mirostat", sampling.mirostat},
  104. {"mirostat_tau", sampling.mirostat_tau},
  105. {"mirostat_eta", sampling.mirostat_eta},
  106. {"stop", antiprompt},
  107. {"max_tokens", n_predict},
  108. {"n_predict", n_predict}, // TODO: deduplicate?
  109. {"n_keep", n_keep},
  110. {"n_discard", n_discard},
  111. {"ignore_eos", sampling.ignore_eos},
  112. {"stream", stream},
  113. {"logit_bias", format_logit_bias(sampling.logit_bias)},
  114. {"n_probs", sampling.n_probs},
  115. {"min_keep", sampling.min_keep},
  116. {"grammar", sampling.grammar},
  117. {"grammar_lazy", sampling.grammar_lazy},
  118. {"grammar_triggers", grammar_triggers},
  119. {"preserved_tokens", sampling.preserved_tokens},
  120. {"chat_format", common_chat_format_name(oaicompat_chat_syntax.format)},
  121. {"reasoning_format", common_reasoning_format_name(oaicompat_chat_syntax.reasoning_format)},
  122. {"reasoning_in_content", oaicompat_chat_syntax.reasoning_in_content},
  123. {"thinking_forced_open", oaicompat_chat_syntax.thinking_forced_open},
  124. {"samplers", samplers},
  125. {"speculative.n_max", speculative.n_max},
  126. {"speculative.n_min", speculative.n_min},
  127. {"speculative.p_min", speculative.p_min},
  128. {"timings_per_token", timings_per_token},
  129. {"post_sampling_probs", post_sampling_probs},
  130. {"lora", lora},
  131. };
  132. }
  133. //
  134. // server_task
  135. //
  136. task_params server_task::params_from_json_cmpl(
  137. const llama_context * ctx,
  138. const common_params & params_base,
  139. const json & data) {
  140. const llama_model * model = llama_get_model(ctx);
  141. const llama_vocab * vocab = llama_model_get_vocab(model);
  142. task_params params;
  143. // Sampling parameter defaults are loaded from the global server context (but individual requests can still them)
  144. task_params defaults;
  145. defaults.sampling = params_base.sampling;
  146. defaults.speculative = params_base.speculative;
  147. defaults.n_keep = params_base.n_keep;
  148. defaults.n_predict = params_base.n_predict;
  149. defaults.antiprompt = params_base.antiprompt;
  150. // enabling this will output extra debug information in the HTTP responses from the server
  151. params.verbose = params_base.verbosity > 9;
  152. params.timings_per_token = json_value(data, "timings_per_token", false);
  153. params.stream = json_value(data, "stream", false);
  154. auto stream_opt = json_value(data, "stream_options", json::object());
  155. params.include_usage = json_value(stream_opt, "include_usage", false);
  156. params.cache_prompt = json_value(data, "cache_prompt", true);
  157. params.return_tokens = json_value(data, "return_tokens", false);
  158. params.return_progress = json_value(data, "return_progress", false);
  159. params.n_predict = json_value(data, "n_predict", json_value(data, "max_tokens", defaults.n_predict));
  160. params.n_indent = json_value(data, "n_indent", defaults.n_indent);
  161. params.n_keep = json_value(data, "n_keep", defaults.n_keep);
  162. params.n_discard = json_value(data, "n_discard", defaults.n_discard);
  163. //params.t_max_prompt_ms = json_value(data, "t_max_prompt_ms", defaults.t_max_prompt_ms); // TODO: implement
  164. params.t_max_predict_ms = json_value(data, "t_max_predict_ms", defaults.t_max_predict_ms);
  165. params.response_fields = json_value(data, "response_fields", std::vector<std::string>());
  166. params.sampling.top_k = json_value(data, "top_k", defaults.sampling.top_k);
  167. params.sampling.top_p = json_value(data, "top_p", defaults.sampling.top_p);
  168. params.sampling.min_p = json_value(data, "min_p", defaults.sampling.min_p);
  169. params.sampling.top_n_sigma = json_value(data, "top_n_sigma", defaults.sampling.top_n_sigma);
  170. params.sampling.xtc_probability = json_value(data, "xtc_probability", defaults.sampling.xtc_probability);
  171. params.sampling.xtc_threshold = json_value(data, "xtc_threshold", defaults.sampling.xtc_threshold);
  172. params.sampling.typ_p = json_value(data, "typical_p", defaults.sampling.typ_p);
  173. params.sampling.temp = json_value(data, "temperature", defaults.sampling.temp);
  174. params.sampling.dynatemp_range = json_value(data, "dynatemp_range", defaults.sampling.dynatemp_range);
  175. params.sampling.dynatemp_exponent = json_value(data, "dynatemp_exponent", defaults.sampling.dynatemp_exponent);
  176. params.sampling.penalty_last_n = json_value(data, "repeat_last_n", defaults.sampling.penalty_last_n);
  177. params.sampling.penalty_repeat = json_value(data, "repeat_penalty", defaults.sampling.penalty_repeat);
  178. params.sampling.penalty_freq = json_value(data, "frequency_penalty", defaults.sampling.penalty_freq);
  179. params.sampling.penalty_present = json_value(data, "presence_penalty", defaults.sampling.penalty_present);
  180. params.sampling.dry_multiplier = json_value(data, "dry_multiplier", defaults.sampling.dry_multiplier);
  181. params.sampling.dry_base = json_value(data, "dry_base", defaults.sampling.dry_base);
  182. params.sampling.dry_allowed_length = json_value(data, "dry_allowed_length", defaults.sampling.dry_allowed_length);
  183. params.sampling.dry_penalty_last_n = json_value(data, "dry_penalty_last_n", defaults.sampling.dry_penalty_last_n);
  184. params.sampling.mirostat = json_value(data, "mirostat", defaults.sampling.mirostat);
  185. params.sampling.mirostat_tau = json_value(data, "mirostat_tau", defaults.sampling.mirostat_tau);
  186. params.sampling.mirostat_eta = json_value(data, "mirostat_eta", defaults.sampling.mirostat_eta);
  187. params.sampling.seed = json_value(data, "seed", defaults.sampling.seed);
  188. params.sampling.n_probs = json_value(data, "n_probs", defaults.sampling.n_probs);
  189. params.sampling.min_keep = json_value(data, "min_keep", defaults.sampling.min_keep);
  190. params.post_sampling_probs = json_value(data, "post_sampling_probs", defaults.post_sampling_probs);
  191. params.speculative.n_min = json_value(data, "speculative.n_min", defaults.speculative.n_min);
  192. params.speculative.n_max = json_value(data, "speculative.n_max", defaults.speculative.n_max);
  193. params.speculative.p_min = json_value(data, "speculative.p_min", defaults.speculative.p_min);
  194. params.speculative.n_min = std::min(params.speculative.n_max, params.speculative.n_min);
  195. params.speculative.n_min = std::max(params.speculative.n_min, 0);
  196. params.speculative.n_max = std::max(params.speculative.n_max, 0);
  197. // Use OpenAI API logprobs only if n_probs wasn't provided
  198. if (data.contains("logprobs") && params.sampling.n_probs == defaults.sampling.n_probs){
  199. params.sampling.n_probs = json_value(data, "logprobs", defaults.sampling.n_probs);
  200. }
  201. if (data.contains("lora")) {
  202. if (data.at("lora").is_array()) {
  203. params.lora = parse_lora_request(params_base.lora_adapters, data.at("lora"));
  204. } else {
  205. throw std::runtime_error("Error: 'lora' must be an array of objects with 'id' and 'scale' fields");
  206. }
  207. } else {
  208. params.lora = params_base.lora_adapters;
  209. }
  210. // TODO: add more sanity checks for the input parameters
  211. if (params.sampling.penalty_last_n < -1) {
  212. throw std::runtime_error("Error: repeat_last_n must be >= -1");
  213. }
  214. if (params.sampling.dry_penalty_last_n < -1) {
  215. throw std::runtime_error("Error: dry_penalty_last_n must be >= -1");
  216. }
  217. if (params.sampling.penalty_last_n == -1) {
  218. // note: should be the slot's context and not the full context, but it's ok
  219. params.sampling.penalty_last_n = llama_n_ctx(ctx);
  220. }
  221. if (params.sampling.dry_penalty_last_n == -1) {
  222. params.sampling.dry_penalty_last_n = llama_n_ctx(ctx);
  223. }
  224. if (params.sampling.dry_base < 1.0f) {
  225. params.sampling.dry_base = defaults.sampling.dry_base;
  226. }
  227. // sequence breakers for DRY
  228. {
  229. // Currently, this is not compatible with TextGen WebUI, Koboldcpp and SillyTavern format
  230. // Ref: https://github.com/oobabooga/text-generation-webui/blob/d1af7a41ade7bd3c3a463bfa640725edb818ebaf/extensions/openai/typing.py#L39
  231. if (data.contains("dry_sequence_breakers")) {
  232. params.sampling.dry_sequence_breakers = json_value(data, "dry_sequence_breakers", std::vector<std::string>());
  233. if (params.sampling.dry_sequence_breakers.empty()) {
  234. throw std::runtime_error("Error: dry_sequence_breakers must be a non-empty array of strings");
  235. }
  236. }
  237. }
  238. // process "json_schema" and "grammar"
  239. if (data.contains("json_schema") && !data.contains("grammar")) {
  240. try {
  241. auto schema = json_value(data, "json_schema", json::object());
  242. SRV_DBG("JSON schema: %s\n", schema.dump(2).c_str());
  243. params.sampling.grammar = json_schema_to_grammar(schema);
  244. SRV_DBG("Converted grammar: %s\n", params.sampling.grammar.c_str());
  245. } catch (const std::exception & e) {
  246. throw std::runtime_error(std::string("\"json_schema\": ") + e.what());
  247. }
  248. } else {
  249. params.sampling.grammar = json_value(data, "grammar", defaults.sampling.grammar);
  250. SRV_DBG("Grammar: %s\n", params.sampling.grammar.c_str());
  251. params.sampling.grammar_lazy = json_value(data, "grammar_lazy", defaults.sampling.grammar_lazy);
  252. SRV_DBG("Grammar lazy: %s\n", params.sampling.grammar_lazy ? "true" : "false");
  253. }
  254. {
  255. auto it = data.find("chat_format");
  256. if (it != data.end()) {
  257. params.oaicompat_chat_syntax.format = static_cast<common_chat_format>(it->get<int>());
  258. SRV_INF("Chat format: %s\n", common_chat_format_name(params.oaicompat_chat_syntax.format));
  259. } else {
  260. params.oaicompat_chat_syntax.format = defaults.oaicompat_chat_syntax.format;
  261. }
  262. common_reasoning_format reasoning_format = params_base.reasoning_format;
  263. if (data.contains("reasoning_format")) {
  264. reasoning_format = common_reasoning_format_from_name(data.at("reasoning_format").get<std::string>());
  265. }
  266. params.oaicompat_chat_syntax.reasoning_format = reasoning_format;
  267. params.oaicompat_chat_syntax.reasoning_in_content = params.stream && (reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY);
  268. params.oaicompat_chat_syntax.thinking_forced_open = json_value(data, "thinking_forced_open", false);
  269. params.oaicompat_chat_syntax.parse_tool_calls = json_value(data, "parse_tool_calls", false);
  270. if (data.contains("chat_parser")) {
  271. params.oaicompat_chat_syntax.parser.load(data.at("chat_parser").get<std::string>());
  272. }
  273. }
  274. {
  275. const auto preserved_tokens = data.find("preserved_tokens");
  276. if (preserved_tokens != data.end()) {
  277. for (const auto & t : *preserved_tokens) {
  278. auto ids = common_tokenize(vocab, t.get<std::string>(), /* add_special= */ false, /* parse_special= */ true);
  279. if (ids.size() == 1) {
  280. SRV_DBG("Preserved token: %d\n", ids[0]);
  281. params.sampling.preserved_tokens.insert(ids[0]);
  282. } else {
  283. // This may happen when using a tool call style meant for a model with special tokens to preserve on a model without said tokens.
  284. SRV_DBG("Not preserved because more than 1 token: %s\n", t.get<std::string>().c_str());
  285. }
  286. }
  287. }
  288. const auto grammar_triggers = data.find("grammar_triggers");
  289. if (grammar_triggers != data.end()) {
  290. for (const auto & t : *grammar_triggers) {
  291. server_grammar_trigger ct(t);
  292. if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_WORD) {
  293. const auto & word = ct.value.value;
  294. auto ids = common_tokenize(vocab, word, /* add_special= */ false, /* parse_special= */ true);
  295. if (ids.size() == 1) {
  296. auto token = ids[0];
  297. if (std::find(params.sampling.preserved_tokens.begin(), params.sampling.preserved_tokens.end(), (llama_token) token) == params.sampling.preserved_tokens.end()) {
  298. throw std::runtime_error("Grammar trigger word should be marked as preserved token: " + word);
  299. }
  300. SRV_DBG("Grammar trigger token: %d (`%s`)\n", token, word.c_str());
  301. common_grammar_trigger trigger;
  302. trigger.type = COMMON_GRAMMAR_TRIGGER_TYPE_TOKEN;
  303. trigger.value = word;
  304. trigger.token = token;
  305. params.sampling.grammar_triggers.push_back(std::move(trigger));
  306. } else {
  307. SRV_DBG("Grammar trigger word: `%s`\n", word.c_str());
  308. params.sampling.grammar_triggers.push_back({COMMON_GRAMMAR_TRIGGER_TYPE_WORD, word});
  309. }
  310. } else {
  311. if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN) {
  312. SRV_DBG("Grammar trigger pattern: `%s`\n", ct.value.value.c_str());
  313. } else if (ct.value.type == COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL) {
  314. SRV_DBG("Grammar trigger pattern full: `%s`\n", ct.value.value.c_str());
  315. } else {
  316. throw std::runtime_error("Unknown grammar trigger type");
  317. }
  318. params.sampling.grammar_triggers.emplace_back(std::move(ct.value));
  319. }
  320. }
  321. }
  322. if (params.sampling.grammar_lazy && params.sampling.grammar_triggers.empty()) {
  323. throw std::runtime_error("Error: no triggers set for lazy grammar!");
  324. }
  325. }
  326. {
  327. params.sampling.logit_bias.clear();
  328. const auto & logit_bias = data.find("logit_bias");
  329. if (logit_bias != data.end() && logit_bias->is_array()) {
  330. const int n_vocab = llama_vocab_n_tokens(vocab);
  331. for (const auto & el : *logit_bias) {
  332. // TODO: we may want to throw errors here, in case "el" is incorrect
  333. if (el.is_array() && el.size() == 2) {
  334. float bias;
  335. if (el[1].is_number()) {
  336. bias = el[1].get<float>();
  337. } else if (el[1].is_boolean() && !el[1].get<bool>()) {
  338. bias = -INFINITY;
  339. } else {
  340. continue;
  341. }
  342. if (el[0].is_number_integer()) {
  343. llama_token tok = el[0].get<llama_token>();
  344. if (tok >= 0 && tok < n_vocab) {
  345. params.sampling.logit_bias.push_back({tok, bias});
  346. }
  347. } else if (el[0].is_string()) {
  348. auto toks = common_tokenize(vocab, el[0].get<std::string>(), false);
  349. for (auto tok : toks) {
  350. params.sampling.logit_bias.push_back({tok, bias});
  351. }
  352. }
  353. }
  354. }
  355. } else if (logit_bias != data.end() && logit_bias->is_object()) {
  356. const int n_vocab = llama_vocab_n_tokens(vocab);
  357. for (const auto & el : logit_bias->items()) {
  358. float bias;
  359. const auto & key = el.key();
  360. const auto & value = el.value();
  361. if (value.is_number()) {
  362. bias = value.get<float>();
  363. } else if (value.is_boolean() && !value.get<bool>()) {
  364. bias = -INFINITY;
  365. } else {
  366. continue;
  367. }
  368. char *end;
  369. llama_token tok = strtol(key.c_str(), &end, 10);
  370. if (*end == 0) {
  371. if (tok >= 0 && tok < n_vocab) {
  372. params.sampling.logit_bias.push_back({tok, bias});
  373. }
  374. } else {
  375. auto toks = common_tokenize(vocab, key, false);
  376. for (auto tok : toks) {
  377. params.sampling.logit_bias.push_back({tok, bias});
  378. }
  379. }
  380. }
  381. }
  382. params.sampling.ignore_eos = json_value(data, "ignore_eos", params_base.sampling.ignore_eos);
  383. if (params.sampling.ignore_eos) {
  384. params.sampling.logit_bias.insert(
  385. params.sampling.logit_bias.end(),
  386. defaults.sampling.logit_bias_eog.begin(), defaults.sampling.logit_bias_eog.end());
  387. }
  388. }
  389. {
  390. params.antiprompt.clear();
  391. const auto & stop = data.find("stop");
  392. if (stop != data.end() && stop->is_array()) {
  393. for (const auto & word : *stop) {
  394. if (!word.empty()) {
  395. params.antiprompt.push_back(word);
  396. }
  397. }
  398. }
  399. // set reverse prompt from cli args if not set in the request
  400. if (params.antiprompt.empty()) {
  401. params.antiprompt = defaults.antiprompt;
  402. }
  403. }
  404. {
  405. const auto samplers = data.find("samplers");
  406. if (samplers != data.end()) {
  407. if (samplers->is_array()) {
  408. params.sampling.samplers = common_sampler_types_from_names(*samplers, false);
  409. } else if (samplers->is_string()){
  410. params.sampling.samplers = common_sampler_types_from_chars(samplers->get<std::string>());
  411. }
  412. } else {
  413. params.sampling.samplers = defaults.sampling.samplers;
  414. }
  415. }
  416. return params;
  417. }
  418. //
  419. // result_timings
  420. //
  421. json result_timings::to_json() const {
  422. json base = {
  423. {"cache_n", cache_n},
  424. {"prompt_n", prompt_n},
  425. {"prompt_ms", prompt_ms},
  426. {"prompt_per_token_ms", prompt_per_token_ms},
  427. {"prompt_per_second", prompt_per_second},
  428. {"predicted_n", predicted_n},
  429. {"predicted_ms", predicted_ms},
  430. {"predicted_per_token_ms", predicted_per_token_ms},
  431. {"predicted_per_second", predicted_per_second},
  432. };
  433. if (draft_n > 0) {
  434. base["draft_n"] = draft_n;
  435. base["draft_n_accepted"] = draft_n_accepted;
  436. }
  437. return base;
  438. }
  439. //
  440. // result_prompt_progress
  441. //
  442. json result_prompt_progress::to_json() const {
  443. return json {
  444. {"total", total},
  445. {"cache", cache},
  446. {"processed", processed},
  447. {"time_ms", time_ms},
  448. };
  449. }
  450. static inline std::string stop_type_to_str(stop_type type) {
  451. switch (type) {
  452. case STOP_TYPE_EOS: return "eos";
  453. case STOP_TYPE_WORD: return "word";
  454. case STOP_TYPE_LIMIT: return "limit";
  455. default: return "none";
  456. }
  457. }
  458. //
  459. // completion_token_output
  460. //
  461. json completion_token_output::to_json(bool post_sampling_probs) const {
  462. json probs_for_token = json::array();
  463. for (const auto & p : probs) {
  464. std::string txt(p.txt);
  465. txt.resize(validate_utf8(txt));
  466. probs_for_token.push_back(json {
  467. {"id", p.tok},
  468. {"token", txt},
  469. {"bytes", str_to_bytes(p.txt)},
  470. {
  471. post_sampling_probs ? "prob" : "logprob",
  472. post_sampling_probs ? p.prob : logarithm(p.prob)
  473. },
  474. });
  475. }
  476. return probs_for_token;
  477. }
  478. json completion_token_output::probs_vector_to_json(const std::vector<completion_token_output> & probs, bool post_sampling_probs) {
  479. json out = json::array();
  480. for (const auto & p : probs) {
  481. std::string txt(p.text_to_send);
  482. txt.resize(validate_utf8(txt));
  483. out.push_back(json {
  484. {"id", p.tok},
  485. {"token", txt},
  486. {"bytes", str_to_bytes(p.text_to_send)},
  487. {
  488. post_sampling_probs ? "prob" : "logprob",
  489. post_sampling_probs ? p.prob : logarithm(p.prob)
  490. },
  491. {
  492. post_sampling_probs ? "top_probs" : "top_logprobs",
  493. p.to_json(post_sampling_probs)
  494. },
  495. });
  496. }
  497. return out;
  498. }
  499. float completion_token_output::logarithm(float x) {
  500. // nlohmann::json converts -inf to null, so we need to prevent that
  501. return x == 0.0f ? std::numeric_limits<float>::lowest() : std::log(x);
  502. }
  503. std::vector<unsigned char> completion_token_output::str_to_bytes(const std::string & str) {
  504. std::vector<unsigned char> bytes;
  505. for (unsigned char c : str) {
  506. bytes.push_back(c);
  507. }
  508. return bytes;
  509. }
  510. //
  511. // server_task_result_cmpl_final
  512. //
  513. json server_task_result_cmpl_final::to_json() {
  514. GGML_ASSERT(is_updated && "update() must be called before to_json()");
  515. switch (res_type) {
  516. case TASK_RESPONSE_TYPE_NONE:
  517. return to_json_non_oaicompat();
  518. case TASK_RESPONSE_TYPE_OAI_CMPL:
  519. return to_json_oaicompat();
  520. case TASK_RESPONSE_TYPE_OAI_CHAT:
  521. return stream ? to_json_oaicompat_chat_stream() : to_json_oaicompat_chat();
  522. case TASK_RESPONSE_TYPE_ANTHROPIC:
  523. return stream ? to_json_anthropic_stream() : to_json_anthropic();
  524. default:
  525. GGML_ASSERT(false && "Invalid task_response_type");
  526. }
  527. }
  528. json server_task_result_cmpl_final::to_json_non_oaicompat() {
  529. json res = json {
  530. {"index", index},
  531. {"content", content},
  532. {"tokens", tokens},
  533. {"id_slot", id_slot},
  534. {"stop", true},
  535. {"model", oaicompat_model},
  536. {"tokens_predicted", n_decoded},
  537. {"tokens_evaluated", n_prompt_tokens},
  538. {"generation_settings", generation_params.to_json()},
  539. {"prompt", prompt},
  540. {"has_new_line", has_new_line},
  541. {"truncated", truncated},
  542. {"stop_type", stop_type_to_str(stop)},
  543. {"stopping_word", stopping_word},
  544. {"tokens_cached", n_tokens_cached},
  545. {"timings", timings.to_json()},
  546. };
  547. if (!stream && !probs_output.empty()) {
  548. res["completion_probabilities"] = completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs);
  549. }
  550. return response_fields.empty() ? res : json_get_nested_values(response_fields, res);
  551. }
  552. json server_task_result_cmpl_final::to_json_oaicompat() {
  553. std::time_t t = std::time(0);
  554. json logprobs = json(nullptr); // OAI default to null
  555. if (!stream && probs_output.size() > 0) {
  556. logprobs = json{
  557. {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
  558. };
  559. }
  560. json finish_reason = "length";
  561. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  562. finish_reason = "stop";
  563. }
  564. json res = json {
  565. {"choices", json::array({
  566. json{
  567. {"text", content},
  568. {"index", index},
  569. {"logprobs", logprobs},
  570. {"finish_reason", finish_reason},
  571. }
  572. })},
  573. {"created", t},
  574. {"model", oaicompat_model},
  575. {"system_fingerprint", build_info},
  576. {"object", "text_completion"},
  577. {"usage", json {
  578. {"completion_tokens", n_decoded},
  579. {"prompt_tokens", n_prompt_tokens},
  580. {"total_tokens", n_decoded + n_prompt_tokens}
  581. }},
  582. {"id", oaicompat_cmpl_id}
  583. };
  584. // extra fields for debugging purposes
  585. if (verbose) {
  586. res["__verbose"] = to_json_non_oaicompat();
  587. }
  588. if (timings.prompt_n >= 0) {
  589. res.push_back({"timings", timings.to_json()});
  590. }
  591. return res;
  592. }
  593. json server_task_result_cmpl_final::to_json_oaicompat_chat() {
  594. std::string finish_reason = "length";
  595. common_chat_msg msg;
  596. if (!oaicompat_msg.empty()) {
  597. msg = oaicompat_msg;
  598. } else {
  599. msg.role = "assistant";
  600. msg.content = content;
  601. }
  602. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  603. finish_reason = msg.tool_calls.empty() ? "stop" : "tool_calls";
  604. }
  605. json choice {
  606. {"finish_reason", finish_reason},
  607. {"index", 0},
  608. {"message", msg.to_json_oaicompat<json>()},
  609. };
  610. if (!stream && probs_output.size() > 0) {
  611. choice["logprobs"] = json{
  612. {"content", completion_token_output::probs_vector_to_json(probs_output, post_sampling_probs)},
  613. };
  614. }
  615. std::time_t t = std::time(0);
  616. json res = json {
  617. {"choices", json::array({choice})},
  618. {"created", t},
  619. {"model", oaicompat_model},
  620. {"system_fingerprint", build_info},
  621. {"object", "chat.completion"},
  622. {"usage", json {
  623. {"completion_tokens", n_decoded},
  624. {"prompt_tokens", n_prompt_tokens},
  625. {"total_tokens", n_decoded + n_prompt_tokens}
  626. }},
  627. {"id", oaicompat_cmpl_id}
  628. };
  629. // extra fields for debugging purposes
  630. if (verbose) {
  631. res["__verbose"] = to_json_non_oaicompat();
  632. }
  633. if (timings.prompt_n >= 0) {
  634. res.push_back({"timings", timings.to_json()});
  635. }
  636. return res;
  637. }
  638. common_chat_msg task_result_state::update_chat_msg(
  639. const std::string & text_added,
  640. bool is_partial,
  641. std::vector<common_chat_msg_diff> & diffs) {
  642. generated_text += text_added;
  643. auto msg_prv_copy = chat_msg;
  644. SRV_DBG("Parsing chat message: %s\n", generated_text.c_str());
  645. auto new_msg = common_chat_parse(
  646. generated_text,
  647. is_partial,
  648. oaicompat_chat_syntax);
  649. if (!new_msg.empty()) {
  650. new_msg.set_tool_call_ids(generated_tool_call_ids, gen_tool_call_id);
  651. chat_msg = new_msg;
  652. diffs = common_chat_msg_diff::compute_diffs(msg_prv_copy, new_msg.empty() ? msg_prv_copy : new_msg);
  653. }
  654. return chat_msg;
  655. }
  656. json server_task_result_cmpl_final::to_json_oaicompat_chat_stream() {
  657. std::time_t t = std::time(0);
  658. std::string finish_reason = "length";
  659. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  660. finish_reason = oaicompat_msg.tool_calls.empty() ? "stop" : "tool_calls";
  661. }
  662. json deltas = json::array();
  663. for (const auto & diff : oaicompat_msg_diffs) {
  664. deltas.push_back({
  665. {"choices", json::array({
  666. json {
  667. {"finish_reason", nullptr},
  668. {"index", 0},
  669. {"delta", common_chat_msg_diff_to_json_oaicompat<json>(diff)},
  670. },
  671. })},
  672. {"created", t},
  673. {"id", oaicompat_cmpl_id},
  674. {"model", oaicompat_model},
  675. {"system_fingerprint", build_info},
  676. {"object", "chat.completion.chunk"},
  677. });
  678. }
  679. deltas.push_back({
  680. {"choices", json::array({
  681. json {
  682. {"finish_reason", finish_reason},
  683. {"index", 0},
  684. {"delta", json::object()},
  685. },
  686. })},
  687. {"created", t},
  688. {"id", oaicompat_cmpl_id},
  689. {"model", oaicompat_model},
  690. {"system_fingerprint", build_info},
  691. {"object", "chat.completion.chunk"},
  692. });
  693. if (include_usage) {
  694. // OpenAI API spec for chat.completion.chunks specifies an empty `choices` array for the last chunk when including usage
  695. // https://platform.openai.com/docs/api-reference/chat_streaming/streaming#chat_streaming/streaming-choices
  696. deltas.push_back({
  697. {"choices", json::array()},
  698. {"created", t},
  699. {"id", oaicompat_cmpl_id},
  700. {"model", oaicompat_model},
  701. {"system_fingerprint", build_info},
  702. {"object", "chat.completion.chunk"},
  703. {"usage", json {
  704. {"completion_tokens", n_decoded},
  705. {"prompt_tokens", n_prompt_tokens},
  706. {"total_tokens", n_decoded + n_prompt_tokens},
  707. }},
  708. });
  709. }
  710. if (timings.prompt_n >= 0) {
  711. deltas.back().push_back({"timings", timings.to_json()});
  712. }
  713. // extra fields for debugging purposes
  714. if (verbose && !deltas.empty()) {
  715. deltas.front()["__verbose"] = to_json_non_oaicompat();
  716. }
  717. return deltas;
  718. }
  719. json server_task_result_cmpl_final::to_json_anthropic() {
  720. std::string stop_reason = "max_tokens";
  721. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  722. stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
  723. }
  724. json content_blocks = json::array();
  725. common_chat_msg msg;
  726. if (!oaicompat_msg.empty()) {
  727. msg = oaicompat_msg;
  728. } else {
  729. msg.role = "assistant";
  730. msg.content = content;
  731. }
  732. if (!msg.content.empty()) {
  733. content_blocks.push_back({
  734. {"type", "text"},
  735. {"text", msg.content}
  736. });
  737. }
  738. for (const auto & tool_call : msg.tool_calls) {
  739. json tool_use_block = {
  740. {"type", "tool_use"},
  741. {"id", tool_call.id},
  742. {"name", tool_call.name}
  743. };
  744. try {
  745. tool_use_block["input"] = json::parse(tool_call.arguments);
  746. } catch (const std::exception &) {
  747. tool_use_block["input"] = json::object();
  748. }
  749. content_blocks.push_back(tool_use_block);
  750. }
  751. json res = {
  752. {"id", oaicompat_cmpl_id},
  753. {"type", "message"},
  754. {"role", "assistant"},
  755. {"content", content_blocks},
  756. {"model", oaicompat_model},
  757. {"stop_reason", stop_reason},
  758. {"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)},
  759. {"usage", {
  760. {"input_tokens", n_prompt_tokens},
  761. {"output_tokens", n_decoded}
  762. }}
  763. };
  764. return res;
  765. }
  766. json server_task_result_cmpl_final::to_json_anthropic_stream() {
  767. json events = json::array();
  768. std::string stop_reason = "max_tokens";
  769. if (stop == STOP_TYPE_WORD || stop == STOP_TYPE_EOS) {
  770. stop_reason = oaicompat_msg.tool_calls.empty() ? "end_turn" : "tool_use";
  771. }
  772. bool has_text = !oaicompat_msg.content.empty();
  773. size_t num_tool_calls = oaicompat_msg.tool_calls.size();
  774. bool text_block_started = false;
  775. std::unordered_set<size_t> tool_calls_started;
  776. for (const auto & diff : oaicompat_msg_diffs) {
  777. if (!diff.content_delta.empty()) {
  778. if (!text_block_started) {
  779. events.push_back({
  780. {"event", "content_block_start"},
  781. {"data", {
  782. {"type", "content_block_start"},
  783. {"index", 0},
  784. {"content_block", {
  785. {"type", "text"},
  786. {"text", ""}
  787. }}
  788. }}
  789. });
  790. text_block_started = true;
  791. }
  792. events.push_back({
  793. {"event", "content_block_delta"},
  794. {"data", {
  795. {"type", "content_block_delta"},
  796. {"index", 0},
  797. {"delta", {
  798. {"type", "text_delta"},
  799. {"text", diff.content_delta}
  800. }}
  801. }}
  802. });
  803. }
  804. if (diff.tool_call_index != std::string::npos) {
  805. size_t content_block_index = (has_text ? 1 : 0) + diff.tool_call_index;
  806. if (tool_calls_started.find(diff.tool_call_index) == tool_calls_started.end()) {
  807. const auto & full_tool_call = oaicompat_msg.tool_calls[diff.tool_call_index];
  808. events.push_back({
  809. {"event", "content_block_start"},
  810. {"data", {
  811. {"type", "content_block_start"},
  812. {"index", content_block_index},
  813. {"content_block", {
  814. {"type", "tool_use"},
  815. {"id", full_tool_call.id},
  816. {"name", full_tool_call.name}
  817. }}
  818. }}
  819. });
  820. tool_calls_started.insert(diff.tool_call_index);
  821. }
  822. if (!diff.tool_call_delta.arguments.empty()) {
  823. events.push_back({
  824. {"event", "content_block_delta"},
  825. {"data", {
  826. {"type", "content_block_delta"},
  827. {"index", content_block_index},
  828. {"delta", {
  829. {"type", "input_json_delta"},
  830. {"partial_json", diff.tool_call_delta.arguments}
  831. }}
  832. }}
  833. });
  834. }
  835. }
  836. }
  837. if (has_text) {
  838. events.push_back({
  839. {"event", "content_block_stop"},
  840. {"data", {
  841. {"type", "content_block_stop"},
  842. {"index", 0}
  843. }}
  844. });
  845. }
  846. for (size_t i = 0; i < num_tool_calls; i++) {
  847. size_t content_block_index = (has_text ? 1 : 0) + i;
  848. events.push_back({
  849. {"event", "content_block_stop"},
  850. {"data", {
  851. {"type", "content_block_stop"},
  852. {"index", content_block_index}
  853. }}
  854. });
  855. }
  856. events.push_back({
  857. {"event", "message_delta"},
  858. {"data", {
  859. {"type", "message_delta"},
  860. {"delta", {
  861. {"stop_reason", stop_reason},
  862. {"stop_sequence", stopping_word.empty() ? nullptr : json(stopping_word)}
  863. }},
  864. {"usage", {
  865. {"output_tokens", n_decoded}
  866. }}
  867. }}
  868. });
  869. events.push_back({
  870. {"event", "message_stop"},
  871. {"data", {
  872. {"type", "message_stop"}
  873. }}
  874. });
  875. return events;
  876. }
  877. //
  878. // server_task_result_cmpl_partial
  879. //
  880. json server_task_result_cmpl_partial::to_json() {
  881. GGML_ASSERT(is_updated && "update() must be called before to_json()");
  882. switch (res_type) {
  883. case TASK_RESPONSE_TYPE_NONE:
  884. return to_json_non_oaicompat();
  885. case TASK_RESPONSE_TYPE_OAI_CMPL:
  886. return to_json_oaicompat();
  887. case TASK_RESPONSE_TYPE_OAI_CHAT:
  888. return to_json_oaicompat_chat();
  889. case TASK_RESPONSE_TYPE_ANTHROPIC:
  890. return to_json_anthropic();
  891. default:
  892. GGML_ASSERT(false && "Invalid task_response_type");
  893. }
  894. }
  895. json server_task_result_cmpl_partial::to_json_non_oaicompat() {
  896. // non-OAI-compat JSON
  897. json res = json {
  898. {"index", index},
  899. {"content", content},
  900. {"tokens", tokens},
  901. {"stop", false},
  902. {"id_slot", id_slot},
  903. {"tokens_predicted", n_decoded},
  904. {"tokens_evaluated", n_prompt_tokens},
  905. };
  906. // populate the timings object when needed (usually for the last response or with timings_per_token enabled)
  907. if (timings.prompt_n > 0) {
  908. res.push_back({"timings", timings.to_json()});
  909. }
  910. if (is_progress) {
  911. res.push_back({"prompt_progress", progress.to_json()});
  912. }
  913. if (!prob_output.probs.empty()) {
  914. res["completion_probabilities"] = completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs);
  915. }
  916. return res;
  917. }
  918. json server_task_result_cmpl_partial::to_json_oaicompat() {
  919. std::time_t t = std::time(0);
  920. json logprobs = json(nullptr); // OAI default to null
  921. if (prob_output.probs.size() > 0) {
  922. logprobs = json{
  923. {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
  924. };
  925. }
  926. json res = json {
  927. {"choices", json::array({
  928. json{
  929. {"text", content},
  930. {"index", index},
  931. {"logprobs", logprobs},
  932. {"finish_reason", nullptr},
  933. }
  934. })},
  935. {"created", t},
  936. {"model", oaicompat_model},
  937. {"system_fingerprint", build_info},
  938. {"object", "text_completion"},
  939. {"id", oaicompat_cmpl_id}
  940. };
  941. // extra fields for debugging purposes
  942. if (verbose) {
  943. res["__verbose"] = to_json_non_oaicompat();
  944. }
  945. if (timings.prompt_n >= 0) {
  946. res.push_back({"timings", timings.to_json()});
  947. }
  948. if (is_progress) {
  949. res.push_back({"prompt_progress", progress.to_json()});
  950. }
  951. return res;
  952. }
  953. json server_task_result_cmpl_partial::to_json_oaicompat_chat() {
  954. bool first = n_decoded == 1;
  955. std::time_t t = std::time(0);
  956. json choices;
  957. std::vector<json> deltas;
  958. auto add_delta = [&](const json & delta) {
  959. deltas.push_back({
  960. {"choices", json::array({
  961. json {
  962. {"finish_reason", nullptr},
  963. {"index", 0},
  964. {"delta", delta},
  965. },
  966. })},
  967. {"created", t},
  968. {"id", oaicompat_cmpl_id},
  969. {"model", oaicompat_model},
  970. {"system_fingerprint", build_info},
  971. {"object", "chat.completion.chunk"},
  972. });
  973. };
  974. // We have to send an initial update to conform to openai behavior
  975. if (first || is_progress) {
  976. add_delta({
  977. {"role", "assistant"},
  978. {"content", nullptr},
  979. });
  980. }
  981. for (const auto & diff : oaicompat_msg_diffs) {
  982. add_delta(common_chat_msg_diff_to_json_oaicompat<json>(diff));
  983. }
  984. if (!deltas.empty()) {
  985. auto & last_json = deltas[deltas.size() - 1];
  986. GGML_ASSERT(last_json.at("choices").size() >= 1);
  987. if (prob_output.probs.size() > 0) {
  988. last_json.at("choices").at(0)["logprobs"] = json {
  989. {"content", completion_token_output::probs_vector_to_json({prob_output}, post_sampling_probs)},
  990. };
  991. }
  992. if (timings.prompt_n >= 0) {
  993. last_json.push_back({"timings", timings.to_json()});
  994. }
  995. if (is_progress) {
  996. last_json.push_back({"prompt_progress", progress.to_json()});
  997. }
  998. }
  999. return deltas;
  1000. }
  1001. //
  1002. // server_task_result_embd
  1003. //
  1004. json server_task_result_embd::to_json() {
  1005. return res_type == TASK_RESPONSE_TYPE_OAI_EMBD
  1006. ? to_json_oaicompat()
  1007. : to_json_non_oaicompat();
  1008. }
  1009. json server_task_result_embd::to_json_non_oaicompat() {
  1010. return json {
  1011. {"index", index},
  1012. {"embedding", embedding},
  1013. };
  1014. }
  1015. json server_task_result_embd::to_json_oaicompat() {
  1016. return json {
  1017. {"index", index},
  1018. {"embedding", embedding[0]},
  1019. {"tokens_evaluated", n_tokens},
  1020. };
  1021. }
  1022. //
  1023. // server_task_result_rerank
  1024. //
  1025. json server_task_result_rerank::to_json() {
  1026. return json {
  1027. {"index", index},
  1028. {"score", score},
  1029. {"tokens_evaluated", n_tokens},
  1030. };
  1031. }
  1032. json server_task_result_cmpl_partial::to_json_anthropic() {
  1033. json events = json::array();
  1034. bool first = (n_decoded == 1);
  1035. static bool text_block_started = false;
  1036. if (first) {
  1037. text_block_started = false;
  1038. events.push_back({
  1039. {"event", "message_start"},
  1040. {"data", {
  1041. {"type", "message_start"},
  1042. {"message", {
  1043. {"id", oaicompat_cmpl_id},
  1044. {"type", "message"},
  1045. {"role", "assistant"},
  1046. {"content", json::array()},
  1047. {"model", oaicompat_model},
  1048. {"stop_reason", nullptr},
  1049. {"stop_sequence", nullptr},
  1050. {"usage", {
  1051. {"input_tokens", n_prompt_tokens},
  1052. {"output_tokens", 0}
  1053. }}
  1054. }}
  1055. }}
  1056. });
  1057. }
  1058. for (const auto & diff : oaicompat_msg_diffs) {
  1059. if (!diff.content_delta.empty()) {
  1060. if (!text_block_started) {
  1061. events.push_back({
  1062. {"event", "content_block_start"},
  1063. {"data", {
  1064. {"type", "content_block_start"},
  1065. {"index", 0},
  1066. {"content_block", {
  1067. {"type", "text"},
  1068. {"text", ""}
  1069. }}
  1070. }}
  1071. });
  1072. text_block_started = true;
  1073. }
  1074. events.push_back({
  1075. {"event", "content_block_delta"},
  1076. {"data", {
  1077. {"type", "content_block_delta"},
  1078. {"index", 0},
  1079. {"delta", {
  1080. {"type", "text_delta"},
  1081. {"text", diff.content_delta}
  1082. }}
  1083. }}
  1084. });
  1085. }
  1086. if (diff.tool_call_index != std::string::npos) {
  1087. size_t content_block_index = (text_block_started ? 1 : 0) + diff.tool_call_index;
  1088. if (!diff.tool_call_delta.name.empty()) {
  1089. events.push_back({
  1090. {"event", "content_block_start"},
  1091. {"data", {
  1092. {"type", "content_block_start"},
  1093. {"index", content_block_index},
  1094. {"content_block", {
  1095. {"type", "tool_use"},
  1096. {"id", diff.tool_call_delta.id},
  1097. {"name", diff.tool_call_delta.name}
  1098. }}
  1099. }}
  1100. });
  1101. }
  1102. if (!diff.tool_call_delta.arguments.empty()) {
  1103. events.push_back({
  1104. {"event", "content_block_delta"},
  1105. {"data", {
  1106. {"type", "content_block_delta"},
  1107. {"index", content_block_index},
  1108. {"delta", {
  1109. {"type", "input_json_delta"},
  1110. {"partial_json", diff.tool_call_delta.arguments}
  1111. }}
  1112. }}
  1113. });
  1114. }
  1115. }
  1116. }
  1117. return events;
  1118. }
  1119. //
  1120. // server_task_result_error
  1121. //
  1122. json server_task_result_error::to_json() {
  1123. json res = format_error_response(err_msg, err_type);
  1124. if (err_type == ERROR_TYPE_EXCEED_CONTEXT_SIZE) {
  1125. res["n_prompt_tokens"] = n_prompt_tokens;
  1126. res["n_ctx"] = n_ctx;
  1127. }
  1128. return res;
  1129. }
  1130. //
  1131. // server_task_result_metrics
  1132. //
  1133. json server_task_result_metrics::to_json() {
  1134. return json {
  1135. { "idle", n_idle_slots },
  1136. { "processing", n_processing_slots },
  1137. { "deferred", n_tasks_deferred },
  1138. { "t_start", t_start },
  1139. { "n_prompt_tokens_processed_total", n_prompt_tokens_processed_total },
  1140. { "t_tokens_generation_total", t_tokens_generation_total },
  1141. { "n_tokens_predicted_total", n_tokens_predicted_total },
  1142. { "t_prompt_processing_total", t_prompt_processing_total },
  1143. { "n_tokens_max", n_tokens_max },
  1144. { "n_prompt_tokens_processed", n_prompt_tokens_processed },
  1145. { "t_prompt_processing", t_prompt_processing },
  1146. { "n_tokens_predicted", n_tokens_predicted },
  1147. { "t_tokens_generation", t_tokens_generation },
  1148. { "n_decode_total", n_decode_total },
  1149. { "n_busy_slots_total", n_busy_slots_total },
  1150. { "slots", slots_data },
  1151. };
  1152. }
  1153. //
  1154. // server_task_result_slot_save_load
  1155. //
  1156. json server_task_result_slot_save_load::to_json() {
  1157. if (is_save) {
  1158. return json {
  1159. { "id_slot", id_slot },
  1160. { "filename", filename },
  1161. { "n_saved", n_tokens },
  1162. { "n_written", n_bytes },
  1163. { "timings", {
  1164. { "save_ms", t_ms }
  1165. }},
  1166. };
  1167. }
  1168. return json {
  1169. { "id_slot", id_slot },
  1170. { "filename", filename },
  1171. { "n_restored", n_tokens },
  1172. { "n_read", n_bytes },
  1173. { "timings", {
  1174. { "restore_ms", t_ms }
  1175. }},
  1176. };
  1177. }
  1178. //
  1179. // server_task_result_slot_erase
  1180. //
  1181. json server_task_result_slot_erase::to_json() {
  1182. return json {
  1183. { "id_slot", id_slot },
  1184. { "n_erased", n_erased },
  1185. };
  1186. }
  1187. //
  1188. // server_task_result_apply_lora
  1189. //
  1190. json server_task_result_apply_lora::to_json() {
  1191. return json {{ "success", true }};
  1192. }
  1193. //
  1194. // server_prompt_cache
  1195. //
  1196. size_t server_prompt_cache::size() const {
  1197. size_t res = 0;
  1198. for (const auto & state : states) {
  1199. res += state.size();
  1200. }
  1201. return res;
  1202. }
  1203. size_t server_prompt_cache::n_tokens() const {
  1204. size_t res = 0;
  1205. for (const auto & state : states) {
  1206. res += state.n_tokens();
  1207. }
  1208. return res;
  1209. }
  1210. server_prompt * server_prompt_cache::alloc(const server_prompt & prompt, size_t state_size) {
  1211. // first check if the current state is contained fully in the cache
  1212. for (auto it = states.begin(); it != states.end(); ++it) {
  1213. const int cur_lcp_len = it->tokens.get_common_prefix(prompt.tokens);
  1214. if (cur_lcp_len == (int) prompt.tokens.size()) {
  1215. SRV_WRN("%s", " - prompt is already in the cache, skipping\n");
  1216. return nullptr;
  1217. }
  1218. }
  1219. // next, remove any cached prompts that are fully contained in the current prompt
  1220. for (auto it = states.begin(); it != states.end();) {
  1221. const int len = it->tokens.get_common_prefix(prompt.tokens);
  1222. if (len == (int) it->tokens.size()) {
  1223. SRV_WRN(" - removing obsolete cached prompt with length %d\n", len);
  1224. it = states.erase(it);
  1225. } else {
  1226. ++it;
  1227. }
  1228. }
  1229. std::vector<uint8_t> state_data;
  1230. // check if we can allocate enough memory for the new state
  1231. try {
  1232. state_data.resize(state_size);
  1233. } catch (const std::bad_alloc & e) {
  1234. SRV_ERR("failed to allocate memory for prompt cache state: %s\n", e.what());
  1235. limit_size = std::max<size_t>(1, 0.4*size());
  1236. SRV_WRN(" - cache size limit reduced to %.3f MiB\n", limit_size / (1024.0 * 1024.0));
  1237. update();
  1238. return nullptr;
  1239. }
  1240. // TODO: for some reason we can't copy server_tokens, so we have to do this workaround
  1241. auto & cur = states.emplace_back();
  1242. cur = {
  1243. /*.tokens =*/ server_tokens(prompt.tokens.get_text_tokens(), false),
  1244. /*.data =*/ std::move(state_data),
  1245. /*.checkpoints =*/ prompt.checkpoints,
  1246. };
  1247. return &cur;
  1248. }
  1249. bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, llama_context * ctx, int32_t id_slot) {
  1250. const int lcp_best = prompt.tokens.get_common_prefix(tokens_new);
  1251. float f_keep_best = float(lcp_best) / prompt.tokens.size();
  1252. float sim_best = float(lcp_best) / tokens_new.size();
  1253. SRV_WRN(" - looking for better prompt, base f_keep = %.3f, sim = %.3f\n", f_keep_best, sim_best);
  1254. auto it_best = states.end();
  1255. // find the most similar cached prompt, that would also preserve the most context
  1256. for (auto it = states.begin(); it != states.end(); ++it) {
  1257. const int lcp_cur = it->tokens.get_common_prefix(tokens_new);
  1258. const float f_keep_cur = float(lcp_cur) / it->tokens.size();
  1259. const float sim_cur = float(lcp_cur) / tokens_new.size();
  1260. // don't trash large prompts
  1261. if (f_keep_cur < 0.25f) {
  1262. continue;
  1263. }
  1264. if (f_keep_best < f_keep_cur && sim_best < sim_cur) {
  1265. f_keep_best = f_keep_cur;
  1266. sim_best = sim_cur;
  1267. it_best = it;
  1268. }
  1269. }
  1270. if (it_best != states.end()) {
  1271. SRV_WRN(" - found better prompt with f_keep = %.3f, sim = %.3f\n", f_keep_best, sim_best);
  1272. const size_t size = it_best->data.size();
  1273. const size_t n = llama_state_seq_set_data_ext(ctx, it_best->data.data(), size, id_slot, 0);
  1274. if (n != size) {
  1275. SRV_WRN("failed to restore state with size %zu\n", size);
  1276. return false;
  1277. }
  1278. it_best->data.clear();
  1279. it_best->data.shrink_to_fit();
  1280. prompt = std::move(*it_best);
  1281. states.erase(it_best);
  1282. }
  1283. return true;
  1284. }
  1285. void server_prompt_cache::update() {
  1286. if (limit_size > 0) {
  1287. // always keep at least one state, regardless of the limits
  1288. while (states.size() > 1 && size() > limit_size) {
  1289. if (states.empty()) {
  1290. break;
  1291. }
  1292. SRV_WRN(" - cache size limit reached, removing oldest entry (size = %.3f MiB)\n", states.front().size() / (1024.0 * 1024.0));
  1293. states.pop_front();
  1294. }
  1295. }
  1296. // average size per token
  1297. const float size_per_token = std::max<float>(1.0f, float(size()) / (std::max<size_t>(1, n_tokens())));
  1298. // dynamically increase the token limit if it can fit in the memory limit
  1299. const size_t limit_tokens_cur = limit_size > 0 ? std::max<size_t>(limit_tokens, limit_size/size_per_token) : limit_tokens;
  1300. if (limit_tokens > 0) {
  1301. while (states.size() > 1 && n_tokens() > limit_tokens_cur) {
  1302. if (states.empty()) {
  1303. break;
  1304. }
  1305. SRV_WRN(" - cache token limit (%zu, est: %zu) reached, removing oldest entry (size = %.3f MiB)\n",
  1306. limit_tokens, limit_tokens_cur, states.front().size() / (1024.0 * 1024.0));
  1307. states.pop_front();
  1308. }
  1309. }
  1310. SRV_WRN(" - cache state: %zu prompts, %.3f MiB (limits: %.3f MiB, %zu tokens, %zu est)\n",
  1311. states.size(), size() / (1024.0 * 1024.0), limit_size / (1024.0 * 1024.0), limit_tokens, limit_tokens_cur);
  1312. for (const auto & state : states) {
  1313. SRV_WRN(" - prompt %p: %7d tokens, checkpoints: %2zu, %9.3f MiB\n",
  1314. (const void *)&state, state.n_tokens(), state.checkpoints.size(), state.size() / (1024.0 * 1024.0));
  1315. }
  1316. }