From 194e60fd37959240967b78d47032bfe49d4e51bc Mon Sep 17 00:00:00 2001 From: rfprod Date: Thu, 29 Oct 2026 18:32:08 +0400 Subject: [PATCH] refactor(program): refactor ollama client, update `clang-format` - [x] increase line length in `.clang-format` to 120 characters; - [x] introduce a reusable method `fetch_web_content` to reduce duplication; --- .clang-format | 2 +- src/interface/progress_spinner.cpp | 7 +- src/interface/progress_spinner.hpp | 4 +- src/interface/user-interface.cpp | 26 ++-- src/interface/user-interface.hpp | 11 +- src/main.cpp | 3 +- src/ollama/ollama_client.cpp | 223 ++++++++++++----------------- src/ollama/ollama_client.hpp | 25 ++++ 8 files changed, 136 insertions(+), 165 deletions(-) diff --git a/.clang-format b/.clang-format index b45eb8b..7aeb0a5 100644 --- a/.clang-format +++ b/.clang-format @@ -1,7 +1,7 @@ BasedOnStyle: LLVM IndentWidth: 4 UseTab: Never -ColumnLimit: 100 +ColumnLimit: 120 AllowShortFunctionsOnASingleLine: None AllowShortIfStatementsOnASingleLine: WithoutElse AllowShortLoopsOnASingleLine: false diff --git a/src/interface/progress_spinner.cpp b/src/interface/progress_spinner.cpp index 03036ed..c69cf79 100644 --- a/src/interface/progress_spinner.cpp +++ b/src/interface/progress_spinner.cpp @@ -8,8 +8,7 @@ ProgressSpinner::ProgressSpinner() : ui(nullptr), active(false) { } -ProgressSpinner::ProgressSpinner(UserInterface* user_interface, bool activate) - : ui(user_interface), active(false) { +ProgressSpinner::ProgressSpinner(UserInterface* user_interface, bool activate) : ui(user_interface), active(false) { if (activate && ui != nullptr) { start(); } @@ -104,8 +103,8 @@ int ProgressSpinner::progress_callback_impl(curl_off_t dltotal, curl_off_t dlnow * * @return 0 to continue the operation, 1 if clientp is nullptr. */ -int ProgressSpinner::progress_callback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, - curl_off_t ultotal, curl_off_t ulnow) { +int ProgressSpinner::progress_callback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, + curl_off_t ulnow) { ProgressSpinner* self = static_cast(clientp); if (self == nullptr) { return 1; diff --git a/src/interface/progress_spinner.hpp b/src/interface/progress_spinner.hpp index 07e659e..333993d 100644 --- a/src/interface/progress_spinner.hpp +++ b/src/interface/progress_spinner.hpp @@ -159,6 +159,6 @@ class ProgressSpinner { * @note CURL calls this frequently; ensure your clientp points to a valid * ProgressSpinner instance. */ - static int progress_callback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, - curl_off_t ultotal, curl_off_t ulnow); + static int progress_callback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, + curl_off_t ulnow); }; diff --git a/src/interface/user-interface.cpp b/src/interface/user-interface.cpp index dc60fb3..4d5fba6 100644 --- a/src/interface/user-interface.cpp +++ b/src/interface/user-interface.cpp @@ -92,8 +92,7 @@ void UserInterface::init_ncurses(void) { } if (has_colors()) { - printf("DEBUG: Checking theme - use_dark_theme = %s\n", - this->use_dark_theme ? "true" : "false"); + printf("DEBUG: Checking theme - use_dark_theme = %s\n", this->use_dark_theme ? "true" : "false"); if (this->use_dark_theme == true) { this->init_dark_theme(); } else { @@ -175,8 +174,7 @@ void UserInterface::draw_input_area() { mvprintw(layout.input_y, layout.input_x + 37, "%s", input_buffer.c_str()); } -UserInterface::UserInterface() - : resize_flag(0), running(0), input_cursor_x(0), layout({}), use_dark_theme(true) { +UserInterface::UserInterface() : resize_flag(0), running(0), input_cursor_x(0), layout({}), use_dark_theme(true) { printf("DEBUG: use_dark_theme = %s\n", this->use_dark_theme ? "true" : "false"); UserInterface::instance = this; } @@ -234,8 +232,8 @@ void UserInterface::end_session(int exit_code) { exit(exit_code); } -void UserInterface::print_args(const std::string& model, const std::string& prompt, bool stream, - bool interactive, bool dark_theme) { +void UserInterface::print_args(const std::string& model, const std::string& prompt, bool stream, bool interactive, + bool dark_theme) { std::string buffer; buffer += "🛈 model = " + model + "\n"; buffer += "🛈 prompt = " + prompt + "\n"; @@ -246,8 +244,8 @@ void UserInterface::print_args(const std::string& model, const std::string& prom this->print(buffer, UserInterface::MESSAGE_TYPE_NORMAL); } -void UserInterface::print_args_noninteractive(const std::string& model, const std::string& prompt, - bool stream, bool interactive, bool dark_theme) { +void UserInterface::print_args_noninteractive(const std::string& model, const std::string& prompt, bool stream, + bool interactive, bool dark_theme) { printf("\n"); printf("🛈 model = %s\n", model.c_str()); printf("🛈 prompt = %s\n", prompt.c_str()); @@ -318,8 +316,7 @@ void UserInterface::select_model(const std::vector& models, std::st } } -void UserInterface::select_model_noninteractive(const std::vector& models, - std::string* model) { +void UserInterface::select_model_noninteractive(const std::vector& models, std::string* model) { int index{}; int read_result{}; @@ -500,8 +497,7 @@ void UserInterface::render_loop(void) { std::unique_lock lock(this->ui_mutex); // Wait for redraw request or timeout (100ms) - this->cv_redraw.wait_for(lock, std::chrono::milliseconds(1500), - [this] { return this->should_redraw.load(); }); + this->cv_redraw.wait_for(lock, std::chrono::milliseconds(1500), [this] { return this->should_redraw.load(); }); // Handle resize (under lock) if (this->resize_flag) { @@ -572,11 +568,9 @@ void UserInterface::draw_spinner() { attron(COLOR_PAIR(DEFAULT_PAIR)); if (progress > 0) { - mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Progress: %d%%", - spinner_chars[frame], progress); + mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Progress: %d%%", spinner_chars[frame], progress); } else { - mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Loading...", - spinner_chars[frame]); + mvprintw(this->layout.spinner_y, this->layout.spinner_x, "%c Loading...", spinner_chars[frame]); } attroff(COLOR_PAIR(DEFAULT_PAIR)); diff --git a/src/interface/user-interface.hpp b/src/interface/user-interface.hpp index f35b241..6469421 100644 --- a/src/interface/user-interface.hpp +++ b/src/interface/user-interface.hpp @@ -219,8 +219,8 @@ class UserInterface { * @param interactive Whether interactive mode is enabled. * @param dark_theme Whether to active the dark theme. */ - void print_args(const std::string& model, const std::string& prompt, bool stream, - bool interactive, bool dark_theme); + void print_args(const std::string& model, const std::string& prompt, bool stream, bool interactive, + bool dark_theme); /** * Static version of print_args() for non-interactive mode. @@ -231,8 +231,8 @@ class UserInterface { * @param interactive Whether interactive mode is enabled. * @param dark_theme Whether to active the dark theme. */ - static void print_args_noninteractive(const std::string& model, const std::string& prompt, - bool stream, bool interactive, bool dark_theme); + static void print_args_noninteractive(const std::string& model, const std::string& prompt, bool stream, + bool interactive, bool dark_theme); /** * Prints available models and their corresponding indexes for selection. @@ -258,8 +258,7 @@ class UserInterface { * @param models The list of available local models. * @param model Pointer to a std::string to receive the user input. */ - static void select_model_noninteractive(const std::vector& models, - std::string* model); + static void select_model_noninteractive(const std::vector& models, std::string* model); /** * Waits for and retrieves the next user input prompt (interactive mode). diff --git a/src/main.cpp b/src/main.cpp index 472ec62..1c6fe61 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -85,8 +85,7 @@ int main(int argc, const char* argv[]) { } else { UserInterface::print_model_list_noninteractive(models); UserInterface::select_model_noninteractive(models, &model); - UserInterface::print_args_noninteractive(model, prompt, stream, interactive, - dark_theme); + UserInterface::print_args_noninteractive(model, prompt, stream, interactive, dark_theme); } } diff --git a/src/ollama/ollama_client.cpp b/src/ollama/ollama_client.cpp index 71721a1..ce381ad 100644 --- a/src/ollama/ollama_client.cpp +++ b/src/ollama/ollama_client.cpp @@ -9,6 +9,15 @@ using nlohmann::json_abi_v3_11_2::json; +/** + * Web content fetch result. + */ +struct WebContent { + std::string read_buffer; + char error_buffer[CURL_ERROR_SIZE]; + long status = 0; +}; + /** * CURL write callback for accumulating response data. * @@ -37,10 +46,7 @@ static size_t WriteCallback(char* contents, size_t size, size_t nmemb, std::stri * Prints a newline in CLI mode for clean output formatting. */ OllamaClient::OllamaClient(UserInterface* ui) { - this->urls = { - generate_url : "http://localhost:11434/api/generate", - tags_url : "http://localhost:11434/api/tags" - }; + this->urls = {generate_url : "http://localhost:11434/api/generate", tags_url : "http://localhost:11434/api/tags"}; this->curl = nullptr; this->headers = nullptr; this->ui = ui; @@ -143,13 +149,11 @@ void OllamaClient::setup_progress_callback() { */ std::string OllamaClient::trim_response(std::string response) { response.erase(response.begin(), - std::find_if(response.begin(), response.end(), - [](unsigned char ch) { return !std::isspace(ch); })); + std::find_if(response.begin(), response.end(), [](unsigned char ch) { return !std::isspace(ch); })); - response.erase(std::find_if(response.rbegin(), response.rend(), - [](unsigned char ch) { return !std::isspace(ch); }) - .base(), - response.end()); + response.erase( + std::find_if(response.rbegin(), response.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), + response.end()); return response; } @@ -169,12 +173,10 @@ void OllamaClient::process_response(std::string response) { json response_json = json::parse(response); if (this->ui->is_running() == false) { - printf("🦙 llama:\n%s\n---\n", - this->trim_response(response_json["response"].get()).c_str()); + printf("🦙 llama:\n%s\n---\n", this->trim_response(response_json["response"].get()).c_str()); } else { this->ui->print_message("🦙 llama:"); - this->ui->print_message( - this->trim_response(response_json["response"].get())); + this->ui->print_message(this->trim_response(response_json["response"].get())); this->ui->print_message("---"); } } catch (const json::exception& err) { @@ -254,6 +256,71 @@ void OllamaClient::process_response_stream(std::string response) { } } +std::string OllamaClient::fetch_web_content(const std::string& url, std::optional post_data) { + struct WebContent content {}; + std::string message{}; + + this->init_curl(); + + this->spinner->start(); + + curl_easy_setopt(this->curl, CURLOPT_URL, url.c_str()); + + if (post_data != std::nullopt) { + curl_easy_setopt(this->curl, CURLOPT_POSTFIELDS, post_data->c_str()); + } + + curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, WriteCallback); + curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, &content.read_buffer); + curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, content.error_buffer); + curl_easy_setopt(this->curl, CURLOPT_FOLLOWLOCATION, 1L); + + this->setup_progress_callback(); + + this->headers = curl_slist_append(this->headers, "Content-Type: application/json"); + curl_easy_setopt(this->curl, CURLOPT_HTTPHEADER, this->headers); + + CURLcode result = curl_easy_perform(this->curl); + this->spinner->stop(); + + curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &content.status); + + curl_easy_cleanup(this->curl); + curl_slist_free_all(this->headers); + this->headers = nullptr; + + if (result != CURLE_OK) { + message = std::format("CURL error: {}\n", curl_easy_strerror(result)); + if (this->ui->is_running() == false) { + fprintf(stderr, "❌ %s", message.c_str()); + if (content.error_buffer[0] != '\0') { + message = std::format("Details: {}\n", content.error_buffer); + fprintf(stderr, "%s", message.c_str()); + } + exit(1); + } else { + this->ui->print_error(message); + if (content.error_buffer[0] != '\0') { + message = std::format("Details: {}\n", content.error_buffer); + this->ui->print_error(message); + } + this->ui->end_session(EXIT_FAILURE); + } + } + if (content.status != 200) { + message = std::format("Ollama returned HTTP status: {}\n", content.status); + if (this->ui->is_running() == false) { + fprintf(stderr, "❌ %s", message.c_str()); + exit(1); + } else { + this->ui->print_error(message); + this->ui->end_session(EXIT_FAILURE); + } + } + + return content.read_buffer; +} + /** * Sends a prompt to an Ollama model and displays the response. * @@ -287,10 +354,6 @@ void OllamaClient::process_response_stream(std::string response) { * or session instead. */ void OllamaClient::query_model(OllamaPromptConfig config) { - this->init_curl(); - - this->spinner->start(); - std::string message = std::format("💬 user: {}\n", config.prompt.c_str()); if (this->ui->is_running() == false) { printf("%s", message.c_str()); @@ -298,64 +361,11 @@ void OllamaClient::query_model(OllamaPromptConfig config) { this->ui->print_message(message); } - json request_payload = { - {"model", config.model}, {"prompt", config.prompt}, {"stream", config.stream}}; + json request_payload = {{"model", config.model}, {"prompt", config.prompt}, {"stream", config.stream}}; std::string post_data = request_payload.dump(); - std::string response; - - char error_buffer[CURL_ERROR_SIZE]; - - curl_easy_setopt(this->curl, CURLOPT_URL, this->urls.generate_url.c_str()); - curl_easy_setopt(this->curl, CURLOPT_POSTFIELDS, post_data.c_str()); - curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, WriteCallback); - curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, &response); - curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, error_buffer); - - this->setup_progress_callback(); - - this->headers = curl_slist_append(this->headers, "Content-Type: application/json"); - curl_easy_setopt(this->curl, CURLOPT_HTTPHEADER, this->headers); - - CURLcode result = curl_easy_perform(this->curl); - this->spinner->stop(); - - long status = 0; - curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &status); - - curl_easy_cleanup(this->curl); - curl_slist_free_all(this->headers); - this->headers = nullptr; - - if (result != CURLE_OK) { - message = std::format("CURL error: {}\n", curl_easy_strerror(result)); - if (this->ui->is_running() == false) { - fprintf(stderr, "%s", message.c_str()); - if (error_buffer[0] != '\0') { - message = std::format("Details: {}\n", error_buffer); - fprintf(stderr, "%s", message.c_str()); - } - exit(1); - } else { - this->ui->print_error(message); - if (error_buffer[0] != '\0') { - message = std::format("Details: {}\n", error_buffer); - this->ui->print_error(message); - } - this->ui->end_session(EXIT_FAILURE); - } - } - if (status != 200) { - message = std::format("Ollama returned HTTP status: {}\n", status); - if (this->ui->is_running() == false) { - fprintf(stderr, "%s", message.c_str()); - exit(1); - } else { - this->ui->print_error(message); - this->ui->end_session(EXIT_FAILURE); - } - } + std::string response = this->fetch_web_content(this->urls.generate_url, post_data); if (config.stream) { this->process_response_stream(response); @@ -397,64 +407,10 @@ void OllamaClient::query_model(OllamaPromptConfig config) { * @see OllamaPromptConfig for model information structure */ std::vector OllamaClient::query_model_list() { - this->init_curl(); - - this->spinner->start(); - - std::string response; - - char error_buffer[CURL_ERROR_SIZE]; - - curl_easy_setopt(this->curl, CURLOPT_URL, this->urls.tags_url.c_str()); - curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, WriteCallback); - curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, &response); - curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, error_buffer); - - this->setup_progress_callback(); - - this->headers = curl_slist_append(this->headers, "Content-Type: application/json"); - curl_easy_setopt(this->curl, CURLOPT_HTTPHEADER, this->headers); - - CURLcode result = curl_easy_perform(this->curl); - this->spinner->stop(); - - long status = 0; - curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &status); - - curl_easy_cleanup(this->curl); - curl_slist_free_all(this->headers); - this->headers = nullptr; - - std::vector models; std::string message{}; - if (result != CURLE_OK) { - message = std::format("CURL error: {}\n", curl_easy_strerror(result)); - if (this->ui->is_running() == false) { - fprintf(stderr, "❌ %s", message.c_str()); - if (error_buffer[0] != '\0') { - message = std::format("Details: {}\n", error_buffer); - fprintf(stderr, "%s", message.c_str()); - } - exit(1); - } else { - this->ui->print_error(message); - if (error_buffer[0] != '\0') { - message = std::format("Details: {}\n", error_buffer); - this->ui->print_error(message); - } - this->ui->end_session(EXIT_FAILURE); - } - } - if (status != 200) { - message = std::format("Ollama returned HTTP status: {}\n", status); - if (this->ui->is_running() == false) { - fprintf(stderr, "❌ %s", message.c_str()); - exit(1); - } else { - this->ui->print_error(message); - this->ui->end_session(EXIT_FAILURE); - } - } + std::vector models; + + std::string response = this->fetch_web_content(this->urls.tags_url); try { const json data = json::parse(response); @@ -480,10 +436,9 @@ std::vector OllamaClient::query_model_list() { for (const auto& model : data["models"]) { const std::string name = model.value("name", "unknown"); const std::string modified_at = model.value("modified_at", "unknown"); - const std::string size = - model.contains("size") - ? std::to_string(model["size"].get() / 1024 / 1024) + " Mb" - : "size unknown"; + const std::string size = model.contains("size") + ? std::to_string(model["size"].get() / 1024 / 1024) + " Mb" + : "size unknown"; if (name != "unknown") { models.push_back(name); diff --git a/src/ollama/ollama_client.hpp b/src/ollama/ollama_client.hpp index d77f3ba..78e19de 100644 --- a/src/ollama/ollama_client.hpp +++ b/src/ollama/ollama_client.hpp @@ -4,6 +4,7 @@ #include "interface/user-interface.hpp" #include #include +#include /** * Configuration for sending a prompt to an Ollama model. @@ -157,6 +158,30 @@ class OllamaClient { */ void process_response_stream(std::string response); + /** + * Fetches web content from the specified URL via HTTP/HTTPS request. + * + * Performs an HTTP GET or POST request to the given URL using libcurl, + * with automatic redirect following and JSON content-type header. + * Shows a spinner while the request is in progress. + * + * @param url The target URL to fetch from. Must be a valid URL string. + * @param post_data Optional POST request body. If provided, the request + * will be a POST request; otherwise a GET request. + * Defaults to std::nullopt (GET request). + * + * @return A WebContent struct containing the response body buffer, + * HTTP status code, and error buffer. + * + * @throws Calls exit(1) on CURL errors or non-200 HTTP status codes + * if the UI is not running. If UI is running, terminates the + * session with EXIT_FAILURE instead. + * + * @note Initializes and cleans up CURL resources internally. + * Automatically manages HTTP headers and follows redirects. + */ + std::string fetch_web_content(const std::string& url, std::optional post_data = std::nullopt); + public: /** * Constructs an OllamaClient connected to a UserInterface.