server.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. error_type error;
  31. try {
  32. return func(req);
  33. } catch (const std::invalid_argument & e) {
  34. // treat invalid_argument as invalid request (400)
  35. error = ERROR_TYPE_INVALID_REQUEST;
  36. message = e.what();
  37. } catch (const std::exception & e) {
  38. // treat other exceptions as server error (500)
  39. error = ERROR_TYPE_SERVER;
  40. message = e.what();
  41. } catch (...) {
  42. error = ERROR_TYPE_SERVER;
  43. message = "unknown error";
  44. }
  45. auto res = std::make_unique<server_http_res>();
  46. res->status = 500;
  47. try {
  48. json error_data = format_error_response(message, error);
  49. res->status = json_value(error_data, "code", 500);
  50. res->data = safe_json_to_str({{ "error", error_data }});
  51. SRV_WRN("got exception: %s\n", res->data.c_str());
  52. } catch (const std::exception & e) {
  53. SRV_ERR("got another exception: %s | while handling exception: %s\n", e.what(), message.c_str());
  54. res->data = "Internal Server Error";
  55. }
  56. return res;
  57. };
  58. }
  59. int main(int argc, char ** argv, char ** envp) {
  60. // own arguments required by this example
  61. common_params params;
  62. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SERVER)) {
  63. return 1;
  64. }
  65. if (params.n_parallel < 0) {
  66. LOG_INF("%s: n_parallel is set to auto, using n_parallel = 4 and kv_unified = true\n", __func__);
  67. params.n_parallel = 4;
  68. params.kv_unified = true;
  69. }
  70. // for consistency between server router mode and single-model mode, we set the same model name as alias
  71. if (params.model_alias.empty() && !params.model.name.empty()) {
  72. params.model_alias = params.model.name;
  73. }
  74. common_init();
  75. // struct that contains llama context and inference
  76. server_context ctx_server;
  77. llama_backend_init();
  78. llama_numa_init(params.numa);
  79. 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());
  80. LOG_INF("\n");
  81. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  82. LOG_INF("\n");
  83. server_http_context ctx_http;
  84. if (!ctx_http.init(params)) {
  85. LOG_ERR("%s: failed to initialize HTTP server\n", __func__);
  86. return 1;
  87. }
  88. //
  89. // Router
  90. //
  91. // register API routes
  92. server_routes routes(params, ctx_server, [&ctx_http]() { return ctx_http.is_ready.load(); });
  93. bool is_router_server = params.model.path.empty();
  94. std::optional<server_models_routes> models_routes{};
  95. if (is_router_server) {
  96. // setup server instances manager
  97. models_routes.emplace(params, argc, argv, envp);
  98. // proxy handlers
  99. // note: routes.get_health stays the same
  100. routes.get_metrics = models_routes->proxy_get;
  101. routes.post_props = models_routes->proxy_post;
  102. routes.get_api_show = models_routes->proxy_get;
  103. routes.post_completions = models_routes->proxy_post;
  104. routes.post_completions_oai = models_routes->proxy_post;
  105. routes.post_chat_completions = models_routes->proxy_post;
  106. routes.post_anthropic_messages = models_routes->proxy_post;
  107. routes.post_anthropic_count_tokens = models_routes->proxy_post;
  108. routes.post_infill = models_routes->proxy_post;
  109. routes.post_embeddings = models_routes->proxy_post;
  110. routes.post_embeddings_oai = models_routes->proxy_post;
  111. routes.post_rerank = models_routes->proxy_post;
  112. routes.post_tokenize = models_routes->proxy_post;
  113. routes.post_detokenize = models_routes->proxy_post;
  114. routes.post_apply_template = models_routes->proxy_post;
  115. routes.get_lora_adapters = models_routes->proxy_get;
  116. routes.post_lora_adapters = models_routes->proxy_post;
  117. routes.get_slots = models_routes->proxy_get;
  118. routes.post_slots = models_routes->proxy_post;
  119. // custom routes for router
  120. routes.get_props = models_routes->get_router_props;
  121. routes.get_models = models_routes->get_router_models;
  122. ctx_http.post("/models/load", ex_wrapper(models_routes->post_router_models_load));
  123. ctx_http.post("/models/unload", ex_wrapper(models_routes->post_router_models_unload));
  124. ctx_http.post("/models/status", ex_wrapper(models_routes->post_router_models_status));
  125. }
  126. ctx_http.get ("/health", ex_wrapper(routes.get_health)); // public endpoint (no API key check)
  127. ctx_http.get ("/v1/health", ex_wrapper(routes.get_health)); // public endpoint (no API key check)
  128. ctx_http.get ("/metrics", ex_wrapper(routes.get_metrics));
  129. ctx_http.get ("/props", ex_wrapper(routes.get_props));
  130. ctx_http.post("/props", ex_wrapper(routes.post_props));
  131. ctx_http.post("/api/show", ex_wrapper(routes.get_api_show));
  132. ctx_http.get ("/models", ex_wrapper(routes.get_models)); // public endpoint (no API key check)
  133. ctx_http.get ("/v1/models", ex_wrapper(routes.get_models)); // public endpoint (no API key check)
  134. ctx_http.get ("/api/tags", ex_wrapper(routes.get_models)); // ollama specific endpoint. public endpoint (no API key check)
  135. ctx_http.post("/completion", ex_wrapper(routes.post_completions)); // legacy
  136. ctx_http.post("/completions", ex_wrapper(routes.post_completions));
  137. ctx_http.post("/v1/completions", ex_wrapper(routes.post_completions_oai));
  138. ctx_http.post("/chat/completions", ex_wrapper(routes.post_chat_completions));
  139. ctx_http.post("/v1/chat/completions", ex_wrapper(routes.post_chat_completions));
  140. ctx_http.post("/api/chat", ex_wrapper(routes.post_chat_completions)); // ollama specific endpoint
  141. ctx_http.post("/v1/messages", ex_wrapper(routes.post_anthropic_messages)); // anthropic messages API
  142. ctx_http.post("/v1/messages/count_tokens", ex_wrapper(routes.post_anthropic_count_tokens)); // anthropic token counting
  143. ctx_http.post("/infill", ex_wrapper(routes.post_infill));
  144. ctx_http.post("/embedding", ex_wrapper(routes.post_embeddings)); // legacy
  145. ctx_http.post("/embeddings", ex_wrapper(routes.post_embeddings));
  146. ctx_http.post("/v1/embeddings", ex_wrapper(routes.post_embeddings_oai));
  147. ctx_http.post("/rerank", ex_wrapper(routes.post_rerank));
  148. ctx_http.post("/reranking", ex_wrapper(routes.post_rerank));
  149. ctx_http.post("/v1/rerank", ex_wrapper(routes.post_rerank));
  150. ctx_http.post("/v1/reranking", ex_wrapper(routes.post_rerank));
  151. ctx_http.post("/tokenize", ex_wrapper(routes.post_tokenize));
  152. ctx_http.post("/detokenize", ex_wrapper(routes.post_detokenize));
  153. ctx_http.post("/apply-template", ex_wrapper(routes.post_apply_template));
  154. // LoRA adapters hotswap
  155. ctx_http.get ("/lora-adapters", ex_wrapper(routes.get_lora_adapters));
  156. ctx_http.post("/lora-adapters", ex_wrapper(routes.post_lora_adapters));
  157. // Save & load slots
  158. ctx_http.get ("/slots", ex_wrapper(routes.get_slots));
  159. ctx_http.post("/slots/:id_slot", ex_wrapper(routes.post_slots));
  160. //
  161. // Start the server
  162. //
  163. std::function<void()> clean_up;
  164. if (is_router_server) {
  165. LOG_INF("%s: starting router server, no model will be loaded in this process\n", __func__);
  166. clean_up = [&models_routes]() {
  167. SRV_INF("%s: cleaning up before exit...\n", __func__);
  168. if (models_routes.has_value()) {
  169. models_routes->models.unload_all();
  170. }
  171. llama_backend_free();
  172. };
  173. if (!ctx_http.start()) {
  174. clean_up();
  175. LOG_ERR("%s: exiting due to HTTP server error\n", __func__);
  176. return 1;
  177. }
  178. ctx_http.is_ready.store(true);
  179. shutdown_handler = [&](int) {
  180. ctx_http.stop();
  181. };
  182. } else {
  183. // setup clean up function, to be called before exit
  184. clean_up = [&ctx_http, &ctx_server]() {
  185. SRV_INF("%s: cleaning up before exit...\n", __func__);
  186. ctx_http.stop();
  187. ctx_server.terminate();
  188. llama_backend_free();
  189. };
  190. // start the HTTP server before loading the model to be able to serve /health requests
  191. if (!ctx_http.start()) {
  192. clean_up();
  193. LOG_ERR("%s: exiting due to HTTP server error\n", __func__);
  194. return 1;
  195. }
  196. // load the model
  197. LOG_INF("%s: loading model\n", __func__);
  198. if (!ctx_server.load_model(params)) {
  199. clean_up();
  200. if (ctx_http.thread.joinable()) {
  201. ctx_http.thread.join();
  202. }
  203. LOG_ERR("%s: exiting due to model loading error\n", __func__);
  204. return 1;
  205. }
  206. ctx_server.init();
  207. ctx_http.is_ready.store(true);
  208. LOG_INF("%s: model loaded\n", __func__);
  209. shutdown_handler = [&](int) {
  210. // this will unblock start_loop()
  211. ctx_server.terminate();
  212. };
  213. }
  214. // TODO: refactor in common/console
  215. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  216. struct sigaction sigint_action;
  217. sigint_action.sa_handler = signal_handler;
  218. sigemptyset (&sigint_action.sa_mask);
  219. sigint_action.sa_flags = 0;
  220. sigaction(SIGINT, &sigint_action, NULL);
  221. sigaction(SIGTERM, &sigint_action, NULL);
  222. #elif defined (_WIN32)
  223. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  224. return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false;
  225. };
  226. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  227. #endif
  228. if (is_router_server) {
  229. LOG_INF("%s: router server is listening on %s\n", __func__, ctx_http.listening_address.c_str());
  230. LOG_INF("%s: NOTE: router mode is experimental\n", __func__);
  231. LOG_INF("%s: it is not recommended to use this mode in untrusted environments\n", __func__);
  232. if (ctx_http.thread.joinable()) {
  233. ctx_http.thread.join(); // keep the main thread alive
  234. }
  235. // when the HTTP server stops, clean up and exit
  236. clean_up();
  237. } else {
  238. LOG_INF("%s: server is listening on %s\n", __func__, ctx_http.listening_address.c_str());
  239. LOG_INF("%s: starting the main loop...\n", __func__);
  240. // optionally, notify router server that this instance is ready
  241. const char * router_port = std::getenv("LLAMA_SERVER_ROUTER_PORT");
  242. std::thread monitor_thread;
  243. if (router_port != nullptr) {
  244. monitor_thread = server_models::setup_child_server(params, std::atoi(router_port), params.model_alias, shutdown_handler);
  245. }
  246. // this call blocks the main thread until queue_tasks.terminate() is called
  247. ctx_server.start_loop();
  248. clean_up();
  249. if (ctx_http.thread.joinable()) {
  250. ctx_http.thread.join();
  251. }
  252. if (monitor_thread.joinable()) {
  253. monitor_thread.join();
  254. }
  255. llama_memory_breakdown_print(ctx_server.get_llama_context());
  256. }
  257. return 0;
  258. }