server.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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. #endif
  380. fprintf(stderr, " -m FNAME, --model FNAME\n");
  381. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  382. fprintf(stderr, " -a ALIAS, --alias ALIAS\n");
  383. fprintf(stderr, " set an alias for the model, will be added as `model` field in completion response\n");
  384. fprintf(stderr, " --host ip address to listen (default 127.0.0.1)\n");
  385. fprintf(stderr, " --port PORT port to listen (default 8080)\n");
  386. fprintf(stderr, "\n");
  387. }
  388. bool server_params_parse(int argc, char **argv, server_params &sparams, gpt_params &params)
  389. {
  390. gpt_params default_params;
  391. std::string arg;
  392. bool invalid_param = false;
  393. for (int i = 1; i < argc; i++)
  394. {
  395. arg = argv[i];
  396. if (arg == "--port")
  397. {
  398. if (++i >= argc)
  399. {
  400. invalid_param = true;
  401. break;
  402. }
  403. sparams.port = std::stoi(argv[i]);
  404. }
  405. else if (arg == "--host")
  406. {
  407. if (++i >= argc)
  408. {
  409. invalid_param = true;
  410. break;
  411. }
  412. sparams.hostname = argv[i];
  413. }
  414. else if (arg == "-s" || arg == "--seed")
  415. {
  416. #if defined(GGML_USE_CUBLAS)
  417. fprintf(stderr, "WARNING: when using cuBLAS generation results are NOT guaranteed to be reproducible.\n");
  418. #endif
  419. if (++i >= argc)
  420. {
  421. invalid_param = true;
  422. break;
  423. }
  424. params.seed = std::stoi(argv[i]);
  425. }
  426. else if (arg == "-m" || arg == "--model")
  427. {
  428. if (++i >= argc)
  429. {
  430. invalid_param = true;
  431. break;
  432. }
  433. params.model = argv[i];
  434. }
  435. else if (arg == "-a" || arg == "--alias")
  436. {
  437. if (++i >= argc)
  438. {
  439. invalid_param = true;
  440. break;
  441. }
  442. params.model_alias = argv[i];
  443. }
  444. else if (arg == "--embedding")
  445. {
  446. params.embedding = true;
  447. }
  448. else if (arg == "-h" || arg == "--help")
  449. {
  450. server_print_usage(argc, argv, default_params);
  451. exit(0);
  452. }
  453. else if (arg == "-c" || arg == "--ctx-size" || arg == "--ctx_size")
  454. {
  455. if (++i >= argc)
  456. {
  457. invalid_param = true;
  458. break;
  459. }
  460. params.n_ctx = std::stoi(argv[i]);
  461. }
  462. else if (arg == "--memory-f32" || arg == "--memory_f32")
  463. {
  464. params.memory_f16 = false;
  465. }
  466. else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers")
  467. {
  468. if (++i >= argc)
  469. {
  470. invalid_param = true;
  471. break;
  472. }
  473. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  474. params.n_gpu_layers = std::stoi(argv[i]);
  475. #else
  476. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  477. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  478. #endif
  479. }
  480. else
  481. {
  482. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  483. server_print_usage(argc, argv, default_params);
  484. exit(1);
  485. }
  486. }
  487. if (invalid_param)
  488. {
  489. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  490. server_print_usage(argc, argv, default_params);
  491. exit(1);
  492. }
  493. return true;
  494. }
  495. bool parse_options_completion(json body, llama_server_context& llama, Response &res) {
  496. if (!body["threads"].is_null())
  497. {
  498. llama.params.n_threads = body["threads"].get<int>();
  499. }
  500. if (!body["n_predict"].is_null())
  501. {
  502. llama.params.n_predict = body["n_predict"].get<int>();
  503. }
  504. if (!body["top_k"].is_null())
  505. {
  506. llama.params.top_k = body["top_k"].get<int>();
  507. }
  508. if (!body["top_p"].is_null())
  509. {
  510. llama.params.top_p = body["top_p"].get<float>();
  511. }
  512. if (!body["temperature"].is_null())
  513. {
  514. llama.params.temp = body["temperature"].get<float>();
  515. }
  516. if (!body["batch_size"].is_null())
  517. {
  518. llama.params.n_batch = body["batch_size"].get<int>();
  519. }
  520. if (!body["n_keep"].is_null())
  521. {
  522. llama.params.n_keep = body["n_keep"].get<int>();
  523. }
  524. if (!body["as_loop"].is_null())
  525. {
  526. llama.as_loop = body["as_loop"].get<bool>();
  527. }
  528. if (!body["interactive"].is_null())
  529. {
  530. llama.params.interactive = body["interactive"].get<bool>();
  531. }
  532. if (!body["prompt"].is_null())
  533. {
  534. llama.params.prompt = body["prompt"].get<std::string>();
  535. }
  536. else
  537. {
  538. json data = {
  539. {"status", "error"},
  540. {"reason", "You need to pass the prompt"}};
  541. res.set_content(data.dump(), "application/json");
  542. res.status = 400;
  543. return false;
  544. }
  545. if (!body["stop"].is_null())
  546. {
  547. std::vector<std::string> stop_words = body["stop"].get<std::vector<std::string>>();
  548. for (std::string stop_word : stop_words)
  549. {
  550. llama.params.antiprompt.push_back(stop_word);
  551. llama.no_show_words.push_back(::llama_tokenize(llama.ctx, stop_word, false));
  552. }
  553. }
  554. if (!body["exclude"].is_null())
  555. {
  556. std::vector<std::string> no_show_words = body["exclude"].get<std::vector<std::string>>();
  557. for (std::string no_show : no_show_words)
  558. {
  559. llama.no_show_words.push_back(::llama_tokenize(llama.ctx, no_show, false));
  560. }
  561. }
  562. return true;
  563. }
  564. int main(int argc, char **argv)
  565. {
  566. // own arguments required by this example
  567. gpt_params params;
  568. server_params sparams;
  569. // struct that contains llama context and inference
  570. llama_server_context llama;
  571. params.model = "ggml-model.bin";
  572. if (server_params_parse(argc, argv, sparams, params) == false)
  573. {
  574. return 1;
  575. }
  576. if (params.seed <= 0)
  577. {
  578. params.seed = time(NULL);
  579. }
  580. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  581. // load the model
  582. if (!llama.loadModel(params))
  583. {
  584. return 1;
  585. }
  586. Server svr;
  587. svr.Get("/", [](const Request &, Response &res)
  588. { res.set_content("<h1>llama.cpp server works</h1>", "text/html"); });
  589. svr.Post("/completion", [&llama](const Request &req, Response &res)
  590. {
  591. if(llama.params.embedding) {
  592. json data = {
  593. {"status", "error"},
  594. {"reason", "To use completion function disable embedding mode"}};
  595. res.set_content(data.dump(), "application/json");
  596. res.status = 400;
  597. return;
  598. }
  599. llama.rewind();
  600. if(parse_options_completion(json::parse(req.body), llama, res) == false){
  601. return;
  602. }
  603. if (!llama.loadPrompt())
  604. {
  605. json data = {
  606. {"status", "error"},
  607. {"reason", "Context too long, please be more specific"}};
  608. res.set_content(data.dump(), "application/json");
  609. res.status = 400;
  610. return;
  611. }
  612. llama.beginCompletion();
  613. if(llama.as_loop) {
  614. json data = {
  615. {"status", "done" } };
  616. return res.set_content(data.dump(), "application/json");
  617. } else {
  618. // loop inference until finish completion
  619. while (llama.has_next_token)
  620. {
  621. llama.doCompletion();
  622. }
  623. try
  624. {
  625. json data = {
  626. {"model", llama.params.model_alias },
  627. {"content", llama.generated_text },
  628. {"tokens_predicted", llama.num_tokens_predicted}};
  629. return res.set_content(data.dump(), "application/json");
  630. }
  631. catch (const json::exception &e)
  632. {
  633. // Some tokens have bad UTF-8 strings, the json parser is very sensitive
  634. json data = {
  635. {"content", "Bad encoding token"},
  636. {"tokens_predicted", 0}};
  637. return res.set_content(data.dump(), "application/json");
  638. }
  639. } });
  640. svr.Post("/tokenize", [&llama](const Request &req, Response &res)
  641. {
  642. json body = json::parse(req.body);
  643. json data = {
  644. {"tokens", ::llama_tokenize(llama.ctx, body["content"].get<std::string>(), false) } };
  645. return res.set_content(data.dump(), "application/json");
  646. });
  647. svr.Post("/embedding", [&llama](const Request &req, Response &res)
  648. {
  649. if(!llama.params.embedding) {
  650. std::vector<float> empty;
  651. json data = {
  652. {"embedding", empty}};
  653. fprintf(stderr, "[llama-server] : You need enable embedding mode adding: --embedding option\n");
  654. return res.set_content(data.dump(), "application/json");
  655. }
  656. json body = json::parse(req.body);
  657. std::string content = body["content"].get<std::string>();
  658. int threads = body["threads"].get<int>();
  659. json data = {
  660. {"embedding", llama.embedding(content, threads) } };
  661. return res.set_content(data.dump(), "application/json");
  662. });
  663. svr.Get("/next-token", [&llama](const Request &req, Response &res)
  664. {
  665. if(llama.params.embedding) {
  666. res.set_content("{}", "application/json");
  667. return;
  668. }
  669. std::string result = "";
  670. if (req.has_param("stop")) {
  671. llama.has_next_token = false;
  672. } else {
  673. result = llama.doCompletion(); // inference next token
  674. }
  675. try {
  676. json data = {
  677. {"content", result },
  678. {"stop", !llama.has_next_token }};
  679. return res.set_content(data.dump(), "application/json");
  680. } catch (const json::exception &e) {
  681. // Some tokens have bad UTF-8 strings, the json parser is very sensitive
  682. json data = {
  683. {"content", "" },
  684. {"stop", !llama.has_next_token }};
  685. return res.set_content(data.dump(), "application/json");
  686. }
  687. });
  688. fprintf(stderr, "%s: http server Listening at http://%s:%i\n", __func__, sparams.hostname.c_str(), sparams.port);
  689. if(params.embedding) {
  690. fprintf(stderr, "NOTE: Mode embedding enabled. Completion function doesn't work in this mode.\n");
  691. }
  692. // change hostname and port
  693. svr.listen(sparams.hostname, sparams.port);
  694. }