1
0

run.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. #if defined(_WIN32)
  2. # include <windows.h>
  3. #else
  4. # include <unistd.h>
  5. #endif
  6. #if defined(LLAMA_USE_CURL)
  7. # include <curl/curl.h>
  8. #endif
  9. #include <cstdarg>
  10. #include <cstdio>
  11. #include <cstring>
  12. #include <filesystem>
  13. #include <iostream>
  14. #include <sstream>
  15. #include <string>
  16. #include <vector>
  17. #include "common.h"
  18. #include "json.hpp"
  19. #include "llama-cpp.h"
  20. #define printe(...) \
  21. do { \
  22. fprintf(stderr, __VA_ARGS__); \
  23. } while (0)
  24. class Opt {
  25. public:
  26. int init(int argc, const char ** argv) {
  27. construct_help_str_();
  28. // Parse arguments
  29. if (parse(argc, argv)) {
  30. printe("Error: Failed to parse arguments.\n");
  31. help();
  32. return 1;
  33. }
  34. // If help is requested, show help and exit
  35. if (help_) {
  36. help();
  37. return 2;
  38. }
  39. return 0; // Success
  40. }
  41. std::string model_;
  42. std::string user_;
  43. int context_size_ = 2048, ngl_ = -1;
  44. private:
  45. std::string help_str_;
  46. bool help_ = false;
  47. void construct_help_str_() {
  48. help_str_ =
  49. "Description:\n"
  50. " Runs a llm\n"
  51. "\n"
  52. "Usage:\n"
  53. " llama-run [options] model [prompt]\n"
  54. "\n"
  55. "Options:\n"
  56. " -c, --context-size <value>\n"
  57. " Context size (default: " +
  58. std::to_string(context_size_);
  59. help_str_ +=
  60. ")\n"
  61. " -n, --ngl <value>\n"
  62. " Number of GPU layers (default: " +
  63. std::to_string(ngl_);
  64. help_str_ +=
  65. ")\n"
  66. " -h, --help\n"
  67. " Show help message\n"
  68. "\n"
  69. "Commands:\n"
  70. " model\n"
  71. " Model is a string with an optional prefix of \n"
  72. " huggingface:// (hf://), ollama://, https:// or file://.\n"
  73. " If no protocol is specified and a file exists in the specified\n"
  74. " path, file:// is assumed, otherwise if a file does not exist in\n"
  75. " the specified path, ollama:// is assumed. Models that are being\n"
  76. " pulled are downloaded with .partial extension while being\n"
  77. " downloaded and then renamed as the file without the .partial\n"
  78. " extension when complete.\n"
  79. "\n"
  80. "Examples:\n"
  81. " llama-run llama3\n"
  82. " llama-run ollama://granite-code\n"
  83. " llama-run ollama://smollm:135m\n"
  84. " llama-run hf://QuantFactory/SmolLM-135M-GGUF/SmolLM-135M.Q2_K.gguf\n"
  85. " llama-run huggingface://bartowski/SmolLM-1.7B-Instruct-v0.2-GGUF/SmolLM-1.7B-Instruct-v0.2-IQ3_M.gguf\n"
  86. " llama-run https://example.com/some-file1.gguf\n"
  87. " llama-run some-file2.gguf\n"
  88. " llama-run file://some-file3.gguf\n"
  89. " llama-run --ngl 99 some-file4.gguf\n"
  90. " llama-run --ngl 99 some-file5.gguf Hello World\n";
  91. }
  92. int parse(int argc, const char ** argv) {
  93. int positional_args_i = 0;
  94. for (int i = 1; i < argc; ++i) {
  95. if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--context-size") == 0) {
  96. if (i + 1 >= argc) {
  97. return 1;
  98. }
  99. context_size_ = std::atoi(argv[++i]);
  100. } else if (strcmp(argv[i], "-n") == 0 || strcmp(argv[i], "--ngl") == 0) {
  101. if (i + 1 >= argc) {
  102. return 1;
  103. }
  104. ngl_ = std::atoi(argv[++i]);
  105. } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
  106. help_ = true;
  107. return 0;
  108. } else if (!positional_args_i) {
  109. ++positional_args_i;
  110. model_ = argv[i];
  111. } else if (positional_args_i == 1) {
  112. ++positional_args_i;
  113. user_ = argv[i];
  114. } else {
  115. user_ += " " + std::string(argv[i]);
  116. }
  117. }
  118. return model_.empty(); // model_ is the only required value
  119. }
  120. void help() const { printf("%s", help_str_.c_str()); }
  121. };
  122. struct progress_data {
  123. size_t file_size = 0;
  124. std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now();
  125. bool printed = false;
  126. };
  127. struct FileDeleter {
  128. void operator()(FILE * file) const {
  129. if (file) {
  130. fclose(file);
  131. }
  132. }
  133. };
  134. typedef std::unique_ptr<FILE, FileDeleter> FILE_ptr;
  135. #ifdef LLAMA_USE_CURL
  136. class CurlWrapper {
  137. public:
  138. int init(const std::string & url, const std::vector<std::string> & headers, const std::string & output_file,
  139. const bool progress, std::string * response_str = nullptr) {
  140. std::string output_file_partial;
  141. curl = curl_easy_init();
  142. if (!curl) {
  143. return 1;
  144. }
  145. progress_data data;
  146. FILE_ptr out;
  147. if (!output_file.empty()) {
  148. output_file_partial = output_file + ".partial";
  149. out.reset(fopen(output_file_partial.c_str(), "ab"));
  150. }
  151. set_write_options(response_str, out);
  152. data.file_size = set_resume_point(output_file_partial);
  153. set_progress_options(progress, data);
  154. set_headers(headers);
  155. perform(url);
  156. if (!output_file.empty()) {
  157. std::filesystem::rename(output_file_partial, output_file);
  158. }
  159. return 0;
  160. }
  161. ~CurlWrapper() {
  162. if (chunk) {
  163. curl_slist_free_all(chunk);
  164. }
  165. if (curl) {
  166. curl_easy_cleanup(curl);
  167. }
  168. }
  169. private:
  170. CURL * curl = nullptr;
  171. struct curl_slist * chunk = nullptr;
  172. void set_write_options(std::string * response_str, const FILE_ptr & out) {
  173. if (response_str) {
  174. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, capture_data);
  175. curl_easy_setopt(curl, CURLOPT_WRITEDATA, response_str);
  176. } else {
  177. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  178. curl_easy_setopt(curl, CURLOPT_WRITEDATA, out.get());
  179. }
  180. }
  181. size_t set_resume_point(const std::string & output_file) {
  182. size_t file_size = 0;
  183. if (std::filesystem::exists(output_file)) {
  184. file_size = std::filesystem::file_size(output_file);
  185. curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, static_cast<curl_off_t>(file_size));
  186. }
  187. return file_size;
  188. }
  189. void set_progress_options(bool progress, progress_data & data) {
  190. if (progress) {
  191. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  192. curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &data);
  193. curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
  194. }
  195. }
  196. void set_headers(const std::vector<std::string> & headers) {
  197. if (!headers.empty()) {
  198. if (chunk) {
  199. curl_slist_free_all(chunk);
  200. chunk = 0;
  201. }
  202. for (const auto & header : headers) {
  203. chunk = curl_slist_append(chunk, header.c_str());
  204. }
  205. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
  206. }
  207. }
  208. void perform(const std::string & url) {
  209. CURLcode res;
  210. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  211. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  212. curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  213. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
  214. res = curl_easy_perform(curl);
  215. if (res != CURLE_OK) {
  216. printe("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
  217. }
  218. }
  219. static std::string human_readable_time(double seconds) {
  220. int hrs = static_cast<int>(seconds) / 3600;
  221. int mins = (static_cast<int>(seconds) % 3600) / 60;
  222. int secs = static_cast<int>(seconds) % 60;
  223. std::ostringstream out;
  224. if (hrs > 0) {
  225. out << hrs << "h " << std::setw(2) << std::setfill('0') << mins << "m " << std::setw(2) << std::setfill('0')
  226. << secs << "s";
  227. } else if (mins > 0) {
  228. out << mins << "m " << std::setw(2) << std::setfill('0') << secs << "s";
  229. } else {
  230. out << secs << "s";
  231. }
  232. return out.str();
  233. }
  234. static std::string human_readable_size(curl_off_t size) {
  235. static const char * suffix[] = { "B", "KB", "MB", "GB", "TB" };
  236. char length = sizeof(suffix) / sizeof(suffix[0]);
  237. int i = 0;
  238. double dbl_size = size;
  239. if (size > 1024) {
  240. for (i = 0; (size / 1024) > 0 && i < length - 1; i++, size /= 1024) {
  241. dbl_size = size / 1024.0;
  242. }
  243. }
  244. std::ostringstream out;
  245. out << std::fixed << std::setprecision(2) << dbl_size << " " << suffix[i];
  246. return out.str();
  247. }
  248. static int progress_callback(void * ptr, curl_off_t total_to_download, curl_off_t now_downloaded, curl_off_t,
  249. curl_off_t) {
  250. progress_data * data = static_cast<progress_data *>(ptr);
  251. if (total_to_download <= 0) {
  252. return 0;
  253. }
  254. total_to_download += data->file_size;
  255. const curl_off_t now_downloaded_plus_file_size = now_downloaded + data->file_size;
  256. const curl_off_t percentage = (now_downloaded_plus_file_size * 100) / total_to_download;
  257. const curl_off_t pos = (percentage / 5);
  258. std::string progress_bar;
  259. for (int i = 0; i < 20; ++i) {
  260. progress_bar.append((i < pos) ? "█" : " ");
  261. }
  262. // Calculate download speed and estimated time to completion
  263. const auto now = std::chrono::steady_clock::now();
  264. const std::chrono::duration<double> elapsed_seconds = now - data->start_time;
  265. const double speed = now_downloaded / elapsed_seconds.count();
  266. const double estimated_time = (total_to_download - now_downloaded) / speed;
  267. printe("\r%ld%% |%s| %s/%s %.2f MB/s %s ", percentage, progress_bar.c_str(),
  268. human_readable_size(now_downloaded).c_str(), human_readable_size(total_to_download).c_str(),
  269. speed / (1024 * 1024), human_readable_time(estimated_time).c_str());
  270. fflush(stderr);
  271. data->printed = true;
  272. return 0;
  273. }
  274. // Function to write data to a file
  275. static size_t write_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  276. FILE * out = static_cast<FILE *>(stream);
  277. return fwrite(ptr, size, nmemb, out);
  278. }
  279. // Function to capture data into a string
  280. static size_t capture_data(void * ptr, size_t size, size_t nmemb, void * stream) {
  281. std::string * str = static_cast<std::string *>(stream);
  282. str->append(static_cast<char *>(ptr), size * nmemb);
  283. return size * nmemb;
  284. }
  285. };
  286. #endif
  287. class LlamaData {
  288. public:
  289. llama_model_ptr model;
  290. llama_sampler_ptr sampler;
  291. llama_context_ptr context;
  292. std::vector<llama_chat_message> messages;
  293. std::vector<std::string> msg_strs;
  294. std::vector<char> fmtted;
  295. int init(Opt & opt) {
  296. model = initialize_model(opt);
  297. if (!model) {
  298. return 1;
  299. }
  300. context = initialize_context(model, opt.context_size_);
  301. if (!context) {
  302. return 1;
  303. }
  304. sampler = initialize_sampler();
  305. return 0;
  306. }
  307. private:
  308. #ifdef LLAMA_USE_CURL
  309. int download(const std::string & url, const std::vector<std::string> & headers, const std::string & output_file,
  310. const bool progress, std::string * response_str = nullptr) {
  311. CurlWrapper curl;
  312. if (curl.init(url, headers, output_file, progress, response_str)) {
  313. return 1;
  314. }
  315. return 0;
  316. }
  317. #else
  318. int download(const std::string &, const std::vector<std::string> &, const std::string &, const bool,
  319. std::string * = nullptr) {
  320. printe("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  321. return 1;
  322. }
  323. #endif
  324. int huggingface_dl(const std::string & model, const std::vector<std::string> headers, const std::string & bn) {
  325. // Find the second occurrence of '/' after protocol string
  326. size_t pos = model.find('/');
  327. pos = model.find('/', pos + 1);
  328. if (pos == std::string::npos) {
  329. return 1;
  330. }
  331. const std::string hfr = model.substr(0, pos);
  332. const std::string hff = model.substr(pos + 1);
  333. const std::string url = "https://huggingface.co/" + hfr + "/resolve/main/" + hff;
  334. return download(url, headers, bn, true);
  335. }
  336. int ollama_dl(std::string & model, const std::vector<std::string> headers, const std::string & bn) {
  337. if (model.find('/') == std::string::npos) {
  338. model = "library/" + model;
  339. }
  340. std::string model_tag = "latest";
  341. size_t colon_pos = model.find(':');
  342. if (colon_pos != std::string::npos) {
  343. model_tag = model.substr(colon_pos + 1);
  344. model = model.substr(0, colon_pos);
  345. }
  346. std::string manifest_url = "https://registry.ollama.ai/v2/" + model + "/manifests/" + model_tag;
  347. std::string manifest_str;
  348. const int ret = download(manifest_url, headers, "", false, &manifest_str);
  349. if (ret) {
  350. return ret;
  351. }
  352. nlohmann::json manifest = nlohmann::json::parse(manifest_str);
  353. std::string layer;
  354. for (const auto & l : manifest["layers"]) {
  355. if (l["mediaType"] == "application/vnd.ollama.image.model") {
  356. layer = l["digest"];
  357. break;
  358. }
  359. }
  360. std::string blob_url = "https://registry.ollama.ai/v2/" + model + "/blobs/" + layer;
  361. return download(blob_url, headers, bn, true);
  362. }
  363. std::string basename(const std::string & path) {
  364. const size_t pos = path.find_last_of("/\\");
  365. if (pos == std::string::npos) {
  366. return path;
  367. }
  368. return path.substr(pos + 1);
  369. }
  370. int remove_proto(std::string & model_) {
  371. const std::string::size_type pos = model_.find("://");
  372. if (pos == std::string::npos) {
  373. return 1;
  374. }
  375. model_ = model_.substr(pos + 3); // Skip past "://"
  376. return 0;
  377. }
  378. int resolve_model(std::string & model_) {
  379. const std::string bn = basename(model_);
  380. const std::vector<std::string> headers = { "--header",
  381. "Accept: application/vnd.docker.distribution.manifest.v2+json" };
  382. int ret = 0;
  383. if (string_starts_with(model_, "file://") || std::filesystem::exists(bn)) {
  384. remove_proto(model_);
  385. } else if (string_starts_with(model_, "hf://") || string_starts_with(model_, "huggingface://")) {
  386. remove_proto(model_);
  387. ret = huggingface_dl(model_, headers, bn);
  388. } else if (string_starts_with(model_, "ollama://")) {
  389. remove_proto(model_);
  390. ret = ollama_dl(model_, headers, bn);
  391. } else if (string_starts_with(model_, "https://")) {
  392. download(model_, headers, bn, true);
  393. } else {
  394. ret = ollama_dl(model_, headers, bn);
  395. }
  396. model_ = bn;
  397. return ret;
  398. }
  399. // Initializes the model and returns a unique pointer to it
  400. llama_model_ptr initialize_model(Opt & opt) {
  401. ggml_backend_load_all();
  402. llama_model_params model_params = llama_model_default_params();
  403. model_params.n_gpu_layers = opt.ngl_ >= 0 ? opt.ngl_ : model_params.n_gpu_layers;
  404. resolve_model(opt.model_);
  405. llama_model_ptr model(llama_load_model_from_file(opt.model_.c_str(), model_params));
  406. if (!model) {
  407. printe("%s: error: unable to load model from file: %s\n", __func__, opt.model_.c_str());
  408. }
  409. return model;
  410. }
  411. // Initializes the context with the specified parameters
  412. llama_context_ptr initialize_context(const llama_model_ptr & model, const int n_ctx) {
  413. llama_context_params ctx_params = llama_context_default_params();
  414. ctx_params.n_ctx = n_ctx;
  415. ctx_params.n_batch = n_ctx;
  416. llama_context_ptr context(llama_new_context_with_model(model.get(), ctx_params));
  417. if (!context) {
  418. printe("%s: error: failed to create the llama_context\n", __func__);
  419. }
  420. return context;
  421. }
  422. // Initializes and configures the sampler
  423. llama_sampler_ptr initialize_sampler() {
  424. llama_sampler_ptr sampler(llama_sampler_chain_init(llama_sampler_chain_default_params()));
  425. llama_sampler_chain_add(sampler.get(), llama_sampler_init_min_p(0.05f, 1));
  426. llama_sampler_chain_add(sampler.get(), llama_sampler_init_temp(0.8f));
  427. llama_sampler_chain_add(sampler.get(), llama_sampler_init_dist(LLAMA_DEFAULT_SEED));
  428. return sampler;
  429. }
  430. };
  431. // Add a message to `messages` and store its content in `msg_strs`
  432. static void add_message(const char * role, const std::string & text, LlamaData & llama_data) {
  433. llama_data.msg_strs.push_back(std::move(text));
  434. llama_data.messages.push_back({ role, llama_data.msg_strs.back().c_str() });
  435. }
  436. // Function to apply the chat template and resize `formatted` if needed
  437. static int apply_chat_template(LlamaData & llama_data, const bool append) {
  438. int result = llama_chat_apply_template(
  439. llama_data.model.get(), nullptr, llama_data.messages.data(), llama_data.messages.size(), append,
  440. append ? llama_data.fmtted.data() : nullptr, append ? llama_data.fmtted.size() : 0);
  441. if (append && result > static_cast<int>(llama_data.fmtted.size())) {
  442. llama_data.fmtted.resize(result);
  443. result = llama_chat_apply_template(llama_data.model.get(), nullptr, llama_data.messages.data(),
  444. llama_data.messages.size(), append, llama_data.fmtted.data(),
  445. llama_data.fmtted.size());
  446. }
  447. return result;
  448. }
  449. // Function to tokenize the prompt
  450. static int tokenize_prompt(const llama_model_ptr & model, const std::string & prompt,
  451. std::vector<llama_token> & prompt_tokens) {
  452. const int n_prompt_tokens = -llama_tokenize(model.get(), prompt.c_str(), prompt.size(), NULL, 0, true, true);
  453. prompt_tokens.resize(n_prompt_tokens);
  454. if (llama_tokenize(model.get(), prompt.c_str(), prompt.size(), prompt_tokens.data(), prompt_tokens.size(), true,
  455. true) < 0) {
  456. printe("failed to tokenize the prompt\n");
  457. return -1;
  458. }
  459. return n_prompt_tokens;
  460. }
  461. // Check if we have enough space in the context to evaluate this batch
  462. static int check_context_size(const llama_context_ptr & ctx, const llama_batch & batch) {
  463. const int n_ctx = llama_n_ctx(ctx.get());
  464. const int n_ctx_used = llama_get_kv_cache_used_cells(ctx.get());
  465. if (n_ctx_used + batch.n_tokens > n_ctx) {
  466. printf("\033[0m\n");
  467. printe("context size exceeded\n");
  468. return 1;
  469. }
  470. return 0;
  471. }
  472. // convert the token to a string
  473. static int convert_token_to_string(const llama_model_ptr & model, const llama_token token_id, std::string & piece) {
  474. char buf[256];
  475. int n = llama_token_to_piece(model.get(), token_id, buf, sizeof(buf), 0, true);
  476. if (n < 0) {
  477. printe("failed to convert token to piece\n");
  478. return 1;
  479. }
  480. piece = std::string(buf, n);
  481. return 0;
  482. }
  483. static void print_word_and_concatenate_to_response(const std::string & piece, std::string & response) {
  484. printf("%s", piece.c_str());
  485. fflush(stdout);
  486. response += piece;
  487. }
  488. // helper function to evaluate a prompt and generate a response
  489. static int generate(LlamaData & llama_data, const std::string & prompt, std::string & response) {
  490. std::vector<llama_token> tokens;
  491. if (tokenize_prompt(llama_data.model, prompt, tokens) < 0) {
  492. return 1;
  493. }
  494. // prepare a batch for the prompt
  495. llama_batch batch = llama_batch_get_one(tokens.data(), tokens.size());
  496. llama_token new_token_id;
  497. while (true) {
  498. check_context_size(llama_data.context, batch);
  499. if (llama_decode(llama_data.context.get(), batch)) {
  500. printe("failed to decode\n");
  501. return 1;
  502. }
  503. // sample the next token, check is it an end of generation?
  504. new_token_id = llama_sampler_sample(llama_data.sampler.get(), llama_data.context.get(), -1);
  505. if (llama_token_is_eog(llama_data.model.get(), new_token_id)) {
  506. break;
  507. }
  508. std::string piece;
  509. if (convert_token_to_string(llama_data.model, new_token_id, piece)) {
  510. return 1;
  511. }
  512. print_word_and_concatenate_to_response(piece, response);
  513. // prepare the next batch with the sampled token
  514. batch = llama_batch_get_one(&new_token_id, 1);
  515. }
  516. return 0;
  517. }
  518. static int read_user_input(std::string & user) {
  519. std::getline(std::cin, user);
  520. return user.empty(); // Should have data in happy path
  521. }
  522. // Function to generate a response based on the prompt
  523. static int generate_response(LlamaData & llama_data, const std::string & prompt, std::string & response) {
  524. // Set response color
  525. printf("\033[33m");
  526. if (generate(llama_data, prompt, response)) {
  527. printe("failed to generate response\n");
  528. return 1;
  529. }
  530. // End response with color reset and newline
  531. printf("\n\033[0m");
  532. return 0;
  533. }
  534. // Helper function to apply the chat template and handle errors
  535. static int apply_chat_template_with_error_handling(LlamaData & llama_data, const bool append, int & output_length) {
  536. const int new_len = apply_chat_template(llama_data, append);
  537. if (new_len < 0) {
  538. printe("failed to apply the chat template\n");
  539. return -1;
  540. }
  541. output_length = new_len;
  542. return 0;
  543. }
  544. // Helper function to handle user input
  545. static int handle_user_input(std::string & user_input, const std::string & user_) {
  546. if (!user_.empty()) {
  547. user_input = user_;
  548. return 0; // No need for interactive input
  549. }
  550. printf(
  551. "\r "
  552. "\r\033[32m> \033[0m");
  553. return read_user_input(user_input); // Returns true if input ends the loop
  554. }
  555. // Function to tokenize the prompt
  556. static int chat_loop(LlamaData & llama_data, const std::string & user_) {
  557. int prev_len = 0;
  558. llama_data.fmtted.resize(llama_n_ctx(llama_data.context.get()));
  559. while (true) {
  560. // Get user input
  561. std::string user_input;
  562. while (handle_user_input(user_input, user_)) {
  563. }
  564. add_message("user", user_.empty() ? user_input : user_, llama_data);
  565. int new_len;
  566. if (apply_chat_template_with_error_handling(llama_data, true, new_len) < 0) {
  567. return 1;
  568. }
  569. std::string prompt(llama_data.fmtted.begin() + prev_len, llama_data.fmtted.begin() + new_len);
  570. std::string response;
  571. if (generate_response(llama_data, prompt, response)) {
  572. return 1;
  573. }
  574. if (!user_.empty()) {
  575. break;
  576. }
  577. add_message("assistant", response, llama_data);
  578. if (apply_chat_template_with_error_handling(llama_data, false, prev_len) < 0) {
  579. return 1;
  580. }
  581. }
  582. return 0;
  583. }
  584. static void log_callback(const enum ggml_log_level level, const char * text, void *) {
  585. if (level == GGML_LOG_LEVEL_ERROR) {
  586. printe("%s", text);
  587. }
  588. }
  589. static bool is_stdin_a_terminal() {
  590. #if defined(_WIN32)
  591. HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
  592. DWORD mode;
  593. return GetConsoleMode(hStdin, &mode);
  594. #else
  595. return isatty(STDIN_FILENO);
  596. #endif
  597. }
  598. static std::string read_pipe_data() {
  599. std::ostringstream result;
  600. result << std::cin.rdbuf(); // Read all data from std::cin
  601. return result.str();
  602. }
  603. int main(int argc, const char ** argv) {
  604. Opt opt;
  605. const int ret = opt.init(argc, argv);
  606. if (ret == 2) {
  607. return 0;
  608. } else if (ret) {
  609. return 1;
  610. }
  611. if (!is_stdin_a_terminal()) {
  612. if (!opt.user_.empty()) {
  613. opt.user_ += "\n\n";
  614. }
  615. opt.user_ += read_pipe_data();
  616. }
  617. llama_log_set(log_callback, nullptr);
  618. LlamaData llama_data;
  619. if (llama_data.init(opt)) {
  620. return 1;
  621. }
  622. if (chat_loop(llama_data, opt.user_)) {
  623. return 1;
  624. }
  625. return 0;
  626. }