1
0

server.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799
  1. #include <httplib.h>
  2. #include <json.hpp>
  3. #include "common.h"
  4. #include "llama.h"
  5. struct server_params
  6. {
  7. std::string hostname = "127.0.0.1";
  8. int32_t port = 8080;
  9. };
  10. struct llama_server_context
  11. {
  12. bool as_loop = false;
  13. bool has_next_token = false;
  14. std::string generated_text = "";
  15. int32_t num_tokens_predicted = 0;
  16. int32_t n_past = 0;
  17. int32_t n_consumed = 0;
  18. int32_t n_session_consumed = 0;
  19. int32_t n_remain = 0;
  20. std::vector<llama_token> embd;
  21. std::vector<llama_token> last_n_tokens;
  22. std::vector<llama_token> processed_tokens;
  23. std::vector<llama_token> llama_token_newline;
  24. std::vector<llama_token> embd_inp;
  25. std::vector<std::vector<llama_token>> no_show_words;
  26. std::vector<llama_token> tokens_predicted;
  27. llama_context *ctx;
  28. gpt_params params;
  29. void rewind() {
  30. as_loop = false;
  31. params.antiprompt.clear();
  32. no_show_words.clear();
  33. num_tokens_predicted = 0;
  34. generated_text = "";
  35. }
  36. bool loadModel(gpt_params params_)
  37. {
  38. params = params_;
  39. ctx = llama_init_from_gpt_params(params);
  40. if (ctx == NULL)
  41. {
  42. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  43. return false;
  44. }
  45. // determine newline token
  46. llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  47. last_n_tokens.resize(params.n_ctx);
  48. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  49. return true;
  50. }
  51. bool loadPrompt() {
  52. params.prompt.insert(0, 1, ' '); // always add a first space
  53. std::vector<llama_token> prompt_tokens = ::llama_tokenize(ctx, params.prompt, true);
  54. // compare the evaluated prompt with the new prompt
  55. int new_prompt_len = 0;
  56. for (size_t i = 0; i < prompt_tokens.size(); i++) {
  57. if (i < processed_tokens.size() &&
  58. processed_tokens[i] == prompt_tokens[i])
  59. {
  60. continue;
  61. }
  62. else
  63. {
  64. embd_inp.push_back(prompt_tokens[i]);
  65. if(new_prompt_len == 0) {
  66. if(int32_t(i) - 1 < n_past) {
  67. processed_tokens.erase(processed_tokens.begin() + i, processed_tokens.end());
  68. }
  69. // Evaluate the new fragment prompt from the last token processed.
  70. n_past = processed_tokens.size();
  71. }
  72. new_prompt_len ++;
  73. }
  74. }
  75. if(n_past > 0 && params.interactive) {
  76. n_remain -= new_prompt_len;
  77. }
  78. if ((int)embd_inp.size() > params.n_ctx - 4)
  79. {
  80. return false;
  81. }
  82. has_next_token = true;
  83. return true;
  84. }
  85. void beginCompletion()
  86. {
  87. if(n_remain == 0) {
  88. // number of tokens to keep when resetting context
  89. if (params.n_keep < 0 || params.n_keep > (int)embd_inp.size())
  90. {
  91. params.n_keep = (int)embd_inp.size();
  92. }
  93. }
  94. n_remain = params.n_predict;
  95. }
  96. llama_token nextToken() {
  97. llama_token result = -1;
  98. if (embd.size() > 0)
  99. {
  100. if (n_past + (int)embd.size() > params.n_ctx)
  101. {
  102. // Reset context
  103. const int n_left = n_past - params.n_keep;
  104. n_past = std::max(1, params.n_keep);
  105. processed_tokens.erase(processed_tokens.begin() + n_past, processed_tokens.end());
  106. embd.insert(embd.begin(), last_n_tokens.begin() + params.n_ctx - n_left / 2 - embd.size(), last_n_tokens.end() - embd.size());
  107. }
  108. for (int i = 0; i < (int)embd.size(); i += params.n_batch)
  109. {
  110. int n_eval = (int)embd.size() - i;
  111. if (n_eval > params.n_batch)
  112. {
  113. n_eval = params.n_batch;
  114. }
  115. if (llama_eval(ctx, &embd[i], n_eval, n_past, params.n_threads))
  116. {
  117. fprintf(stderr, "%s : failed to eval\n", __func__);
  118. has_next_token = false;
  119. return result;
  120. }
  121. n_past += n_eval;
  122. }
  123. }
  124. embd.clear();
  125. if ((int)embd_inp.size() <= n_consumed && has_next_token)
  126. {
  127. // out of user input, sample next token
  128. const float temp = params.temp;
  129. // const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  130. const float top_p = params.top_p;
  131. const float tfs_z = params.tfs_z;
  132. const float typical_p = params.typical_p;
  133. const int32_t repeat_last_n = params.repeat_last_n < 0 ? params.n_ctx : params.repeat_last_n;
  134. const float repeat_penalty = params.repeat_penalty;
  135. const float alpha_presence = params.presence_penalty;
  136. const float alpha_frequency = params.frequency_penalty;
  137. const int mirostat = params.mirostat;
  138. const float mirostat_tau = params.mirostat_tau;
  139. const float mirostat_eta = params.mirostat_eta;
  140. const bool penalize_nl = params.penalize_nl;
  141. llama_token id = 0;
  142. {
  143. auto logits = llama_get_logits(ctx);
  144. auto n_vocab = llama_n_vocab(ctx);
  145. // Apply params.logit_bias map
  146. for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++)
  147. {
  148. logits[it->first] += it->second;
  149. }
  150. std::vector<llama_token_data> candidates;
  151. candidates.reserve(n_vocab);
  152. for (llama_token token_id = 0; token_id < n_vocab; token_id++)
  153. {
  154. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  155. }
  156. llama_token_data_array candidates_p = {candidates.data(), candidates.size(), false};
  157. // Apply penalties
  158. float nl_logit = logits[llama_token_nl()];
  159. auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), params.n_ctx);
  160. llama_sample_repetition_penalty(ctx, &candidates_p,
  161. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  162. last_n_repeat, repeat_penalty);
  163. llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
  164. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  165. last_n_repeat, alpha_frequency, alpha_presence);
  166. if (!penalize_nl)
  167. {
  168. logits[llama_token_nl()] = nl_logit;
  169. }
  170. if (temp <= 0)
  171. {
  172. // Greedy sampling
  173. id = llama_sample_token_greedy(ctx, &candidates_p);
  174. }
  175. else
  176. {
  177. if (mirostat == 1)
  178. {
  179. static float mirostat_mu = 2.0f * mirostat_tau;
  180. const int mirostat_m = 100;
  181. llama_sample_temperature(ctx, &candidates_p, temp);
  182. id = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  183. }
  184. else if (mirostat == 2)
  185. {
  186. static float mirostat_mu = 2.0f * mirostat_tau;
  187. llama_sample_temperature(ctx, &candidates_p, temp);
  188. id = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  189. }
  190. else
  191. {
  192. // Temperature sampling
  193. llama_sample_tail_free(ctx, &candidates_p, tfs_z, 1);
  194. llama_sample_typical(ctx, &candidates_p, typical_p, 1);
  195. llama_sample_top_p(ctx, &candidates_p, top_p, 1);
  196. llama_sample_temperature(ctx, &candidates_p, temp);
  197. id = llama_sample_token(ctx, &candidates_p);
  198. }
  199. }
  200. last_n_tokens.erase(last_n_tokens.begin());
  201. last_n_tokens.push_back(id);
  202. processed_tokens.push_back(id);
  203. num_tokens_predicted++;
  204. }
  205. // replace end of text token with newline token when in interactive mode
  206. if (id == llama_token_eos() && params.interactive)
  207. {
  208. id = llama_token_newline.front();
  209. if (params.antiprompt.size() != 0)
  210. {
  211. // tokenize and inject first reverse prompt
  212. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  213. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  214. }
  215. }
  216. // add it to the context
  217. embd.push_back(id);
  218. for (auto id : embd)
  219. {
  220. result = id;
  221. }
  222. // decrement remaining sampling budget
  223. --n_remain;
  224. }
  225. else
  226. {
  227. // some user input remains from prompt or interaction, forward it to processing
  228. while ((int)embd_inp.size() > n_consumed)
  229. {
  230. embd.push_back(embd_inp[n_consumed]);
  231. last_n_tokens.erase(last_n_tokens.begin());
  232. last_n_tokens.push_back(embd_inp[n_consumed]);
  233. processed_tokens.push_back(embd_inp[n_consumed]);
  234. ++n_consumed;
  235. if ((int)embd.size() >= params.n_batch)
  236. {
  237. break;
  238. }
  239. }
  240. }
  241. if (params.interactive && (int)embd_inp.size() <= n_consumed)
  242. {
  243. // check for reverse prompt
  244. if (params.antiprompt.size())
  245. {
  246. std::string last_output;
  247. for (auto id : last_n_tokens)
  248. {
  249. last_output += llama_token_to_str(ctx, id);
  250. }
  251. has_next_token = true;
  252. // Check if each of the reverse prompts appears at the end of the output.
  253. for (std::string &antiprompt : params.antiprompt)
  254. {
  255. if (last_output.find(antiprompt.c_str(), last_output.length() - antiprompt.length(), antiprompt.length()) != std::string::npos)
  256. {
  257. has_next_token = false;
  258. return result;
  259. }
  260. }
  261. }
  262. if (n_past > 0)
  263. {
  264. has_next_token = true;
  265. }
  266. }
  267. if (!embd.empty() && embd.back() == llama_token_eos()) {
  268. has_next_token = false;
  269. }
  270. if (params.interactive && n_remain <= 0 && params.n_predict != -1)
  271. {
  272. n_remain = params.n_predict;
  273. }
  274. has_next_token = n_remain != 0;
  275. return result;
  276. }
  277. std::string doCompletion()
  278. {
  279. llama_token token = nextToken();
  280. if (token == -1) {
  281. return "";
  282. }
  283. tokens_predicted.clear();
  284. tokens_predicted.push_back(token);
  285. // Avoid add the no show words to the response
  286. for (std::vector<llama_token> word_tokens : no_show_words)
  287. {
  288. size_t match_token = 1;
  289. if (tokens_predicted.front() == word_tokens.front())
  290. {
  291. bool execute_matching = true;
  292. if (tokens_predicted.size() > 1) { // if previus tokens had been tested
  293. for (size_t i = 1; i < word_tokens.size(); i++)
  294. {
  295. if (i >= tokens_predicted.size()) {
  296. match_token = i;
  297. break;
  298. }
  299. if (tokens_predicted[i] == word_tokens[i])
  300. {
  301. continue;
  302. }
  303. else
  304. {
  305. execute_matching = false;
  306. break;
  307. }
  308. }
  309. }
  310. while (execute_matching) {
  311. if (match_token == word_tokens.size()) {
  312. return "";
  313. }
  314. token = nextToken();
  315. tokens_predicted.push_back(token);
  316. if (token == word_tokens[match_token])
  317. { // the token follow the sequence
  318. match_token++;
  319. }
  320. else if (match_token < word_tokens.size())
  321. { // no complete all word sequence
  322. break;
  323. }
  324. }
  325. }
  326. }
  327. if(as_loop) {
  328. generated_text = "";
  329. }
  330. for (llama_token tkn : tokens_predicted)
  331. {
  332. generated_text += llama_token_to_str(ctx, tkn);
  333. }
  334. return generated_text;
  335. }
  336. std::vector<float> embedding(std::string content, int threads) {
  337. content.insert(0, 1, ' ');
  338. std::vector<llama_token> tokens = ::llama_tokenize(ctx, content, true);
  339. if (tokens.size() > 0)
  340. {
  341. if (llama_eval(ctx, tokens.data(), tokens.size(), 0, threads))
  342. {
  343. fprintf(stderr, "%s : failed to eval\n", __func__);
  344. std::vector<float> embeddings_;
  345. return embeddings_;
  346. }
  347. }
  348. const int n_embd = llama_n_embd(ctx);
  349. const auto embeddings = llama_get_embeddings(ctx);
  350. std::vector<float> embeddings_(embeddings, embeddings + n_embd);
  351. return embeddings_;
  352. }
  353. };
  354. using namespace httplib;
  355. using json = nlohmann::json;
  356. void server_print_usage(int /*argc*/, char **argv, const gpt_params &params)
  357. {
  358. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  359. fprintf(stderr, "\n");
  360. fprintf(stderr, "options:\n");
  361. fprintf(stderr, " -h, --help show this help message and exit\n");
  362. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  363. fprintf(stderr, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  364. fprintf(stderr, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  365. fprintf(stderr, " not recommended: doubles context memory required and no measurable increase in quality\n");
  366. fprintf(stderr, " --embedding enable embedding mode\n");
  367. fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  368. if (llama_mlock_supported())
  369. {
  370. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  371. }
  372. if (llama_mmap_supported())
  373. {
  374. fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  375. }
  376. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  377. fprintf(stderr, " -ngl N, --n-gpu-layers N\n");
  378. fprintf(stderr, " number of layers to store in VRAM\n");
  379. fprintf(stderr, " -ts SPLIT --tensor-split SPLIT\n");
  380. fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  381. fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  382. fprintf(stderr, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n" );
  383. fprintf(stderr, " -lv, --low-vram don't allocate VRAM scratch buffer\n" );
  384. #endif
  385. fprintf(stderr, " -m FNAME, --model FNAME\n");
  386. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  387. fprintf(stderr, " -a ALIAS, --alias ALIAS\n");
  388. fprintf(stderr, " set an alias for the model, will be added as `model` field in completion response\n");
  389. fprintf(stderr, " --host ip address to listen (default 127.0.0.1)\n");
  390. fprintf(stderr, " --port PORT port to listen (default 8080)\n");
  391. fprintf(stderr, "\n");
  392. }
  393. bool server_params_parse(int argc, char **argv, server_params &sparams, gpt_params &params)
  394. {
  395. gpt_params default_params;
  396. std::string arg;
  397. bool invalid_param = false;
  398. for (int i = 1; i < argc; i++)
  399. {
  400. arg = argv[i];
  401. if (arg == "--port")
  402. {
  403. if (++i >= argc)
  404. {
  405. invalid_param = true;
  406. break;
  407. }
  408. sparams.port = std::stoi(argv[i]);
  409. }
  410. else if (arg == "--host")
  411. {
  412. if (++i >= argc)
  413. {
  414. invalid_param = true;
  415. break;
  416. }
  417. sparams.hostname = argv[i];
  418. }
  419. else if (arg == "-s" || arg == "--seed")
  420. {
  421. #if defined(GGML_USE_CUBLAS)
  422. fprintf(stderr, "WARNING: when using cuBLAS generation results are NOT guaranteed to be reproducible.\n");
  423. #endif
  424. if (++i >= argc)
  425. {
  426. invalid_param = true;
  427. break;
  428. }
  429. params.seed = std::stoi(argv[i]);
  430. }
  431. else if (arg == "-m" || arg == "--model")
  432. {
  433. if (++i >= argc)
  434. {
  435. invalid_param = true;
  436. break;
  437. }
  438. params.model = argv[i];
  439. }
  440. else if (arg == "-a" || arg == "--alias")
  441. {
  442. if (++i >= argc)
  443. {
  444. invalid_param = true;
  445. break;
  446. }
  447. params.model_alias = argv[i];
  448. }
  449. else if (arg == "--embedding")
  450. {
  451. params.embedding = true;
  452. }
  453. else if (arg == "-h" || arg == "--help")
  454. {
  455. server_print_usage(argc, argv, default_params);
  456. exit(0);
  457. }
  458. else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size")
  459. {
  460. if (++i >= argc)
  461. {
  462. invalid_param = true;
  463. break;
  464. }
  465. params.n_ctx = std::stoi(argv[i]);
  466. }
  467. else if (arg == "--memory-f32" || arg == "--memory_f32")
  468. {
  469. params.memory_f16 = false;
  470. }
  471. else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
  472. {
  473. if (++i >= argc)
  474. {
  475. invalid_param = true;
  476. break;
  477. }
  478. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  479. params.n_gpu_layers = std::stoi(argv[i]);
  480. #else
  481. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  482. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  483. #endif
  484. }
  485. else if (arg == "--tensor-split" || arg == "-ts")
  486. {
  487. if (++i >= argc)
  488. {
  489. invalid_param = true;
  490. break;
  491. }
  492. #ifdef GGML_USE_CUBLAS
  493. std::string arg_next = argv[i];
  494. // split string by , and /
  495. const std::regex regex{R"([,/]+)"};
  496. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  497. std::vector<std::string> split_arg{it, {}};
  498. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  499. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i)
  500. {
  501. if (i < split_arg.size())
  502. {
  503. params.tensor_split[i] = std::stof(split_arg[i]);
  504. }
  505. else
  506. {
  507. params.tensor_split[i] = 0.0f;
  508. }
  509. }
  510. #else
  511. fprintf(stderr, "WARNING: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
  512. #endif // GGML_USE_CUBLAS
  513. }
  514. else if (arg == "--low-vram" || arg == "-lv")
  515. {
  516. #ifdef GGML_USE_CUBLAS
  517. params.low_vram = true;
  518. #else
  519. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set lower vram usage.\n");
  520. #endif // GGML_USE_CUBLAS
  521. }
  522. else if (arg == "--main-gpu" || arg == "-mg")
  523. {
  524. if (++i >= argc)
  525. {
  526. invalid_param = true;
  527. break;
  528. }
  529. #ifdef GGML_USE_CUBLAS
  530. params.main_gpu = std::stoi(argv[i]);
  531. #else
  532. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
  533. #endif
  534. }
  535. else
  536. {
  537. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  538. server_print_usage(argc, argv, default_params);
  539. exit(1);
  540. }
  541. }
  542. if (invalid_param)
  543. {
  544. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  545. server_print_usage(argc, argv, default_params);
  546. exit(1);
  547. }
  548. return true;
  549. }
  550. bool parse_options_completion(json body, llama_server_context& llama, Response &res) {
  551. if (!body["threads"].is_null())
  552. {
  553. llama.params.n_threads = body["threads"].get<int>();
  554. }
  555. if (!body["n_predict"].is_null())
  556. {
  557. llama.params.n_predict = body["n_predict"].get<int>();
  558. }
  559. if (!body["top_k"].is_null())
  560. {
  561. llama.params.top_k = body["top_k"].get<int>();
  562. }
  563. if (!body["top_p"].is_null())
  564. {
  565. llama.params.top_p = body["top_p"].get<float>();
  566. }
  567. if (!body["temperature"].is_null())
  568. {
  569. llama.params.temp = body["temperature"].get<float>();
  570. }
  571. if (!body["batch_size"].is_null())
  572. {
  573. llama.params.n_batch = body["batch_size"].get<int>();
  574. }
  575. if (!body["n_keep"].is_null())
  576. {
  577. llama.params.n_keep = body["n_keep"].get<int>();
  578. }
  579. if (!body["as_loop"].is_null())
  580. {
  581. llama.as_loop = body["as_loop"].get<bool>();
  582. }
  583. if (!body["interactive"].is_null())
  584. {
  585. llama.params.interactive = body["interactive"].get<bool>();
  586. }
  587. if (!body["prompt"].is_null())
  588. {
  589. llama.params.prompt = body["prompt"].get<std::string>();
  590. }
  591. else
  592. {
  593. json data = {
  594. {"status", "error"},
  595. {"reason", "You need to pass the prompt"}};
  596. res.set_content(data.dump(), "application/json");
  597. res.status = 400;
  598. return false;
  599. }
  600. if (!body["stop"].is_null())
  601. {
  602. std::vector<std::string> stop_words = body["stop"].get<std::vector<std::string>>();
  603. for (std::string stop_word : stop_words)
  604. {
  605. llama.params.antiprompt.push_back(stop_word);
  606. llama.no_show_words.push_back(::llama_tokenize(llama.ctx, stop_word, false));
  607. }
  608. }
  609. if (!body["exclude"].is_null())
  610. {
  611. std::vector<std::string> no_show_words = body["exclude"].get<std::vector<std::string>>();
  612. for (std::string no_show : no_show_words)
  613. {
  614. llama.no_show_words.push_back(::llama_tokenize(llama.ctx, no_show, false));
  615. }
  616. }
  617. return true;
  618. }
  619. int main(int argc, char **argv)
  620. {
  621. // own arguments required by this example
  622. gpt_params params;
  623. server_params sparams;
  624. // struct that contains llama context and inference
  625. llama_server_context llama;
  626. params.model = "ggml-model.bin";
  627. if (server_params_parse(argc, argv, sparams, params) == false)
  628. {
  629. return 1;
  630. }
  631. if (params.seed <= 0)
  632. {
  633. params.seed = time(NULL);
  634. }
  635. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  636. // load the model
  637. if (!llama.loadModel(params))
  638. {
  639. return 1;
  640. }
  641. Server svr;
  642. svr.Get("/", [](const Request &, Response &res)
  643. { res.set_content("<h1>llama.cpp server works</h1>", "text/html"); });
  644. svr.Post("/completion", [&llama](const Request &req, Response &res)
  645. {
  646. if(llama.params.embedding) {
  647. json data = {
  648. {"status", "error"},
  649. {"reason", "To use completion function disable embedding mode"}};
  650. res.set_content(data.dump(), "application/json");
  651. res.status = 400;
  652. return;
  653. }
  654. llama.rewind();
  655. if(parse_options_completion(json::parse(req.body), llama, res) == false){
  656. return;
  657. }
  658. if (!llama.loadPrompt())
  659. {
  660. json data = {
  661. {"status", "error"},
  662. {"reason", "Context too long, please be more specific"}};
  663. res.set_content(data.dump(), "application/json");
  664. res.status = 400;
  665. return;
  666. }
  667. llama.beginCompletion();
  668. if(llama.as_loop) {
  669. json data = {
  670. {"status", "done" } };
  671. return res.set_content(data.dump(), "application/json");
  672. } else {
  673. // loop inference until finish completion
  674. while (llama.has_next_token)
  675. {
  676. llama.doCompletion();
  677. }
  678. try
  679. {
  680. json data = {
  681. {"model", llama.params.model_alias },
  682. {"content", llama.generated_text },
  683. {"tokens_predicted", llama.num_tokens_predicted}};
  684. return res.set_content(data.dump(), "application/json");
  685. }
  686. catch (const json::exception &e)
  687. {
  688. // Some tokens have bad UTF-8 strings, the json parser is very sensitive
  689. json data = {
  690. {"content", "Bad encoding token"},
  691. {"tokens_predicted", 0}};
  692. return res.set_content(data.dump(), "application/json");
  693. }
  694. } });
  695. svr.Post("/tokenize", [&llama](const Request &req, Response &res)
  696. {
  697. json body = json::parse(req.body);
  698. json data = {
  699. {"tokens", ::llama_tokenize(llama.ctx, body["content"].get<std::string>(), false) } };
  700. return res.set_content(data.dump(), "application/json");
  701. });
  702. svr.Post("/embedding", [&llama](const Request &req, Response &res)
  703. {
  704. if(!llama.params.embedding) {
  705. std::vector<float> empty;
  706. json data = {
  707. {"embedding", empty}};
  708. fprintf(stderr, "[llama-server] : You need enable embedding mode adding: --embedding option\n");
  709. return res.set_content(data.dump(), "application/json");
  710. }
  711. json body = json::parse(req.body);
  712. std::string content = body["content"].get<std::string>();
  713. int threads = body["threads"].get<int>();
  714. json data = {
  715. {"embedding", llama.embedding(content, threads) } };
  716. return res.set_content(data.dump(), "application/json");
  717. });
  718. svr.Get("/next-token", [&llama](const Request &req, Response &res)
  719. {
  720. if(llama.params.embedding) {
  721. res.set_content("{}", "application/json");
  722. return;
  723. }
  724. std::string result = "";
  725. if (req.has_param("stop")) {
  726. llama.has_next_token = false;
  727. } else {
  728. result = llama.doCompletion(); // inference next token
  729. }
  730. try {
  731. json data = {
  732. {"content", result },
  733. {"stop", !llama.has_next_token }};
  734. return res.set_content(data.dump(), "application/json");
  735. } catch (const json::exception &e) {
  736. // Some tokens have bad UTF-8 strings, the json parser is very sensitive
  737. json data = {
  738. {"content", "" },
  739. {"stop", !llama.has_next_token }};
  740. return res.set_content(data.dump(), "application/json");
  741. }
  742. });
  743. fprintf(stderr, "%s: http server Listening at http://%s:%i\n", __func__, sparams.hostname.c_str(), sparams.port);
  744. if(params.embedding) {
  745. fprintf(stderr, "NOTE: Mode embedding enabled. Completion function doesn't work in this mode.\n");
  746. }
  747. // change hostname and port
  748. svr.listen(sparams.hostname, sparams.port);
  749. }