1
0

server.cpp 53 KB

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