server.cpp 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  1. #include "common.h"
  2. #include "llama.h"
  3. #include "build-info.h"
  4. #ifndef NDEBUG
  5. // crash the server in debug mode, otherwise send an http 500 error
  6. #define CPPHTTPLIB_NO_EXCEPTIONS 1
  7. #endif
  8. #include "httplib.h"
  9. #include "json.hpp"
  10. // auto generated files (update with ./deps.sh)
  11. #include "index.html.hpp"
  12. #include "index.js.hpp"
  13. #include "completion.js.hpp"
  14. #ifndef SERVER_VERBOSE
  15. #define SERVER_VERBOSE 1
  16. #endif
  17. using namespace httplib;
  18. using json = nlohmann::json;
  19. struct server_params
  20. {
  21. std::string hostname = "127.0.0.1";
  22. std::string public_path = "examples/server/public";
  23. int32_t port = 8080;
  24. int32_t read_timeout = 600;
  25. int32_t write_timeout = 600;
  26. };
  27. // completion token output with probabilities
  28. struct completion_token_output
  29. {
  30. struct token_prob
  31. {
  32. llama_token tok;
  33. float prob;
  34. };
  35. std::vector<token_prob> probs;
  36. llama_token tok;
  37. };
  38. static size_t common_part(const std::vector<llama_token> &a, const std::vector<llama_token> &b)
  39. {
  40. size_t i;
  41. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++)
  42. {
  43. }
  44. return i;
  45. }
  46. enum stop_type
  47. {
  48. STOP_FULL,
  49. STOP_PARTIAL,
  50. };
  51. static bool ends_with(const std::string &str, const std::string &suffix)
  52. {
  53. return str.size() >= suffix.size() &&
  54. 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
  55. }
  56. static size_t find_partial_stop_string(const std::string &stop,
  57. const std::string &text)
  58. {
  59. if (!text.empty() && !stop.empty())
  60. {
  61. const char text_last_char = text.back();
  62. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--)
  63. {
  64. if (stop[char_index] == text_last_char)
  65. {
  66. const std::string current_partial = stop.substr(0, char_index + 1);
  67. if (ends_with(text, current_partial))
  68. {
  69. return text.size() - char_index - 1;
  70. }
  71. }
  72. }
  73. }
  74. return std::string::npos;
  75. }
  76. template <class Iter>
  77. static std::string tokens_to_str(llama_context *ctx, Iter begin, Iter end)
  78. {
  79. std::string ret;
  80. for (; begin != end; ++begin)
  81. {
  82. ret += llama_token_to_str(ctx, *begin);
  83. }
  84. return ret;
  85. }
  86. static void server_log(const char *level, const char *function, int line,
  87. const char *message, const nlohmann::ordered_json &extra)
  88. {
  89. nlohmann::ordered_json log{
  90. {"timestamp", time(nullptr)},
  91. {"level", level},
  92. {"function", function},
  93. {"line", line},
  94. {"message", message},
  95. };
  96. if (!extra.empty())
  97. {
  98. log.merge_patch(extra);
  99. }
  100. const std::string str = log.dump(-1, ' ', false, json::error_handler_t::replace);
  101. fprintf(stdout, "%.*s\n", (int)str.size(), str.data());
  102. fflush(stdout);
  103. }
  104. // format incomplete utf-8 multibyte character for output
  105. static std::string tokens_to_output_formatted_string(const llama_context *ctx, const llama_token token)
  106. {
  107. std::string out = token == -1 ? "" : llama_token_to_str(ctx, token);
  108. // if first bit is 1, meaning it's a partial character
  109. if (out.size() > 0 && (out[0] & 0x80) == 0x80)
  110. {
  111. std::stringstream ss;
  112. ss << std::hex << (out[0] & 0xff);
  113. std::string res(ss.str());
  114. out = "byte: \\x" + res;
  115. }
  116. return out;
  117. }
  118. // convert a vector of completion_token_output to json
  119. static json probs_vector_to_json(const llama_context *ctx, const std::vector<completion_token_output> probs)
  120. {
  121. json out = json::array();
  122. for (const auto &prob : probs)
  123. {
  124. json probs_for_token = json::array();
  125. for (const auto &p : prob.probs)
  126. {
  127. std::string tok_str = tokens_to_output_formatted_string(ctx, p.tok);
  128. probs_for_token.push_back(json{
  129. {"tok_str", tok_str},
  130. {"prob", p.prob},
  131. });
  132. }
  133. std::string tok_str = tokens_to_output_formatted_string(ctx, prob.tok);
  134. out.push_back(json{
  135. {"content", tok_str},
  136. {"probs", probs_for_token},
  137. });
  138. }
  139. return out;
  140. }
  141. static bool server_verbose = false;
  142. #if SERVER_VERBOSE != 1
  143. #define LOG_VERBOSE(MSG, ...)
  144. #else
  145. #define LOG_VERBOSE(MSG, ...) \
  146. do \
  147. { \
  148. if (server_verbose) \
  149. { \
  150. server_log("VERBOSE", __func__, __LINE__, MSG, __VA_ARGS__); \
  151. } \
  152. } while (0)
  153. #endif
  154. #define LOG_ERROR(MSG, ...) server_log("ERROR", __func__, __LINE__, MSG, __VA_ARGS__)
  155. #define LOG_WARNING(MSG, ...) server_log("WARNING", __func__, __LINE__, MSG, __VA_ARGS__)
  156. #define LOG_INFO(MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
  157. struct llama_server_context
  158. {
  159. bool stream = false;
  160. bool has_next_token = false;
  161. std::string generated_text;
  162. std::vector<completion_token_output> generated_token_probs;
  163. size_t num_prompt_tokens = 0;
  164. size_t num_tokens_predicted = 0;
  165. size_t n_past = 0;
  166. size_t n_remain = 0;
  167. std::vector<llama_token> embd;
  168. std::vector<llama_token> last_n_tokens;
  169. llama_model *model = nullptr;
  170. llama_context *ctx = nullptr;
  171. gpt_params params;
  172. bool truncated = false;
  173. bool stopped_eos = false;
  174. bool stopped_word = false;
  175. bool stopped_limit = false;
  176. std::string stopping_word;
  177. int32_t multibyte_pending = 0;
  178. std::mutex mutex;
  179. std::unique_lock<std::mutex> lock()
  180. {
  181. return std::unique_lock<std::mutex>(mutex);
  182. }
  183. ~llama_server_context()
  184. {
  185. if (ctx)
  186. {
  187. llama_free(ctx);
  188. ctx = nullptr;
  189. }
  190. if (model)
  191. {
  192. llama_free_model(model);
  193. model = nullptr;
  194. }
  195. }
  196. void rewind()
  197. {
  198. params.antiprompt.clear();
  199. num_prompt_tokens = 0;
  200. num_tokens_predicted = 0;
  201. generated_text = "";
  202. generated_text.reserve(params.n_ctx);
  203. generated_token_probs.clear();
  204. truncated = false;
  205. stopped_eos = false;
  206. stopped_word = false;
  207. stopped_limit = false;
  208. stopping_word = "";
  209. multibyte_pending = 0;
  210. n_remain = 0;
  211. n_past = 0;
  212. }
  213. bool loadModel(const gpt_params &params_)
  214. {
  215. params = params_;
  216. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  217. if (model == nullptr)
  218. {
  219. LOG_ERROR("unable to load model", {{"model", params_.model}});
  220. return false;
  221. }
  222. last_n_tokens.resize(params.n_ctx);
  223. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  224. return true;
  225. }
  226. void loadPrompt()
  227. {
  228. params.prompt.insert(0, 1, ' '); // always add a first space
  229. std::vector<llama_token> prompt_tokens = ::llama_tokenize(ctx, params.prompt, true);
  230. num_prompt_tokens = prompt_tokens.size();
  231. if (params.n_keep < 0)
  232. {
  233. params.n_keep = (int)num_prompt_tokens;
  234. }
  235. params.n_keep = std::min(params.n_ctx - 4, params.n_keep);
  236. // if input prompt is too big, truncate like normal
  237. if (num_prompt_tokens >= (size_t)params.n_ctx)
  238. {
  239. const int n_left = (params.n_ctx - params.n_keep) / 2;
  240. std::vector<llama_token> new_tokens(prompt_tokens.begin(), prompt_tokens.begin() + params.n_keep);
  241. const int erased_blocks = (num_prompt_tokens - params.n_keep - n_left - 1) / n_left;
  242. new_tokens.insert(new_tokens.end(), prompt_tokens.begin() + params.n_keep + erased_blocks * n_left, prompt_tokens.end());
  243. std::copy(prompt_tokens.end() - params.n_ctx, prompt_tokens.end(), last_n_tokens.begin());
  244. LOG_VERBOSE("input truncated", {
  245. {"n_ctx", params.n_ctx},
  246. {"n_keep", params.n_keep},
  247. {"n_left", n_left},
  248. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  249. });
  250. truncated = true;
  251. prompt_tokens = new_tokens;
  252. }
  253. else
  254. {
  255. const size_t ps = num_prompt_tokens;
  256. std::fill(last_n_tokens.begin(), last_n_tokens.end() - ps, 0);
  257. std::copy(prompt_tokens.begin(), prompt_tokens.end(), last_n_tokens.end() - ps);
  258. }
  259. // compare the evaluated prompt with the new prompt
  260. n_past = common_part(embd, prompt_tokens);
  261. embd = prompt_tokens;
  262. if (n_past == num_prompt_tokens)
  263. {
  264. // we have to evaluate at least 1 token to generate logits.
  265. n_past--;
  266. }
  267. LOG_VERBOSE("prompt ingested", {
  268. {"n_past", n_past},
  269. {"cached", tokens_to_str(ctx, embd.cbegin(), embd.cbegin() + n_past)},
  270. {"to_eval", tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend())},
  271. });
  272. has_next_token = true;
  273. }
  274. void beginCompletion()
  275. {
  276. // number of tokens to keep when resetting context
  277. n_remain = params.n_predict;
  278. llama_set_rng_seed(ctx, params.seed);
  279. }
  280. completion_token_output nextToken()
  281. {
  282. completion_token_output result;
  283. result.tok = -1;
  284. if (embd.size() >= (size_t)params.n_ctx)
  285. {
  286. // Reset context
  287. const int n_left = (params.n_ctx - params.n_keep) / 2;
  288. std::vector<llama_token> new_tokens(embd.begin(), embd.begin() + params.n_keep);
  289. new_tokens.insert(new_tokens.end(), embd.end() - n_left, embd.end());
  290. embd = new_tokens;
  291. n_past = params.n_keep;
  292. truncated = true;
  293. LOG_VERBOSE("input truncated", {
  294. {"n_ctx", params.n_ctx},
  295. {"n_keep", params.n_keep},
  296. {"n_left", n_left},
  297. {"new_tokens", tokens_to_str(ctx, new_tokens.cbegin(), new_tokens.cend())},
  298. });
  299. }
  300. while (n_past < embd.size())
  301. {
  302. int n_eval = (int)embd.size() - n_past;
  303. if (n_eval > params.n_batch)
  304. {
  305. n_eval = params.n_batch;
  306. }
  307. if (llama_eval(ctx, &embd[n_past], n_eval, n_past, params.n_threads))
  308. {
  309. LOG_ERROR("failed to eval", {
  310. {"n_eval", n_eval},
  311. {"n_past", n_past},
  312. {"n_threads", params.n_threads},
  313. {"embd", tokens_to_str(ctx, embd.cbegin() + n_past, embd.cend())},
  314. });
  315. has_next_token = false;
  316. return result;
  317. }
  318. n_past += n_eval;
  319. }
  320. if (params.n_predict == 0)
  321. {
  322. has_next_token = false;
  323. result.tok = llama_token_eos();
  324. return result;
  325. }
  326. // out of user input, sample next token
  327. const float temp = params.temp;
  328. const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  329. const float top_p = params.top_p;
  330. const float tfs_z = params.tfs_z;
  331. const float typical_p = params.typical_p;
  332. const int32_t repeat_last_n = params.repeat_last_n < 0 ? params.n_ctx : params.repeat_last_n;
  333. const float repeat_penalty = params.repeat_penalty;
  334. const float alpha_presence = params.presence_penalty;
  335. const float alpha_frequency = params.frequency_penalty;
  336. const int mirostat = params.mirostat;
  337. const float mirostat_tau = params.mirostat_tau;
  338. const float mirostat_eta = params.mirostat_eta;
  339. const bool penalize_nl = params.penalize_nl;
  340. const int32_t n_probs = params.n_probs;
  341. {
  342. auto *logits = llama_get_logits(ctx);
  343. auto n_vocab = llama_n_vocab(ctx);
  344. // Apply params.logit_bias map
  345. for (const auto &it : params.logit_bias)
  346. {
  347. logits[it.first] += it.second;
  348. }
  349. std::vector<llama_token_data> candidates;
  350. candidates.reserve(n_vocab);
  351. for (llama_token token_id = 0; token_id < n_vocab; token_id++)
  352. {
  353. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  354. }
  355. llama_token_data_array candidates_p = {candidates.data(), candidates.size(), false};
  356. // Apply penalties
  357. float nl_logit = logits[llama_token_nl()];
  358. auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), params.n_ctx);
  359. llama_sample_repetition_penalty(ctx, &candidates_p,
  360. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  361. last_n_repeat, repeat_penalty);
  362. llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
  363. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  364. last_n_repeat, alpha_frequency, alpha_presence);
  365. if (!penalize_nl)
  366. {
  367. logits[llama_token_nl()] = nl_logit;
  368. }
  369. if (temp <= 0)
  370. {
  371. // Greedy sampling
  372. result.tok = llama_sample_token_greedy(ctx, &candidates_p);
  373. if (n_probs > 0)
  374. {
  375. llama_sample_softmax(ctx, &candidates_p);
  376. }
  377. }
  378. else
  379. {
  380. if (mirostat == 1)
  381. {
  382. static float mirostat_mu = 2.0f * mirostat_tau;
  383. const int mirostat_m = 100;
  384. llama_sample_temperature(ctx, &candidates_p, temp);
  385. result.tok = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  386. }
  387. else if (mirostat == 2)
  388. {
  389. static float mirostat_mu = 2.0f * mirostat_tau;
  390. llama_sample_temperature(ctx, &candidates_p, temp);
  391. result.tok = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  392. }
  393. else
  394. {
  395. // Temperature sampling
  396. size_t min_keep = std::max(1, n_probs);
  397. llama_sample_top_k(ctx, &candidates_p, top_k, min_keep);
  398. llama_sample_tail_free(ctx, &candidates_p, tfs_z, min_keep);
  399. llama_sample_typical(ctx, &candidates_p, typical_p, min_keep);
  400. llama_sample_top_p(ctx, &candidates_p, top_p, min_keep);
  401. llama_sample_temperature(ctx, &candidates_p, temp);
  402. result.tok = llama_sample_token(ctx, &candidates_p);
  403. }
  404. }
  405. for (size_t i = 0; i < std::min(candidates_p.size, (size_t)n_probs); ++i)
  406. {
  407. result.probs.push_back({candidates_p.data[i].id, candidates_p.data[i].p});
  408. }
  409. last_n_tokens.erase(last_n_tokens.begin());
  410. last_n_tokens.push_back(result.tok);
  411. num_tokens_predicted++;
  412. }
  413. // add it to the context
  414. embd.push_back(result.tok);
  415. // decrement remaining sampling budget
  416. --n_remain;
  417. if (!embd.empty() && embd.back() == llama_token_eos())
  418. {
  419. // stopping_word = llama_token_to_str(ctx, embd.back());
  420. has_next_token = false;
  421. stopped_eos = true;
  422. LOG_VERBOSE("eos token found", {});
  423. return result;
  424. }
  425. has_next_token = params.n_predict == -1 || n_remain != 0;
  426. return result;
  427. }
  428. size_t findStoppingStrings(const std::string &text, const size_t last_token_size,
  429. const stop_type type)
  430. {
  431. size_t stop_pos = std::string::npos;
  432. for (const std::string &word : params.antiprompt)
  433. {
  434. size_t pos;
  435. if (type == STOP_FULL)
  436. {
  437. const size_t tmp = word.size() + last_token_size;
  438. const size_t from_pos = text.size() > tmp ? text.size() - tmp : 0;
  439. pos = text.find(word, from_pos);
  440. }
  441. else
  442. {
  443. pos = find_partial_stop_string(word, text);
  444. }
  445. if (pos != std::string::npos &&
  446. (stop_pos == std::string::npos || pos < stop_pos))
  447. {
  448. if (type == STOP_FULL)
  449. {
  450. stopping_word = word;
  451. stopped_word = true;
  452. has_next_token = false;
  453. }
  454. stop_pos = pos;
  455. }
  456. }
  457. return stop_pos;
  458. }
  459. completion_token_output doCompletion()
  460. {
  461. const completion_token_output token_with_probs = nextToken();
  462. const std::string token_text = token_with_probs.tok == -1 ? "" : llama_token_to_str(ctx, token_with_probs.tok);
  463. generated_text += token_text;
  464. if (params.n_probs > 0)
  465. {
  466. generated_token_probs.push_back(token_with_probs);
  467. }
  468. if (multibyte_pending > 0)
  469. {
  470. multibyte_pending -= token_text.size();
  471. }
  472. else if (token_text.size() == 1)
  473. {
  474. const char c = token_text[0];
  475. // 2-byte characters: 110xxxxx 10xxxxxx
  476. if ((c & 0xE0) == 0xC0)
  477. {
  478. multibyte_pending = 1;
  479. // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
  480. }
  481. else if ((c & 0xF0) == 0xE0)
  482. {
  483. multibyte_pending = 2;
  484. // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  485. }
  486. else if ((c & 0xF8) == 0xF0)
  487. {
  488. multibyte_pending = 3;
  489. }
  490. else
  491. {
  492. multibyte_pending = 0;
  493. }
  494. }
  495. if (multibyte_pending > 0 && !has_next_token)
  496. {
  497. has_next_token = true;
  498. n_remain++;
  499. }
  500. if (!has_next_token && n_remain == 0)
  501. {
  502. stopped_limit = true;
  503. }
  504. LOG_VERBOSE("next token", {
  505. {"token", token_with_probs.tok},
  506. {"token_text", tokens_to_output_formatted_string(ctx, token_with_probs.tok)},
  507. {"has_next_token", has_next_token},
  508. {"n_remain", n_remain},
  509. {"num_tokens_predicted", num_tokens_predicted},
  510. {"stopped_eos", stopped_eos},
  511. {"stopped_word", stopped_word},
  512. {"stopped_limit", stopped_limit},
  513. {"stopping_word", stopping_word},
  514. });
  515. return token_with_probs;
  516. }
  517. std::vector<float> getEmbedding()
  518. {
  519. static const int n_embd = llama_n_embd(ctx);
  520. if (!params.embedding)
  521. {
  522. LOG_WARNING("embedding disabled", {
  523. {"params.embedding", params.embedding},
  524. });
  525. return std::vector<float>(n_embd, 0.0f);
  526. }
  527. const float *data = llama_get_embeddings(ctx);
  528. std::vector<float> embedding(data, data + n_embd);
  529. return embedding;
  530. }
  531. };
  532. static void server_print_usage(const char *argv0, const gpt_params &params,
  533. const server_params &sparams)
  534. {
  535. fprintf(stderr, "usage: %s [options]\n", argv0);
  536. fprintf(stderr, "\n");
  537. fprintf(stderr, "options:\n");
  538. fprintf(stderr, " -h, --help show this help message and exit\n");
  539. fprintf(stderr, " -v, --verbose verbose output (default: %s)\n", server_verbose ? "enabled" : "disabled");
  540. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  541. fprintf(stderr, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  542. fprintf(stderr, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  543. fprintf(stderr, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  544. fprintf(stderr, " not recommended: doubles context memory required and no measurable increase in quality\n");
  545. if (llama_mlock_supported())
  546. {
  547. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  548. }
  549. if (llama_mmap_supported())
  550. {
  551. fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  552. }
  553. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  554. fprintf(stderr, " -ngl N, --n-gpu-layers N\n");
  555. fprintf(stderr, " number of layers to store in VRAM\n");
  556. fprintf(stderr, " -ts SPLIT --tensor-split SPLIT\n");
  557. fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  558. fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  559. fprintf(stderr, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n");
  560. fprintf(stderr, " -lv, --low-vram don't allocate VRAM scratch buffer\n");
  561. #endif
  562. fprintf(stderr, " -m FNAME, --model FNAME\n");
  563. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  564. fprintf(stderr, " -a ALIAS, --alias ALIAS\n");
  565. fprintf(stderr, " set an alias for the model, will be added as `model` field in completion response\n");
  566. fprintf(stderr, " --lora FNAME apply LoRA adapter\n");
  567. fprintf(stderr, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  568. fprintf(stderr, " --host ip address to listen (default (default: %s)\n", sparams.hostname.c_str());
  569. fprintf(stderr, " --port PORT port to listen (default (default: %d)\n", sparams.port);
  570. fprintf(stderr, " --path PUBLIC_PATH path from which to serve static files (default %s)\n", sparams.public_path.c_str());
  571. fprintf(stderr, " -to N, --timeout N server read/write timeout in seconds (default: %d)\n", sparams.read_timeout);
  572. fprintf(stderr, " --embedding enable embedding vector output (default: %s)\n", params.embedding ? "enabled" : "disabled");
  573. fprintf(stderr, "\n");
  574. }
  575. static void server_params_parse(int argc, char **argv, server_params &sparams,
  576. gpt_params &params)
  577. {
  578. gpt_params default_params;
  579. server_params default_sparams;
  580. std::string arg;
  581. bool invalid_param = false;
  582. for (int i = 1; i < argc; i++)
  583. {
  584. arg = argv[i];
  585. if (arg == "--port")
  586. {
  587. if (++i >= argc)
  588. {
  589. invalid_param = true;
  590. break;
  591. }
  592. sparams.port = std::stoi(argv[i]);
  593. }
  594. else if (arg == "--host")
  595. {
  596. if (++i >= argc)
  597. {
  598. invalid_param = true;
  599. break;
  600. }
  601. sparams.hostname = argv[i];
  602. }
  603. else if (arg == "--path")
  604. {
  605. if (++i >= argc)
  606. {
  607. invalid_param = true;
  608. break;
  609. }
  610. sparams.public_path = argv[i];
  611. }
  612. else if (arg == "--timeout" || arg == "-to")
  613. {
  614. if (++i >= argc)
  615. {
  616. invalid_param = true;
  617. break;
  618. }
  619. sparams.read_timeout = std::stoi(argv[i]);
  620. sparams.write_timeout = std::stoi(argv[i]);
  621. }
  622. else if (arg == "-m" || arg == "--model")
  623. {
  624. if (++i >= argc)
  625. {
  626. invalid_param = true;
  627. break;
  628. }
  629. params.model = argv[i];
  630. }
  631. else if (arg == "-a" || arg == "--alias")
  632. {
  633. if (++i >= argc)
  634. {
  635. invalid_param = true;
  636. break;
  637. }
  638. params.model_alias = argv[i];
  639. }
  640. else if (arg == "-h" || arg == "--help")
  641. {
  642. server_print_usage(argv[0], default_params, default_sparams);
  643. exit(0);
  644. }
  645. else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size")
  646. {
  647. if (++i >= argc)
  648. {
  649. invalid_param = true;
  650. break;
  651. }
  652. params.n_ctx = std::stoi(argv[i]);
  653. }
  654. else if (arg == "--memory-f32" || arg == "--memory_f32")
  655. {
  656. params.memory_f16 = false;
  657. }
  658. else if (arg == "--threads" || arg == "-t")
  659. {
  660. if (++i >= argc)
  661. {
  662. invalid_param = true;
  663. break;
  664. }
  665. params.n_threads = std::stoi(argv[i]);
  666. }
  667. else if (arg == "-b" || arg == "--batch-size")
  668. {
  669. if (++i >= argc)
  670. {
  671. invalid_param = true;
  672. break;
  673. }
  674. params.n_batch = std::stoi(argv[i]);
  675. params.n_batch = std::min(512, params.n_batch);
  676. }
  677. else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
  678. {
  679. if (++i >= argc)
  680. {
  681. invalid_param = true;
  682. break;
  683. }
  684. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  685. params.n_gpu_layers = std::stoi(argv[i]);
  686. #else
  687. LOG_WARNING("Not compiled with GPU offload support, --n-gpu-layers option will be ignored. "
  688. "See main README.md for information on enabling GPU BLAS support",
  689. {{"n_gpu_layers", params.n_gpu_layers}});
  690. #endif
  691. }
  692. else if (arg == "--tensor-split" || arg == "-ts")
  693. {
  694. if (++i >= argc)
  695. {
  696. invalid_param = true;
  697. break;
  698. }
  699. #ifdef GGML_USE_CUBLAS
  700. std::string arg_next = argv[i];
  701. // split string by , and /
  702. const std::regex regex{R"([,/]+)"};
  703. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  704. std::vector<std::string> split_arg{it, {}};
  705. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  706. for (size_t i_device = 0; i_device < LLAMA_MAX_DEVICES; ++i_device)
  707. {
  708. if (i_device < split_arg.size())
  709. {
  710. params.tensor_split[i_device] = std::stof(split_arg[i_device]);
  711. }
  712. else
  713. {
  714. params.tensor_split[i_device] = 0.0f;
  715. }
  716. }
  717. #else
  718. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.", {});
  719. #endif // GGML_USE_CUBLAS
  720. }
  721. else if (arg == "--low-vram" || arg == "-lv")
  722. {
  723. #ifdef GGML_USE_CUBLAS
  724. params.low_vram = true;
  725. #else
  726. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n");
  727. #endif // GGML_USE_CUBLAS
  728. }
  729. else if (arg == "--main-gpu" || arg == "-mg")
  730. {
  731. if (++i >= argc)
  732. {
  733. invalid_param = true;
  734. break;
  735. }
  736. #ifdef GGML_USE_CUBLAS
  737. params.main_gpu = std::stoi(argv[i]);
  738. #else
  739. LOG_WARNING("llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.", {});
  740. #endif
  741. }
  742. else if (arg == "--lora")
  743. {
  744. if (++i >= argc)
  745. {
  746. invalid_param = true;
  747. break;
  748. }
  749. params.lora_adapter = argv[i];
  750. }
  751. else if (arg == "--lora-base")
  752. {
  753. if (++i >= argc)
  754. {
  755. invalid_param = true;
  756. break;
  757. }
  758. params.lora_base = argv[i];
  759. }
  760. else if (arg == "-v" || arg == "--verbose")
  761. {
  762. #if SERVER_VERBOSE != 1
  763. LOG_WARNING("server.cpp is not built with verbose logging.", {});
  764. #else
  765. server_verbose = true;
  766. #endif
  767. }
  768. else if (arg == "--mlock")
  769. {
  770. params.use_mlock = true;
  771. }
  772. else if (arg == "--no-mmap")
  773. {
  774. params.use_mmap = false;
  775. }
  776. else if (arg == "--embedding")
  777. {
  778. params.embedding = true;
  779. }
  780. else
  781. {
  782. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  783. server_print_usage(argv[0], default_params, default_sparams);
  784. exit(1);
  785. }
  786. }
  787. if (invalid_param)
  788. {
  789. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  790. server_print_usage(argv[0], default_params, default_sparams);
  791. exit(1);
  792. }
  793. }
  794. static json format_generation_settings(llama_server_context &llama)
  795. {
  796. const auto eos_bias = llama.params.logit_bias.find(llama_token_eos());
  797. const bool ignore_eos = eos_bias != llama.params.logit_bias.end() &&
  798. eos_bias->second < 0.0f && std::isinf(eos_bias->second);
  799. return json{
  800. {"n_ctx", llama.params.n_ctx},
  801. {"model", llama.params.model_alias},
  802. {"seed", llama.params.seed},
  803. {"temp", llama.params.temp},
  804. {"top_k", llama.params.top_k},
  805. {"top_p", llama.params.top_p},
  806. {"tfs_z", llama.params.tfs_z},
  807. {"typical_p", llama.params.typical_p},
  808. {"repeat_last_n", llama.params.repeat_last_n},
  809. {"repeat_penalty", llama.params.repeat_penalty},
  810. {"presence_penalty", llama.params.presence_penalty},
  811. {"frequency_penalty", llama.params.frequency_penalty},
  812. {"mirostat", llama.params.mirostat},
  813. {"mirostat_tau", llama.params.mirostat_tau},
  814. {"mirostat_eta", llama.params.mirostat_eta},
  815. {"penalize_nl", llama.params.penalize_nl},
  816. {"stop", llama.params.antiprompt},
  817. {"n_predict", llama.params.n_predict},
  818. {"n_keep", llama.params.n_keep},
  819. {"ignore_eos", ignore_eos},
  820. {"stream", llama.stream},
  821. {"logit_bias", llama.params.logit_bias},
  822. {"n_probs", llama.params.n_probs},
  823. };
  824. }
  825. static json format_embedding_response(llama_server_context &llama)
  826. {
  827. return json{
  828. {"embedding", llama.getEmbedding()},
  829. };
  830. }
  831. static json format_timings(llama_server_context &llama)
  832. {
  833. const auto timings = llama_get_timings(llama.ctx);
  834. assert(timings.n_eval == llama.num_tokens_predicted);
  835. return json{
  836. {"prompt_n", timings.n_eval},
  837. {"prompt_ms", timings.t_p_eval_ms},
  838. {"prompt_per_token_ms", timings.t_p_eval_ms / timings.n_p_eval},
  839. {"prompt_per_second", 1e3 / timings.t_p_eval_ms * timings.n_p_eval},
  840. {"predicted_n", timings.n_eval},
  841. {"predicted_ms", timings.t_eval_ms},
  842. {"predicted_per_token_ms", timings.t_eval_ms / timings.n_eval},
  843. {"predicted_per_second", 1e3 / timings.t_eval_ms * timings.n_eval},
  844. };
  845. }
  846. static json format_final_response(llama_server_context &llama, const std::string &content, const std::vector<completion_token_output> &probs)
  847. {
  848. json res = json{
  849. {"content", content},
  850. {"stop", true},
  851. {"model", llama.params.model_alias},
  852. {"tokens_predicted", llama.num_tokens_predicted},
  853. {"tokens_evaluated", llama.num_prompt_tokens},
  854. {"generation_settings", format_generation_settings(llama)},
  855. {"prompt", llama.params.prompt},
  856. {"truncated", llama.truncated},
  857. {"stopped_eos", llama.stopped_eos},
  858. {"stopped_word", llama.stopped_word},
  859. {"stopped_limit", llama.stopped_limit},
  860. {"stopping_word", llama.stopping_word},
  861. {"tokens_cached", llama.n_past},
  862. {"tokens_predicted", llama.num_tokens_predicted},
  863. {"timings", format_timings(llama)},
  864. };
  865. if (llama.params.n_probs > 0)
  866. {
  867. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  868. }
  869. return res;
  870. }
  871. static json format_partial_response(llama_server_context &llama, const std::string &content, const std::vector<completion_token_output> &probs)
  872. {
  873. json res = json{
  874. {"content", content},
  875. {"stop", false},
  876. };
  877. if (llama.params.n_probs > 0)
  878. {
  879. res["completion_probabilities"] = probs_vector_to_json(llama.ctx, probs);
  880. }
  881. return res;
  882. }
  883. static json format_tokenizer_response(const std::vector<llama_token> &tokens)
  884. {
  885. return json{
  886. {"tokens", tokens}};
  887. }
  888. static void parse_options_completion(const json &body, llama_server_context &llama)
  889. {
  890. gpt_params default_params;
  891. llama.stream = body.value("stream", false);
  892. llama.params.n_predict = body.value("n_predict", default_params.n_predict);
  893. llama.params.top_k = body.value("top_k", default_params.top_k);
  894. llama.params.top_p = body.value("top_p", default_params.top_p);
  895. llama.params.tfs_z = body.value("tfs_z", default_params.tfs_z);
  896. llama.params.typical_p = body.value("typical_p", default_params.typical_p);
  897. llama.params.repeat_last_n = body.value("repeat_last_n", default_params.repeat_last_n);
  898. llama.params.temp = body.value("temperature", default_params.temp);
  899. llama.params.repeat_penalty = body.value("repeat_penalty", default_params.repeat_penalty);
  900. llama.params.presence_penalty = body.value("presence_penalty", default_params.presence_penalty);
  901. llama.params.frequency_penalty = body.value("frequency_penalty", default_params.frequency_penalty);
  902. llama.params.mirostat = body.value("mirostat", default_params.mirostat);
  903. llama.params.mirostat_tau = body.value("mirostat_tau", default_params.mirostat_tau);
  904. llama.params.mirostat_eta = body.value("mirostat_eta", default_params.mirostat_eta);
  905. llama.params.penalize_nl = body.value("penalize_nl", default_params.penalize_nl);
  906. llama.params.n_keep = body.value("n_keep", default_params.n_keep);
  907. llama.params.seed = body.value("seed", default_params.seed);
  908. llama.params.prompt = body.value("prompt", default_params.prompt);
  909. llama.params.n_probs = body.value("n_probs", default_params.n_probs);
  910. llama.params.logit_bias.clear();
  911. if (body.value("ignore_eos", false))
  912. {
  913. llama.params.logit_bias[llama_token_eos()] = -INFINITY;
  914. }
  915. const auto &logit_bias = body.find("logit_bias");
  916. if (logit_bias != body.end() && logit_bias->is_array())
  917. {
  918. const int n_vocab = llama_n_vocab(llama.ctx);
  919. for (const auto &el : *logit_bias)
  920. {
  921. if (el.is_array() && el.size() == 2 && el[0].is_number_integer())
  922. {
  923. llama_token tok = el[0].get<llama_token>();
  924. if (tok >= 0 && tok < n_vocab)
  925. {
  926. if (el[1].is_number())
  927. {
  928. llama.params.logit_bias[tok] = el[1].get<float>();
  929. }
  930. else if (el[1].is_boolean() && !el[1].get<bool>())
  931. {
  932. llama.params.logit_bias[tok] = -INFINITY;
  933. }
  934. }
  935. }
  936. }
  937. }
  938. llama.params.antiprompt.clear();
  939. const auto &stop = body.find("stop");
  940. if (stop != body.end() && stop->is_array())
  941. {
  942. for (const auto &word : *stop)
  943. {
  944. if (!word.empty())
  945. {
  946. llama.params.antiprompt.push_back(word);
  947. }
  948. }
  949. }
  950. LOG_VERBOSE("completion parameters parsed", format_generation_settings(llama));
  951. }
  952. static void log_server_request(const Request &req, const Response &res)
  953. {
  954. LOG_INFO("request", {
  955. {"remote_addr", req.remote_addr},
  956. {"remote_port", req.remote_port},
  957. {"status", res.status},
  958. {"method", req.method},
  959. {"path", req.path},
  960. {"params", req.params},
  961. });
  962. LOG_VERBOSE("request", {
  963. {"request", req.body},
  964. {"response", res.body},
  965. });
  966. }
  967. int main(int argc, char **argv)
  968. {
  969. // own arguments required by this example
  970. gpt_params params;
  971. server_params sparams;
  972. // struct that contains llama context and inference
  973. llama_server_context llama;
  974. server_params_parse(argc, argv, sparams, params);
  975. if (params.model_alias == "unknown")
  976. {
  977. params.model_alias = params.model;
  978. }
  979. llama_backend_init(params.numa);
  980. LOG_INFO("build info", {{"build", BUILD_NUMBER},
  981. {"commit", BUILD_COMMIT}});
  982. LOG_INFO("system info", {
  983. {"n_threads", params.n_threads},
  984. {"total_threads", std::thread::hardware_concurrency()},
  985. {"system_info", llama_print_system_info()},
  986. });
  987. // load the model
  988. if (!llama.loadModel(params))
  989. {
  990. return 1;
  991. }
  992. Server svr;
  993. svr.set_default_headers({{"Server", "llama.cpp"},
  994. {"Access-Control-Allow-Origin", "*"},
  995. {"Access-Control-Allow-Headers", "content-type"}});
  996. // this is only called if no index.html is found in the public --path
  997. svr.Get("/", [](const Request &, Response &res)
  998. {
  999. res.set_content(reinterpret_cast<const char*>(&index_html), index_html_len, "text/html");
  1000. return false; });
  1001. // this is only called if no index.js is found in the public --path
  1002. svr.Get("/index.js", [](const Request &, Response &res)
  1003. {
  1004. res.set_content(reinterpret_cast<const char *>(&index_js), index_js_len, "text/javascript");
  1005. return false; });
  1006. // this is only called if no index.html is found in the public --path
  1007. svr.Get("/completion.js", [](const Request &, Response &res)
  1008. {
  1009. res.set_content(reinterpret_cast<const char*>(&completion_js), completion_js_len, "application/javascript");
  1010. return false; });
  1011. svr.Post("/completion", [&llama](const Request &req, Response &res)
  1012. {
  1013. auto lock = llama.lock();
  1014. llama.rewind();
  1015. llama_reset_timings(llama.ctx);
  1016. parse_options_completion(json::parse(req.body), llama);
  1017. llama.loadPrompt();
  1018. llama.beginCompletion();
  1019. if (!llama.stream) {
  1020. size_t stop_pos = std::string::npos;
  1021. while (llama.has_next_token) {
  1022. const completion_token_output token_with_probs = llama.doCompletion();
  1023. const std::string token_text = token_with_probs.tok == -1 ? "" : llama_token_to_str(llama.ctx, token_with_probs.tok);
  1024. stop_pos = llama.findStoppingStrings(llama.generated_text,
  1025. token_text.size(), STOP_FULL);
  1026. }
  1027. if (stop_pos == std::string::npos) {
  1028. stop_pos = llama.findStoppingStrings(llama.generated_text, 0, STOP_PARTIAL);
  1029. }
  1030. if (stop_pos != std::string::npos) {
  1031. llama.generated_text.erase(llama.generated_text.begin() + stop_pos,
  1032. llama.generated_text.end());
  1033. }
  1034. const json data = format_final_response(llama, llama.generated_text, llama.generated_token_probs);
  1035. llama_print_timings(llama.ctx);
  1036. res.set_content(data.dump(-1, ' ', false, json::error_handler_t::replace),
  1037. "application/json");
  1038. } else {
  1039. const auto chunked_content_provider = [&](size_t, DataSink & sink) {
  1040. size_t sent_count = 0;
  1041. size_t sent_token_probs_index = 0;
  1042. while (llama.has_next_token) {
  1043. const completion_token_output token_with_probs = llama.doCompletion();
  1044. const std::string token_text = token_with_probs.tok == -1 ? "" : llama_token_to_str(llama.ctx, token_with_probs.tok);
  1045. if (llama.multibyte_pending > 0) {
  1046. continue;
  1047. }
  1048. size_t pos = std::min(sent_count, llama.generated_text.size());
  1049. const std::string str_test = llama.generated_text.substr(pos);
  1050. size_t stop_pos =
  1051. llama.findStoppingStrings(str_test, token_text.size(), STOP_FULL);
  1052. if (stop_pos != std::string::npos) {
  1053. llama.generated_text.erase(
  1054. llama.generated_text.begin() + pos + stop_pos,
  1055. llama.generated_text.end());
  1056. pos = std::min(sent_count, llama.generated_text.size());
  1057. } else {
  1058. stop_pos = llama.findStoppingStrings(str_test, token_text.size(),
  1059. STOP_PARTIAL);
  1060. }
  1061. const std::string to_send = llama.generated_text.substr(pos, stop_pos);
  1062. sent_count += to_send.size();
  1063. std::vector<completion_token_output> probs_output = {};
  1064. if (llama.params.n_probs > 0) {
  1065. const std::vector<llama_token> to_send_toks = llama_tokenize(llama.ctx, to_send, false);
  1066. size_t probs_pos = std::min(sent_token_probs_index, llama.generated_token_probs.size());
  1067. size_t probs_stop_pos = std::min(sent_token_probs_index + to_send_toks.size(), llama.generated_token_probs.size());
  1068. if (probs_pos < probs_stop_pos) {
  1069. probs_output = std::vector<completion_token_output>(llama.generated_token_probs.begin() + probs_pos, llama.generated_token_probs.begin() + probs_stop_pos);
  1070. }
  1071. sent_token_probs_index = probs_stop_pos;
  1072. }
  1073. const json data = llama.has_next_token
  1074. ? format_partial_response(llama, to_send, probs_output)
  1075. // Generation is done, send extra information.
  1076. : format_final_response(llama, to_send, llama.generated_token_probs);
  1077. const std::string str =
  1078. "data: " +
  1079. data.dump(-1, ' ', false, json::error_handler_t::replace) +
  1080. "\n\n";
  1081. LOG_VERBOSE("data stream", {
  1082. { "to_send", str }
  1083. });
  1084. if (!sink.write(str.data(), str.size())) {
  1085. LOG_VERBOSE("stream closed", {});
  1086. llama_print_timings(llama.ctx);
  1087. return false;
  1088. }
  1089. }
  1090. llama_print_timings(llama.ctx);
  1091. sink.done();
  1092. return true;
  1093. };
  1094. res.set_chunked_content_provider("text/event-stream", chunked_content_provider);
  1095. } });
  1096. svr.Get("/model.json", [&llama](const Request &, Response &res)
  1097. {
  1098. const json data = format_generation_settings(llama);
  1099. return res.set_content(data.dump(), "application/json"); });
  1100. svr.Options(R"(/.*)", [](const Request &, Response &res)
  1101. { return res.set_content("", "application/json"); });
  1102. svr.Post("/tokenize", [&llama](const Request &req, Response &res)
  1103. {
  1104. auto lock = llama.lock();
  1105. const json body = json::parse(req.body);
  1106. const std::string content = body.value("content", "");
  1107. const std::vector<llama_token> tokens = llama_tokenize(llama.ctx, content, false);
  1108. const json data = format_tokenizer_response(tokens);
  1109. return res.set_content(data.dump(), "application/json"); });
  1110. svr.Post("/embedding", [&llama](const Request &req, Response &res)
  1111. {
  1112. auto lock = llama.lock();
  1113. const json body = json::parse(req.body);
  1114. llama.rewind();
  1115. llama_reset_timings(llama.ctx);
  1116. llama.params.prompt = body.value("content", "");
  1117. llama.params.n_predict = 0;
  1118. llama.loadPrompt();
  1119. llama.beginCompletion();
  1120. llama.doCompletion();
  1121. const json data = format_embedding_response(llama);
  1122. return res.set_content(data.dump(), "application/json"); });
  1123. svr.set_logger(log_server_request);
  1124. svr.set_exception_handler([](const Request &, Response &res, std::exception_ptr ep)
  1125. {
  1126. const auto * fmt = "500 Internal Server Error\n%s";
  1127. char buf[BUFSIZ];
  1128. try {
  1129. std::rethrow_exception(std::move(ep));
  1130. } catch (std::exception & e) {
  1131. snprintf(buf, sizeof(buf), fmt, e.what());
  1132. } catch (...) {
  1133. snprintf(buf, sizeof(buf), fmt, "Unknown Exception");
  1134. }
  1135. res.set_content(buf, "text/plain");
  1136. res.status = 500; });
  1137. svr.set_error_handler([](const Request &, Response &res)
  1138. {
  1139. res.set_content("File Not Found", "text/plain");
  1140. res.status = 404; });
  1141. // set timeouts and change hostname and port
  1142. svr.set_read_timeout(sparams.read_timeout);
  1143. svr.set_write_timeout(sparams.write_timeout);
  1144. if (!svr.bind_to_port(sparams.hostname, sparams.port))
  1145. {
  1146. fprintf(stderr, "\ncouldn't bind to server socket: hostname=%s port=%d\n\n", sparams.hostname.c_str(), sparams.port);
  1147. return 1;
  1148. }
  1149. // Set the base directory for serving static files
  1150. svr.set_base_dir(sparams.public_path);
  1151. // to make it ctrl+clickable:
  1152. fprintf(stdout, "\nllama server listening at http://%s:%d\n\n", sparams.hostname.c_str(), sparams.port);
  1153. LOG_INFO("HTTP server listening", {
  1154. {"hostname", sparams.hostname},
  1155. {"port", sparams.port},
  1156. });
  1157. if (!svr.listen_after_bind())
  1158. {
  1159. return 1;
  1160. }
  1161. llama_backend_free();
  1162. return 0;
  1163. }