server.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. #include "server-context.h"
  2. #include "server-http.h"
  3. #include "server-models.h"
  4. #include "arg.h"
  5. #include "common.h"
  6. #include "llama.h"
  7. #include "log.h"
  8. #include <atomic>
  9. #include <signal.h>
  10. #include <thread> // for std::thread::hardware_concurrency
  11. #if defined(_WIN32)
  12. #include <windows.h>
  13. #endif
  14. static std::function<void(int)> shutdown_handler;
  15. static std::atomic_flag is_terminating = ATOMIC_FLAG_INIT;
  16. static inline void signal_handler(int signal) {
  17. if (is_terminating.test_and_set()) {
  18. // in case it hangs, we can force terminate the server by hitting Ctrl+C twice
  19. // this is for better developer experience, we can remove when the server is stable enough
  20. fprintf(stderr, "Received second interrupt, terminating immediately.\n");
  21. exit(1);
  22. }
  23. shutdown_handler(signal);
  24. }
  25. // wrapper function that handles exceptions and logs errors
  26. // this is to make sure handler_t never throws exceptions; instead, it returns an error response
  27. static server_http_context::handler_t ex_wrapper(server_http_context::handler_t func) {
  28. return [func = std::move(func)](const server_http_req & req) -> server_http_res_ptr {
  29. std::string message;
  30. try {
  31. return func(req);
  32. } catch (const std::exception & e) {
  33. message = e.what();
  34. } catch (...) {
  35. message = "unknown error";
  36. }
  37. auto res = std::make_unique<server_http_res>();
  38. res->status = 500;
  39. try {
  40. json error_data = format_error_response(message, ERROR_TYPE_SERVER);
  41. res->status = json_value(error_data, "code", 500);
  42. res->data = safe_json_to_str({{ "error", error_data }});
  43. SRV_WRN("got exception: %s\n", res->data.c_str());
  44. } catch (const std::exception & e) {
  45. SRV_ERR("got another exception: %s | while handling exception: %s\n", e.what(), message.c_str());
  46. res->data = "Internal Server Error";
  47. }
  48. return res;
  49. };
  50. }
  51. int main(int argc, char ** argv, char ** envp) {
  52. // own arguments required by this example
  53. common_params params;
  54. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SERVER)) {
  55. return 1;
  56. }
  57. // TODO: should we have a separate n_parallel parameter for the server?
  58. // https://github.com/ggml-org/llama.cpp/pull/16736#discussion_r2483763177
  59. // TODO: this is a common configuration that is suitable for most local use cases
  60. // however, overriding the parameters is a bit confusing - figure out something more intuitive
  61. if (params.n_parallel == 1 && params.kv_unified == false && !params.has_speculative()) {
  62. LOG_WRN("%s: setting n_parallel = 4 and kv_unified = true (add -kvu to disable this)\n", __func__);
  63. params.n_parallel = 4;
  64. params.kv_unified = true;
  65. }
  66. // for consistency between server router mode and single-model mode, we set the same model name as alias
  67. if (params.model_alias.empty() && !params.model.name.empty()) {
  68. params.model_alias = params.model.name;
  69. }
  70. common_init();
  71. // struct that contains llama context and inference
  72. server_context ctx_server;
  73. llama_backend_init();
  74. llama_numa_init(params.numa);
  75. LOG_INF("system info: n_threads = %d, n_threads_batch = %d, total_threads = %d\n", params.cpuparams.n_threads, params.cpuparams_batch.n_threads, std::thread::hardware_concurrency());
  76. LOG_INF("\n");
  77. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  78. LOG_INF("\n");
  79. server_http_context ctx_http;
  80. if (!ctx_http.init(params)) {
  81. LOG_ERR("%s: failed to initialize HTTP server\n", __func__);
  82. return 1;
  83. }
  84. //
  85. // Router
  86. //
  87. // register API routes
  88. server_routes routes(params, ctx_server, [&ctx_http]() { return ctx_http.is_ready.load(); });
  89. bool is_router_server = params.model.path.empty();
  90. std::optional<server_models_routes> models_routes{};
  91. if (is_router_server) {
  92. // setup server instances manager
  93. models_routes.emplace(params, argc, argv, envp);
  94. // proxy handlers
  95. // note: routes.get_health stays the same
  96. routes.get_metrics = models_routes->proxy_get;
  97. routes.post_props = models_routes->proxy_post;
  98. routes.get_api_show = models_routes->proxy_get;
  99. routes.post_completions = models_routes->proxy_post;
  100. routes.post_completions_oai = models_routes->proxy_post;
  101. routes.post_chat_completions = models_routes->proxy_post;
  102. routes.post_anthropic_messages = models_routes->proxy_post;
  103. routes.post_anthropic_count_tokens = models_routes->proxy_post;
  104. routes.post_infill = models_routes->proxy_post;
  105. routes.post_embeddings = models_routes->proxy_post;
  106. routes.post_embeddings_oai = models_routes->proxy_post;
  107. routes.post_rerank = models_routes->proxy_post;
  108. routes.post_tokenize = models_routes->proxy_post;
  109. routes.post_detokenize = models_routes->proxy_post;
  110. routes.post_apply_template = models_routes->proxy_post;
  111. routes.get_lora_adapters = models_routes->proxy_get;
  112. routes.post_lora_adapters = models_routes->proxy_post;
  113. routes.get_slots = models_routes->proxy_get;
  114. routes.post_slots = models_routes->proxy_post;
  115. // custom routes for router
  116. routes.get_props = models_routes->get_router_props;
  117. routes.get_models = models_routes->get_router_models;
  118. ctx_http.post("/models/load", ex_wrapper(models_routes->post_router_models_load));
  119. ctx_http.post("/models/unload", ex_wrapper(models_routes->post_router_models_unload));
  120. ctx_http.post("/models/status", ex_wrapper(models_routes->post_router_models_status));
  121. }
  122. ctx_http.get ("/health", ex_wrapper(routes.get_health)); // public endpoint (no API key check)
  123. ctx_http.get ("/v1/health", ex_wrapper(routes.get_health)); // public endpoint (no API key check)
  124. ctx_http.get ("/metrics", ex_wrapper(routes.get_metrics));
  125. ctx_http.get ("/props", ex_wrapper(routes.get_props));
  126. ctx_http.post("/props", ex_wrapper(routes.post_props));
  127. ctx_http.post("/api/show", ex_wrapper(routes.get_api_show));
  128. ctx_http.get ("/models", ex_wrapper(routes.get_models)); // public endpoint (no API key check)
  129. ctx_http.get ("/v1/models", ex_wrapper(routes.get_models)); // public endpoint (no API key check)
  130. ctx_http.get ("/api/tags", ex_wrapper(routes.get_models)); // ollama specific endpoint. public endpoint (no API key check)
  131. ctx_http.post("/completion", ex_wrapper(routes.post_completions)); // legacy
  132. ctx_http.post("/completions", ex_wrapper(routes.post_completions));
  133. ctx_http.post("/v1/completions", ex_wrapper(routes.post_completions_oai));
  134. ctx_http.post("/chat/completions", ex_wrapper(routes.post_chat_completions));
  135. ctx_http.post("/v1/chat/completions", ex_wrapper(routes.post_chat_completions));
  136. ctx_http.post("/api/chat", ex_wrapper(routes.post_chat_completions)); // ollama specific endpoint
  137. ctx_http.post("/v1/messages", ex_wrapper(routes.post_anthropic_messages)); // anthropic messages API
  138. ctx_http.post("/v1/messages/count_tokens", ex_wrapper(routes.post_anthropic_count_tokens)); // anthropic token counting
  139. ctx_http.post("/infill", ex_wrapper(routes.post_infill));
  140. ctx_http.post("/embedding", ex_wrapper(routes.post_embeddings)); // legacy
  141. ctx_http.post("/embeddings", ex_wrapper(routes.post_embeddings));
  142. ctx_http.post("/v1/embeddings", ex_wrapper(routes.post_embeddings_oai));
  143. ctx_http.post("/rerank", ex_wrapper(routes.post_rerank));
  144. ctx_http.post("/reranking", ex_wrapper(routes.post_rerank));
  145. ctx_http.post("/v1/rerank", ex_wrapper(routes.post_rerank));
  146. ctx_http.post("/v1/reranking", ex_wrapper(routes.post_rerank));
  147. ctx_http.post("/tokenize", ex_wrapper(routes.post_tokenize));
  148. ctx_http.post("/detokenize", ex_wrapper(routes.post_detokenize));
  149. ctx_http.post("/apply-template", ex_wrapper(routes.post_apply_template));
  150. // LoRA adapters hotswap
  151. ctx_http.get ("/lora-adapters", ex_wrapper(routes.get_lora_adapters));
  152. ctx_http.post("/lora-adapters", ex_wrapper(routes.post_lora_adapters));
  153. // Save & load slots
  154. ctx_http.get ("/slots", ex_wrapper(routes.get_slots));
  155. ctx_http.post("/slots/:id_slot", ex_wrapper(routes.post_slots));
  156. //
  157. // Start the server
  158. //
  159. std::function<void()> clean_up;
  160. if (is_router_server) {
  161. LOG_INF("%s: starting router server, no model will be loaded in this process\n", __func__);
  162. clean_up = [&models_routes]() {
  163. SRV_INF("%s: cleaning up before exit...\n", __func__);
  164. if (models_routes.has_value()) {
  165. models_routes->models.unload_all();
  166. }
  167. llama_backend_free();
  168. };
  169. if (!ctx_http.start()) {
  170. clean_up();
  171. LOG_ERR("%s: exiting due to HTTP server error\n", __func__);
  172. return 1;
  173. }
  174. ctx_http.is_ready.store(true);
  175. shutdown_handler = [&](int) {
  176. ctx_http.stop();
  177. };
  178. } else {
  179. // setup clean up function, to be called before exit
  180. clean_up = [&ctx_http, &ctx_server]() {
  181. SRV_INF("%s: cleaning up before exit...\n", __func__);
  182. ctx_http.stop();
  183. ctx_server.terminate();
  184. llama_backend_free();
  185. };
  186. // start the HTTP server before loading the model to be able to serve /health requests
  187. if (!ctx_http.start()) {
  188. clean_up();
  189. LOG_ERR("%s: exiting due to HTTP server error\n", __func__);
  190. return 1;
  191. }
  192. // load the model
  193. LOG_INF("%s: loading model\n", __func__);
  194. if (!ctx_server.load_model(params)) {
  195. clean_up();
  196. if (ctx_http.thread.joinable()) {
  197. ctx_http.thread.join();
  198. }
  199. LOG_ERR("%s: exiting due to model loading error\n", __func__);
  200. return 1;
  201. }
  202. ctx_server.init();
  203. ctx_http.is_ready.store(true);
  204. LOG_INF("%s: model loaded\n", __func__);
  205. shutdown_handler = [&](int) {
  206. // this will unblock start_loop()
  207. ctx_server.terminate();
  208. };
  209. }
  210. // TODO: refactor in common/console
  211. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  212. struct sigaction sigint_action;
  213. sigint_action.sa_handler = signal_handler;
  214. sigemptyset (&sigint_action.sa_mask);
  215. sigint_action.sa_flags = 0;
  216. sigaction(SIGINT, &sigint_action, NULL);
  217. sigaction(SIGTERM, &sigint_action, NULL);
  218. #elif defined (_WIN32)
  219. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  220. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  221. };
  222. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  223. #endif
  224. if (is_router_server) {
  225. LOG_INF("%s: router server is listening on %s\n", __func__, ctx_http.listening_address.c_str());
  226. LOG_INF("%s: NOTE: router mode is experimental\n", __func__);
  227. LOG_INF("%s: it is not recommended to use this mode in untrusted environments\n", __func__);
  228. if (ctx_http.thread.joinable()) {
  229. ctx_http.thread.join(); // keep the main thread alive
  230. }
  231. // when the HTTP server stops, clean up and exit
  232. clean_up();
  233. } else {
  234. LOG_INF("%s: server is listening on %s\n", __func__, ctx_http.listening_address.c_str());
  235. LOG_INF("%s: starting the main loop...\n", __func__);
  236. // optionally, notify router server that this instance is ready
  237. const char * router_port = std::getenv("LLAMA_SERVER_ROUTER_PORT");
  238. std::thread monitor_thread;
  239. if (router_port != nullptr) {
  240. monitor_thread = server_models::setup_child_server(params, std::atoi(router_port), params.model_alias, shutdown_handler);
  241. }
  242. // this call blocks the main thread until queue_tasks.terminate() is called
  243. ctx_server.start_loop();
  244. clean_up();
  245. if (ctx_http.thread.joinable()) {
  246. ctx_http.thread.join();
  247. }
  248. if (monitor_thread.joinable()) {
  249. monitor_thread.join();
  250. }
  251. llama_memory_breakdown_print(ctx_server.get_llama_context());
  252. }
  253. return 0;
  254. }