C++ API reference
-
class ArgsUtils
- #include <args_utils.hpp>
Utility class for parsing command-line arguments. Uses a handler map to associate argument keys with parsing functions, enabling O(1) lookup and flexible argument handling.
Public Functions
-
ArgsUtils()
Initializes the ArgsUtils instance with command-line argument handlers. Sets up a map of argument keys to handler functions that parse and assign values to ParsedArgs.
-
struct ParsedArgs parse_args(const int argc, const char *const argv[]) const
Parses command-line arguments and returns a ParsedArgs struct. Initializes all arguments with default values, then overrides them with values from the command line. Expects arguments in the format –key=value.
- Parameters:
- Returns:
ParsedArgs struct containing all parsed argument values
-
const char *help_text()
Returns the help text containing information about all supported runtime arguments.
-
void print_help()
Prints usage information for all supported runtime arguments and exits. Displays each argument name, type, description, and default value.
Private Members
-
std::unordered_map<std::string, std::function<void(const std::string&, struct ParsedArgs *args)>> handlers
Maps command-line argument keys to handler functions. Each handler processes the argument value and updates the corresponding field in ParsedArgs. Provides O(1) lookup when parsing arguments.
-
ArgsUtils()
-
class CurlUtils
- #include <curl_utils.hpp>
CURL HTTP client wrapper for making web requests to the Ollama server.
Provides a simplified interface for HTTP operations by encapsulating CURL initialization, request execution, and resource cleanup. Manages CURL easy handles and HTTP headers, with support for both GET and POST requests via optional POST data parameter. Integrates with the UserInterface for logging and progress feedback during network operations. Follows RAII pattern with automatic resource cleanup in the destructor. Uses a progress spinner to provide visual feedback during potentially long-running HTTP operations.
Public Functions
Constructs a CurlUtils instance with dependency injection.
Initializes CURL and headers pointers to nullptr, stores the provided UserInterface pointer for logging and status messages, and creates a ProgressSpinner instance for visual feedback during network operations. The actual CURL easy handle initialization is deferred to the initialize() method, typically called after object construction.
- Parameters:
ui – Pointer to the UserInterface for displaying messages and progress
-
~CurlUtils()
Destroys the CurlUtils instance and releases its CURL resources.
Calls cleanup(), which resets the curl and headers unique_ptrs and runs their deleters. Because the unique_ptrs also release their resources when they are destroyed, this call is not strictly required. It is kept so that the handle is released in the same way as at the end of each request.
Note
cleanup() also prints a completion message. This output appears when the object is destroyed, even if no request was made.
-
long wait_for_service(const std::string &url, const std::map<std::string, std::string> &extra_headers = {}, int max_retries = 3, int initial_delay_ms = 500)
Waits for a service to become available with retries and exponential backoff.
- Parameters:
url – Target endpoint URL.
extra_headers – Map of custom headers.
max_retries – Number of retry attempts (default: 10).
initial_delay_ms – Initial delay in milliseconds (default: 500ms).
- Returns:
HTTP status code on success; -1 if service unavailable after retries.
-
std::string fetch_web_content(const std::string &url, std::optional<std::string> post_data = std::nullopt, std::optional<std::string> custom_request_type = std::nullopt, std::optional<std::map<std::string, std::string>> extra_headers = std::nullopt, bool fail_on_http_error = true)
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.
See also
check_service_status()
Note
Initializes and cleans up CURL resources internally. Automatically manages HTTP headers and follows redirects.
- Parameters:
url – The target URL to fetch from. Must be a valid URL string.
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).
custom_request_type – Custom request type: GET, POST, PUT. Primarily used for PUT.
extra_headers – Optional map of custom headers to include (e.g., {“Authorization”: “Bearer token”}). Content-Type application/json is always added automatically. Defaults to std::nullopt (no extra headers).
fail_on_http_error – If false, returns response body even on non-200 status codes. If true (default), exits on non-200 status. Used for existence checks. Defaults to true.
- Throws:
Calls – std::exit(EXIT_FAILURE) 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.
- Returns:
A string containing the response body.
-
WebContentStream fetch_web_content_stream(const std::string &url, std::optional<std::string> post_data, std::function<void(const std::string&)> on_chunk, std::optional<std::string> custom_request_type = std::nullopt, std::optional<std::map<std::string, std::string>> extra_headers = std::nullopt, bool fail_on_http_error = true)
Performs an HTTP request and streams the response body to a callback.
Stores on_chunk as the stream callback, then sends the request through the shared curl handle. The response body is passed through curl_streaming_write_callback and process_chunk, which deliver each complete JSON line to on_chunk as it arrives. Unlike fetch_web_content(), this method does not start the progress spinner.
Content-Type: application/json is always sent. extra_headers are added after it. When the transfer finishes, the handle and headers are released through cleanup(). The returned WebContentStream reports whether the request succeeded, along with the HTTP status and any error message.
On a CURL error or a non-200 status, the error is shown through the UI or to stdout and stderr. The process then exits (non-interactive mode, or when fail_on_http_error is true for an HTTP error) or the UI session ends with EXIT_FAILURE. When fail_on_http_error is false, an HTTP error throws an HttpException.
Note
The post_data string must stay valid until curl_easy_perform() returns. content.status must be a long, because CURLINFO_RESPONSE_CODE writes a long.
- Parameters:
url – The request URL.
post_data – Optional request body, sent with CURLOPT_POSTFIELDS.
on_chunk – Callback invoked once for each complete JSON line in the response.
custom_request_type – Optional HTTP method override, such as “DELETE”.
extra_headers – Optional additional headers, as name and value pairs.
fail_on_http_error – If true, a non-200 status ends the program instead of throwing.
- Throws:
HttpException – If the HTTP status is not 200 and fail_on_http_error is false.
- Returns:
A WebContentStream with the HTTP status, the success flag, and the error message.
Private Functions
-
void initialize(void)
Creates a new CURL easy handle and stores it in the curl unique_ptr.
Calls curl_easy_init() and assigns the result with reset(), which releases any previously held handle through its custom deleter (curl_easy_cleanup). If initialization fails, the error is reported through the UI or to stdout, and the process exits (non-interactive mode) or the UI session ends with EXIT_FAILURE. On success, a confirmation message is printed.
Note
Because reset() releases an existing handle, calling this method discards any state set on the previous handle.
-
void cleanup(void)
Releases the CURL handle and the header list held by this object.
Calls reset() on the curl and headers unique_ptrs, which runs their custom deleters (curl_easy_cleanup and curl_slist_free_all). Each resource is only released if it is currently held, so calling this method more than once is safe.
In DEBUG builds, the pointer values are logged before they are released when no UI is running. A success message is printed at the end, either through the UI or to stdout.
Note
Do not call curl_easy_cleanup or curl_slist_free_all manually for these resources. Doing so together with the deleters causes a double free.
-
void add_header(curl_slist *&headers, const std::string &line)
Appends a single header line to a curl_slist that is being built.
Calls curl_slist_append() and, on success, updates the caller’s list pointer to the new head. If the append fails, the pointer is left unchanged, so the previously built list remains valid and is not lost.
Note
On failure the header is silently dropped. Callers that must guarantee every header is sent should check the list afterwards.
- Parameters:
headers – Reference to the curl_slist pointer being built. May be nullptr to start a new list.
line – The header line to append, in the form “Name: value”.
-
long check_service_status(const std::string &url, const std::map<std::string, std::string> &extra_headers = {}, long timeout_seconds = 5L)
Checks service availability by querying an HTTP endpoint and returning the HTTP status code.
Makes a silent HEAD request to the specified URL with optional custom headers, discards the response body, and returns the HTTP status code. On curl failure, returns -1.
See also
initialize(), cleanup()
Note
Initializes and cleans up curl handle internally; manages spinner lifecycle.
- Parameters:
url – Target endpoint URL (e.g., “http://localhost:6333/collections”).
extra_headers –
Map of custom headers to include (e.g., {“api-key”: “secret”, “Authorization”: “Bearer
token”}). If empty, request is sent without additional headers.
timeout_seconds – Connection and transfer timeout in seconds (default: 5).
- Returns:
HTTP status code on success (e.g., 200, 401, 404); -1 on curl failure.
-
void process_chunk(const std::string &chunk)
Buffers streamed response data and dispatches complete JSON lines.
Appends the incoming chunk to stream_buffer and extracts every complete line (terminated by ‘
’). A trailing ‘\r’ is removed, so \r
line endings work. Only lines that start with ‘{’ are treated as JSON and passed to stream_callback. Other lines are skipped. Any incomplete trailing data stays in stream_buffer until the next chunk arrives. If no stream_callback is set, the line is dropped.
Debug output goes to stdout only when no UserInterface is running.
Note
Each complete line is passed to stream_callback as a copy, so the callback may keep it. Lines that are not JSON objects are discarded.
- Parameters:
chunk – The raw data received from the current CURL write callback. It may contain zero, one, or several complete lines, or a partial line.
Private Members
-
std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> curl = {nullptr, curl_easy_cleanup}
CURL handle for HTTP requests. Initialized in init_curl().
-
std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)> headers = {nullptr, curl_slist_free_all}
CURL headers list for HTTP requests (Content-Type, etc.). Allocated in query methods and freed after each request.
-
std::shared_ptr<UserInterface> ui
Pointer to the UserInterface for displaying messages and errors. Used for both CLI and interactive UI output.
-
std::unique_ptr<ProgressSpinner> spinner
Progress spinner for visual feedback during network operations. Managed via std::unique_ptr for automatic cleanup.
Private Static Functions
-
static size_t curl_write_callback(char *contents, size_t size, size_t nmemb, std::string *userp)
CURL write callback for accumulating response data.
Called by CURL whenever data is received. Appends the chunk to the userp string buffer.
- Parameters:
contents – Pointer to the received data chunk.
size – Size of each element (always 1 for this use case).
nmemb – Number of elements received.
userp – Pointer to the std::string buffer to append data to.
- Returns:
Total bytes processed (size * nmemb).
-
static size_t curl_streaming_write_callback(char *contents, size_t size, size_t nmemb, void *userp)
CURL write callback for streaming response data.
Called by CURL whenever a chunk of the response body is received. The chunk is copied into a std::string and passed to CurlUtils::process_chunk() on the CurlUtils instance stored in userp. Output for errors and debug messages goes through the UserInterface when it is running, and to stdout or stderr otherwise.
Note
This method reads curl_obj->ui directly, so it is unsafe when no UserInterface is set. Consider using ui_running() before each access.
- Parameters:
contents – Pointer to the received data chunk. Not null-terminated.
size – Size of each element (always 1 for this use case).
nmemb – Number of elements received.
userp – Pointer to the CurlUtils instance that owns the transfer.
- Returns:
Total bytes processed (size * nmemb). Returns 0 if process_chunk() throws, which makes CURL abort the transfer with CURLE_WRITE_ERROR.
-
class EmbeddingUtils
- #include <embedding_utils.hpp>
Public Functions
Constructs an EmbeddingUtils instance with the collaborators it needs for generating and storing embeddings.
Initializes the ui, curl, ollama_client, and storage_client members by copying each shared pointer, so this instance shares ownership of every dependency with the caller. The constructor body is empty, so no other work is performed.
Note: Because the dependencies are shared, they remain alive as long as any holder still references them. Passing a null pointer is not checked here, so any later use of a null dependency will fail at the point of use.
- Parameters:
ui – Shared pointer to the UserInterface used to display messages and status.
curl – Shared pointer to the CurlUtils used to perform HTTP requests.
ollama_client – Shared pointer to the OllamaClient used to request embeddings from Ollama.
storage_client – Shared pointer to the QdrantClient used to store and retrieve embeddings.
-
void create_embedings(const std::vector<std::string> &urls)
Fetches documents from the given URLs, splits them into chunks, generates embeddings for those chunks, and stores the chunks with their embeddings in Qdrant.
Runs a four-stage pipeline. First, each URL is fetched with the CurlUtils instance and its content is collected in order. Second, every fetched document is split with TextUtils::split_text using a chunk size of 250 and an overlap of 0, and the resulting chunks are appended to a single list. Third, the OllamaClient generates one embedding per chunk. Fourth, the QdrantClient stores the chunks together with their embeddings. Before each stage, a progress message is shown, using the interactive UI when it is running and the non-interactive output otherwise. When all stages finish, a success message is displayed through the same mechanism.
Note: The method assumes that the embeddings returned by the OllamaClient correspond index for index to the chunks passed to it, because the storage call pairs them by position. No length check is performed. Fetch failures are not detected here, so an empty or error string returned by CurlUtils is split and embedded like any other content. Exceptions thrown by the curl, Ollama, Qdrant, or UI components are not caught and propagate to the caller, which means a failure in any stage stops the pipeline before the later stages run.
- Parameters:
urls – The web addresses whose content should be fetched and embedded.
Private Members
-
std::shared_ptr<UserInterface> ui
Pointer to the UserInterface for displaying messages and errors.
-
std::shared_ptr<CurlUtils> curl
Pointer to the CURL wrapper containing pre-configured internal logic.
-
std::shared_ptr<OllamaClient> ollama_client
Pointer to the OllamaClient for LLM ops.
-
std::shared_ptr<QdrantClient> storage_client
Pointer to the QdrantClient for vector database ops.
-
class ExitRequest : public std::exception
- #include <exit_request.hpp>
Exception thrown to request that the application exit with a specific code.
Throwing an ExitRequest signals that the program should shut down in an orderly way. The exit code travels with the exception, so the top-level handler can pass it to the operating system. Because the class derives from std::exception, a catch block for std::exception will also match it, so handlers that must let it through should catch ExitRequest first.
Catch it by const reference. The constructor, code(), and what() are all noexcept, so the object can be created and inspected without risk of throwing a second exception.
Public Functions
-
inline explicit ExitRequest(const int code, const std::string &reason = "application exit requested") noexcept
Constructs an exit request with the given exit code.
The constructor is explicit, so an int cannot be implicitly converted to an ExitRequest. The exit request must be created deliberately.
- Parameters:
code – The exit code to report when the application terminates.
-
inline int code() const noexcept
Returns the exit code carried by this request.
- Returns:
The exit code passed to the constructor. This function does not throw.
-
inline const char *what() const noexcept override
Returns a description of the exception.
The message is fixed and does not include the exit code. Use code() to retrieve the code. The returned pointer refers to a string literal with static storage duration, so it remains valid for the lifetime of the program.
- Returns:
A null-terminated string, “application exit requested”.
-
inline explicit ExitRequest(const int code, const std::string &reason = "application exit requested") noexcept
-
class HttpException : public std::runtime_error
- #include <http_utils.hpp>
Public Functions
-
inline long get_status_code() const
Private Members
-
long status_code
The HTTP status code that triggered the exception.
-
inline long get_status_code() const
-
struct Layout
- #include <terminal_backend.hpp>
UI layout positioning configuration.
Stores calculated row and column positions for all major UI elements relative to terminal dimensions. Updated by update_layout() when terminal is resized.
-
class OllamaClient
- #include <ollama_client.hpp>
Client for interacting with the Ollama API server.
Manages communication with an Ollama server instance, providing functionality to query language models, retrieve available models, and generate embeddings. Encapsulates HTTP communication via CURL, response parsing, and dual-mode output (console or interactive UI) based on the running state of the user interface. Validates server connectivity on initialization and handles errors with appropriate logging to either stderr or the UI.
The client uses pre-configured API endpoint URLs and delegates HTTP operations to a CURL wrapper utility. Responses from the server are processed and displayed to the user through the provided UI interface.
Public Functions
Constructs an OllamaClient connected to a UserInterface.
Initializes the Ollama API endpoint URLs, verifies the Ollama binary is installed, and creates a ProgressSpinner for network operations.
Note
Calls check_ollama() during construction. Exits if Ollama is not found.
- Parameters:
config – Pointer to the Ollama Client configuration options.
ui – Pointer to the UserInterface for displaying output.
curl – Pointer to a CurlUtils instance for HTTP communication with Qdrant.
system_utils – Pointer to a SustemUtils instance for
system()call status handling.
-
~OllamaClient()
Destroys the OllamaClient instance and clears the Ollama history file.
Runs a shell command that overwrites ~/.ollama/history with an empty string, truncating its contents. Passes the return status of the shell command to system_utils->catch_error() for handling.
Note: This destructor depends on system_utils remaining valid for the duration of destruction, and it relies on the shell to expand the ~ path. Because it runs a shell command, it will also fail silently in environments where system() is unavailable or where the history file does not exist.
-
template<typename T>
const T &get_config_value(const std::string &property_name) const Retrieves a configuration value by property name as a const reference of the requested type.
Compares property_name against each supported property in turn. For a matching name, returns a reference to the corresponding config member only when T matches that member’s type. The type checks are resolved at compile time with if constexpr, so each instantiation contains only the branch for its type.
Note: If the name matches but T does not, control falls through to the remaining checks and ends at the exception. The returned reference refers into config, so it must not outlive the OllamaClient instance.
- Template Parameters:
T – Type of the configuration value to return. Supported types are std::string for “model”, “embedding_model”, and “prompt”, and bool for “stream”.
- Parameters:
property_name – Name of the configuration property to look up.
- Throws:
std::runtime_error – If property_name is not a supported property, or if T does not match the property’s type.
- Returns:
: Const reference to the matching member of config, valid for as long as config is alive.
-
const std::string &get_url_value(const std::string &property_name) const
Retrieves a URL value by property name as a const reference to a std::string.
Compares property_name against “generate_url” and then “embed_url”, returning a reference to the corresponding field of urls on a match.
Note: The returned reference refers into urls, so it must not outlive the OllamaClient instance. Unlike get_config_value(), this method has no type parameter because every URL property is a std::string.
- Parameters:
property_name – Name of the URL property to look up; supported values are “generate_url” and “embed_url”.
- Throws:
std::runtime_error – If property_name is not a supported URL property.
- Returns:
: Const reference to the matching URL string stored in the urls member, valid for as long as this OllamaClient instance is alive.
-
std::vector<std::vector<float>> generate_embeddings(const std::vector<std::string> &texts, std::optional<OllamaClientConfig> config_opt = std::nullopt)
Generates embeddings for a list of text strings using the Ollama embedding model.
This method sends each text to the Ollama embedding endpoint and retrieves the corresponding embedding vectors. Embeddings are processed sequentially.
- Parameters:
texts – A vector of text strings to embed
config_opt – Configuration object specifying the embedding model to use
- Throws:
std::exception – if the web request fails or the response cannot be parsed
- Returns:
A vector of embedding vectors, where each inner vector contains the float values representing the embedding for the corresponding text. The order of embeddings matches the order of input texts.
-
void query_model(std::optional<OllamaClientConfig> config_opt = std::nullopt)
Sends a prompt query to the Ollama model and processes the response.
Displays the formatted user message to either the console or UI based on the UI’s running state, then constructs a JSON request payload with the model, prompt, and stream settings. Fetches the response from the Ollama server and processes it either as a stream or as a complete response.
- Parameters:
config_opt – The prompt configuration containing the model name, prompt text, and stream preference
-
void process_response(std::string response)
Parses and displays a complete JSON response from Ollama.
Extracts the “response” field, trims whitespace, and displays it with a llama emoji header and separator. On JSON parse error, displays an error message and exits or ends the session.
Output is routed through the UserInterface or stdout/stderr.
- Parameters:
response – The complete JSON response from the Ollama API.
-
void process_response_stream(const std::string &chunk)
Parses one line of a streamed Ollama response and displays its text fragment.
Parses line as JSON and extracts the “response” text fragment. A static flag tracks whether this is the first chunk of the current response. The first chunk starts a new message entry, and later chunks are appended to it. The text is shown through the UI when it is running, or printed non-interactively otherwise. When the “done” field is true, the flag is reset so the next response starts a new entry, and the method returns.
Parse failures and other json::exception errors are caught and reported through print_error_noninteractive(), including the error ID and the offending line.
Note: When compiled with DEBUG defined, the first 100 characters of each line are logged if the UI is not running. The first_chunk flag is static, so it is shared by all OllamaClient instances. If a stream ends or fails to parse before a chunk with “done” set to true, the flag is not reset and the next response will be appended to the previous message.
- Parameters:
line – One JSON-encoded chunk from the streaming response, expected to contain a “response” string and a “done” boolean.
-
std::vector<std::string> query_model_list()
Retrieves a list of available models from the Ollama server.
Fetches the models list from the Ollama tags endpoint and parses the JSON response. Validates that the response contains a valid models array. Extracts and displays model metadata including name, modification timestamp, and size (converted from bytes to megabytes). Collects valid model names into a vector for return. Handles errors (invalid response structure or JSON parsing failures) by terminating with an error message directed to either stderr or the UI based on the UI’s running state.
- Returns:
A vector of available model names extracted from the server response. Returns an empty vector if an error occurs during fetch or parsing.
Private Functions
-
void check_ollama()
Verifies that the `is available on the system.
Uses the
which ollamacommand to check if Ollama is in the PATH.If found: displays a checkmark and continues.
If not found: displays an error message with installation instructions and exits or ends the session.
Output is routed through the UserInterface (if available) or stdout/stderr.
Displays a checkmark on success.
Private Members
-
OllamaServerURLs urls
API endpoint URLs for the Ollama server.
-
std::shared_ptr<OllamaClientConfig> config
Pointer to the Ollama Client configuraion.
-
std::shared_ptr<UserInterface> ui
Pointer to the UserInterface for displaying messages and errors.
-
std::shared_ptr<CurlUtils> curl
Pointer to the CURL wrapper containing pre-configured internal logic.
-
std::shared_ptr<SystemUtils> system_utils
Pointer to the SystemUtils for processing
system()calls.
-
struct OllamaClientConfig
- #include <ollama_client.hpp>
Configuration for sending a prompt to an Ollama model.
- Param model:
The name of the model to query (e.g., “llama2”, “neural-chat”).
- Param embedding_model:
The name of the embedding model to query (e.g., “embeddinggemma”).
- Param prompt:
The text prompt to send to the model.
- Param stream:
Whether to stream the response (true) or receive it all at once (false).
-
struct OllamaServerURLs
- #include <ollama_client.hpp>
URLs for Ollama API endpoints.
- Param generate_url:
The endpoint for querying a model.
- Param tags_url:
The endpoint for listing available models.
- Param embed_url:
The endpoint for creating embeddings.
-
struct ParsedArgs
- #include <args_utils.hpp>
Represents parsed command-line arguments. Contains all supported runtime arguments with their parsed values. Boolean fields default to false; string fields default to empty strings.
-
class ProgressSpinner
- #include <progress_spinner.hpp>
Displays and manages an animated progress spinner with optional download tracking.
Runs a spinner animation in a dedicated background thread, providing visual feedback during network operations. Supports two modes: UI-driven (displays via UserInterface) and manual mode (spinner_thread active but output deferred). Integrates with CURL progress callbacks to track download progress. Thread-safe via atomic flags for state management (active, completion_shown).
Public Functions
-
ProgressSpinner()
Constructs a ProgressSpinner in manual mode.
Creates a spinner that displays to stdout without UI integration. Must be manually started with start().
Constructs a ProgressSpinner with optional UI integration.
Note
The UserInterface pointer must remain valid for the lifetime of the ProgressSpinner object.
- Parameters:
user_interface – Pointer to a UserInterface instance for rendering, or nullptr for manual mode (CLI spinner).
activate – If true and user_interface is not nullptr, automatically starts the spinner. Default: false.
-
~ProgressSpinner()
Destructs the ProgressSpinner, ensuring the spinner thread is stopped.
Calls stop() to cleanly shut down the spinner thread.
-
void start()
Starts the spinner animation on a background thread.
If no UserInterface is set, displays an animated spinner (| / - ) to stdout.
If a UserInterface is set, delegates animation to the UI via start_spinner() and advance_spinner_frame().
Sets progress to 0% and resets the completion_shown flag.
Note
Safe to call multiple times; subsequent calls are no-ops if already running.
-
void stop()
Stops the spinner animation and cleans up the background thread.
Waits for the spinner thread to finish (via join()) and notifies the UserInterface to stop its spinner, if set.
Note
Safe to call multiple times or if start() was never called.
-
int progress_callback_impl(curl_off_t dltotal, curl_off_t dlnow)
Internal progress callback for CURL integration.
Processes download progress information and updates the spinner or UI accordingly. Displays a progress bar (▰▰▰▱) with percentage if total size is known.
Note
This method is called frequently by CURL; keep it lightweight.
- Parameters:
dltotal – Total bytes to download (0 if unknown).
dlnow – Bytes downloaded so far.
- Returns:
0 to continue the CURL operation, non-zero to abort.
Public Static Functions
-
static int progress_callback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow)
Static CURL callback adapter for progress tracking.
This static method serves as the callback function for CURL’s CURLOPT_XFERINFOFUNCTION option. It casts the clientp parameter to a ProgressSpinner instance and delegates to progress_callback_impl().
Note
CURL calls this frequently; ensure your clientp points to a valid ProgressSpinner instance.
- Parameters:
clientp – Opaque pointer to the ProgressSpinner instance (passed via CURLOPT_XFERINFODATA).
dltotal – Total bytes to download (0 if unknown).
dlnow – Bytes downloaded so far.
ultotal – Total bytes to upload (unused).
ulnow – Bytes uploaded so far (unused).
- Returns:
0 to continue the CURL operation, 1 to abort if clientp is nullptr.
Private Members
-
std::shared_ptr<UserInterface> ui
Pointer to the associated UserInterface, or nullptr for manual mode.
-
ProgressSpinner()
-
class QdrantClient
- #include <qdrant_client.hpp>
Manages the lifecycle and API interaction with a Qdrant vector database server running in Docker.
The QdrantClient class is responsible for:
Automatically pulling and starting a Qdrant Docker container during construction
Validating required environment variables (QDRANT_API_KEY, QDRANT_API_KEY_READ_ONLY)
Creating and managing a Docker network for inter-service communication
Verifying server health and availability
Storing text embeddings as vector points in the Qdrant database
Cleaning up Docker resources during destruction
The Qdrant server listens on localhost:6333 (gRPC) and localhost:6334 (HTTP API) by default, with configuration via the QDRANT_URL environment variable.
Lifecycle:
Constructor calls setup() to initialize Docker resources and check_qdrant() to verify connectivity.
Destructor automatically stops and removes the container and associated network.
Note
Requires Docker to be installed and running on the host system.
Note
Environment variables QDRANT_API_KEY and QDRANT_API_KEY_READ_ONLY must be set before construction.
Note
Creates persistent data directory at $HOME/qdrant for container use.
Note
Creates Docker network app-rag-net for service communication.
- Param ui:
Pointer to UserInterface for displaying status messages and errors. Must remain valid for the lifetime of this QdrantClient instance.
- Param curl:
Pointer to CurlUtils for executing HTTP requests to the Qdrant API. Must remain valid for the lifetime of this QdrantClient instance.
Public Functions
Initializes a QdrantClient instance with the provided UI and networking utilities. Constructs the base URL from the QDRANT_URL environment variable, defaulting to the local Qdrant service. Performs an immediate health check of the Qdrant service upon construction.
Note
Constructor calls check_qdrant() as a side effect, which may produce console or UI output.
- Parameters:
ui – Pointer to a UserInterface instance for status message output.
curl – Pointer to a CurlUtils instance for HTTP communication with Qdrant.
system_utils – Pointer to a SustemUtils instance for
system()call status handling.
-
~QdrantClient()
Cleans up Docker resources associated with the Qdrant container and network. Stops and removes the qdrant-rag-app container and destroys the app-rag-net Docker network. Suppresses errors during cleanup to ensure all resources are removed even if individual commands fail.
Note
This destructor is called automatically when the QdrantClient instance is destroyed.
-
const std::string &get_url_value(const std::string &property_name) const
Retrieves a URL value by property name as a const reference to a std::string.
Compares property_name against “collections_url” and returns a reference to the corresponding field of urls on a match.
Note: The returned reference refers into urls, so it must not outlive the QdrantClient instance. Because this class exposes only one URL property, any other name throws, which makes the lookup a single comparison rather than a loop or map search.
- Parameters:
property_name – Name of the URL property to look up; the only supported value is “collections_url”.
- Throws:
std::runtime_error – If property_name is not a supported URL property.
- Returns:
: Const reference to the matching URL string stored in the urls member, valid for as long as this QdrantClient instance is alive.
-
void store(const std::vector<std::string> &texts, const std::vector<std::vector<float>> &embeddings)
Stores text documents and their corresponding embeddings into the Qdrant collection. Constructs points from the provided texts and embeddings, then sends them to the Qdrant service via PUT request. Authentication is performed using the QDRANT_API_KEY environment variable.
Note
The size of texts and embeddings vectors should match; behavior is undefined if they differ.
- Parameters:
texts – A vector of text strings to be stored as payloads in Qdrant points.
embeddings – A vector of embedding vectors (floats) corresponding to each text string.
Private Functions
-
void setup()
Initializes and starts the Qdrant Docker container with necessary configuration. Pulls the Qdrant image, validates the QDRANT_API_KEY and QDRANT_API_KEY_READ_ONLY environment variables, creates a persistent data directory, establishes a Docker network, and launches the container with API key authentication. If a Qdrant container is already running, this method returns early without restarting it.
Note
This method should be called before check_qdrant() to ensure the service is available.
Note
Does not wait for the container to be fully operational; health verification is delegated to check_qdrant().
- Throws:
Exits – with status code 1 if required environment variables are missing or container startup fails.
-
void check_qdrant()
Checks the health status of the Qdrant service using the configured API endpoint. Retrieves the API key from the QDRANT_API_KEY environment variable for authentication. Outputs a status message (success, error, or warning) to the UI or console based on the HTTP response code.
-
bool collection_exists(const std::string &collection_name)
Checks if a collection exists in Qdrant.
- Parameters:
collection_name – The name of the collection to check.
- Returns:
true if the collection exists, false otherwise.
Private Members
-
QdrantServerURLs urls
API endpoint URLs for the Qdrant server.
-
std::shared_ptr<UserInterface> ui
Pointer to the UserInterface for displaying messages and errors. Used for both CLI and interactive UI output.
-
std::shared_ptr<SystemUtils> system_utils
Pointer to the SystemUtils for processing
system()calls.
-
struct QdrantServerURLs
- #include <qdrant_client.hpp>
URLs for Qdrant API endpoints.
- Param collections_url:
The endpoint for querying collections.
-
class RetrievingUtils
- #include <retrieving_utils.hpp>
Public Functions
Constructs a RetrievingUtils instance with the configuration and collaborators it needs to retrieve stored embeddings.
Initializes the config, ui, curl, ollama_client, and storage_client members by copying each shared pointer, so this instance shares ownership of every dependency with the caller. The constructor body is empty, so no other work is performed.
Note: Because the dependencies are shared, they remain alive as long as any holder still references them. Passing a null pointer is not checked here, so any later use of a null dependency will fail at the point of use.
- Parameters:
config – Shared pointer to the RetrievingUtilsConfig that supplies the retrieval settings.
ui – Shared pointer to the UserInterface used to display messages and status.
curl – Shared pointer to the CurlUtils used to perform HTTP requests.
ollama_client – Shared pointer to the OllamaClient used to generate query embeddings.
storage_client – Shared pointer to the QdrantClient used to search stored embeddings.
-
void run(void)
Runs one retrieval-augmented question-answering cycle using the prompt from the configuration.
Reads the “prompt” string from the Ollama client configuration and keeps a constant reference to it. The prompt is then shown to the user as a message, either through the interactive UI when it is running or through non-interactive output otherwise. The same prompt is used as the search input for retrieve, which embeds it and returns the matching document texts from the vector store. Those documents, together with the prompt as the question, are passed to generate_answer, which builds the final prompt, queries the model, and processes the answer.
Note: The prompt is both the displayed user message and the retrieval query, and it is also used as the question in generate_answer. Because the returned reference points into the configuration object, the configuration must outlive this method. The method performs no check on whether retrieve returned any documents, so generate_answer is called even with an empty list.
- Throws:
std::runtime_error – If the “prompt” config property is not supported or has an unexpected type, or if retrieve or generate_answer fails with a runtime error.
nlohmann::json::parse_error – If a retrieval response cannot be parsed as JSON, as propagated from retrieve.
nlohmann::json::type_error – If a retrieval response has an unexpected JSON structure, as propagated from retrieve.
Private Functions
-
std::vector<std::string> retrieve(const std::string &question)
Retrieves the stored document chunks that are most similar to a user question.
Builds a JSON request with the embedding model name and the question, then posts it to the Ollama embed URL through the CurlUtils instance. The first vector in the returned “embeddings” array becomes the question embedding. That vector, the configured result limit k, and a flag requesting payloads are serialized into a search request. The request is posted to the “rag-app/points/search” endpoint under the Qdrant collections URL, with the api-key header set from the QDRANT_API_KEY environment variable. Each entry in the “result” array of the search response contributes its payload text to the returned list. In debug builds, when the UI is not running, both raw responses are printed to the non-interactive output.
Note: The method depends on the QDRANT_API_KEY environment variable. If it is unset, the null pointer passed to the header map is not checked, which can cause undefined behavior or a std::logic_error at construction. The response is not checked for HTTP errors before parsing, so an error body from either service typically surfaces as a parse or type exception. The method reads only the first embedding, so it expects the embed service to return exactly one vector for the single question.
- Parameters:
question – The natural-language question to search for.
- Throws:
std::runtime_error – If the “embedding_model” config property or the “embed_url” or “collections_url” URL property is not supported, or if the “embedding_model” value is not a std::string.
nlohmann::json::parse_error – If the embedding response or the search response is not valid JSON.
nlohmann::json::type_error – If the embedding response does not contain a numeric “embeddings” array, or if a search result does not contain a string “payload” “text” field.
- Returns:
The text payloads of the top matching chunks from Qdrant, ordered by similarity. The list has at most config->k entries.
-
void generate_answer(const std::string &question, const std::vector<std::string> &documents)
Builds a retrieval-augmented prompt from a question and its supporting documents, sends it to the Ollama generate endpoint, and processes the model’s answer.
Concatenates the document texts into one string, separating entries with newlines, and places that string together with the question into a fixed instruction template. The template asks the model to answer in at most three sentences and to say when it does not know the answer. The prompt, the model name, a temperature of 0, and the stream flag are serialized into a JSON request. When streaming is enabled, the request is posted through fetch_web_content_stream, and each received chunk is forwarded to OllamaClient::process_response_stream. The resulting success flag and status are then reported through the UI or the non-interactive output. When streaming is disabled, the request is posted with fetch_web_content, and the full body is passed to OllamaClient::process_response.
Note: The question and document text are inserted into the prompt without escaping or sanitizing, so instructions contained in retrieved documents can influence the model. The method does not check whether the documents vector is empty, although the join loop itself handles that case safely. Errors from the HTTP layer are not inspected beyond the stream status message, so a failed non-streamed request reaches the response handler as-is.
- Parameters:
question – The user question that the model should answer.
documents – The retrieved document texts that provide context for the answer. Each entry is joined with a newline.
- Throws:
std::runtime_error – If the “model” or “stream” config property is not supported or has an unexpected type, or if the “generate_url” URL property is not supported.
nlohmann::json::exception – If the streamed or non-streamed response cannot be parsed, as propagated from the OllamaClient response handlers.
Private Members
-
std::shared_ptr<RetrievingUtilsConfig> config
Pointer to the Retrieving Utils configuration.
-
std::shared_ptr<UserInterface> ui
Pointer to the UserInterface for displaying messages and errors.
-
std::shared_ptr<CurlUtils> curl
Pointer to the CURL wrapper containing pre-configured internal logic.
-
std::shared_ptr<OllamaClient> ollama_client
Pointer to the OllamaClient for LLM ops.
-
std::shared_ptr<QdrantClient> storage_client
Pointer to the QdrantClient for vector database ops.
-
struct RetrievingUtilsConfig
- #include <retrieving_utils.hpp>
Public Members
-
int k = 4
-
int k = 4
-
class SystemUtils
- #include <system_utils.hpp>
Public Functions
Initializes a SystemUtils instance with a reference to the UserInterface.
Note
The SystemUtils class does not take ownership of the ui pointer; the caller is responsible for managing the UserInterface lifetime.
- Parameters:
ui – Pointer to UserInterface for displaying messages and error output. Must remain valid for the lifetime of this SystemUtils instance.
-
void catch_error(int status)
Evaluates the wait status from a system() call and reports any failure.
This method interprets the status with the POSIX macros WIFEXITED and WEXITSTATUS. A status of -1 means system() itself failed, and only the “system() failed.” message is reported. A status where the process did not exit normally is reported as “Command terminated abnormally.” A normal exit with a non-zero code is reported with that code. A successful command (exit code 0) produces no output and returns normally.
Each failure is passed to report_failure(), which shows the message through the UserInterface in interactive mode or prints it non-interactively otherwise, then ends the program with EXIT_FAILURE.
Note
Non-interactive failures terminate the process immediately. Interactive failures return to the caller only if UserInterface::end_session() returns.
- Parameters:
status – The wait status returned from a system() call, as interpreted by the POSIX macros WIFEXITED and WEXITSTATUS.
- Throws:
Does – not throw. Ends the program with EXIT_FAILURE on any detected error, through report_failure().
Private Functions
-
void report_failure(const std::string &message)
Reports a failure and ends the program with EXIT_FAILURE.
In interactive mode, the message is shown through the UserInterface and the session is ended with EXIT_FAILURE. Otherwise, the message is printed non-interactively and the process exits immediately with EXIT_FAILURE.
Note
In interactive mode, this relies on UserInterface::end_session() not returning. If it does return, report_failure returns to its caller.
- Parameters:
message – The error message to display. The messages passed from catch_error each end with a newline.
Private Members
-
std::shared_ptr<UserInterface> ui
Pointer to the UserInterface for displaying messages and errors. Used for both CLI and interactive UI output.
-
class TerminalBackend
- #include <terminal_backend.hpp>
Public Functions
-
TerminalBackend()
Constructs a TerminalBackend instance and initializes member variables.
Initializes input_cursor_x to 0 (cursor at leftmost position). Initializes layout struct to default-constructed values (all fields zeroed/default). Sets use_dark_theme to true, establishing dark theme as the default color scheme preference.
Note: This constructor performs only member initialization and singleton registration. Full ncurses initialization (terminal setup, color pair configuration, input handling) is deferred to init_ncurses(), which must be called explicitly after construction to establish the UI environment.
-
explicit TerminalBackend(bool dark_theme)
Constructs a TerminalBackend instance with a caller-specified color theme preference.
Initializes input_cursor_x to 0 (cursor at leftmost position). Initializes layout struct to default-constructed values (all fields zeroed/default). Sets use_dark_theme to the caller-provided dark_theme value, establishing the preferred color scheme that will be applied during init_ncurses().
Note: This constructor performs only member initialization and singleton registration. Full ncurses initialization (terminal setup, color pair configuration, input handling) is deferred to init_ncurses(), which must be called explicitly after construction to establish the UI environment.
- Parameters:
dark_theme – Boolean flag to select color scheme; true for dark theme, false for light theme.
-
~TerminalBackend()
Destroys the TerminalBackend and ends its session if it is still active.
Calls end_session() with its default exit code. That call stops the render thread and restores the terminal, but only if terminal_restored has not already been set. The destructor does not acquire ui_mutex directly.
Note
Destruction always blocks for about one second because end_session() calls napms(1000) unconditionally, even when the session was already ended earlier.
Warning
Destructors are implicitly noexcept. If end_session() or anything it calls throws, std::terminate() is called. Call end_session() explicitly before destruction if a session needs to be ended while exceptions are still being handled.
- Post:
The render thread has been stopped.
- Post:
The terminal has been restored, and endwin() has run exactly once across all calls to end_session().
-
void end_session(int code = EXIT_SUCCESS)
Ends the terminal session and restores the terminal state.
The function sleeps for one second, stops the render thread, and then calls endwin() if the terminal has not been restored yet. The check and update of terminal_restored use exchange(), so cleanup runs at most once even if this function is called more than once.
Note
The call blocks the calling thread for about one second through napms(1000) before doing anything else. Avoid calling it from a thread that must respond promptly.
- Post:
The render thread has been stopped.
- Post:
terminal_restored is true, and endwin() has run exactly once across all calls.
-
void run(void)
Initializes and starts the TerminalBackend subsystem.
Performs full initialization pipeline: calls init_ncurses() to set up the ncurses library, terminal settings, and signal handlers; calls draw_ui() to render the initial full-terminal Unicode box border; and calls start_render_thread() to spawn the background rendering thread.
The rendering thread continuously redraws the UI (output area, input area, spinner) in response to state changes and terminal resize events (resize_flag).
No parameters; operates on the current TerminalBackend instance state.
Initialization status is communicated via successful completion (or program termination if init_ncurses() encounters a fatal error).
Acts as the entry point for the UI system. Should be called once after TerminalBackend instantiation and before any event processing or input handling.
Enables the interactive terminal UI with responsive rendering and asynchronous screen updates via the background thread, while the main thread handles user input and application logic.
- Returns:
void
-
bool is_running()
Reports whether the backend’s thread is currently running.
The value is read atomically, so this function does not acquire ui_mutex. The result can become stale as soon as the function returns.
Note
Use this for status checks only. Do not use it to decide whether to start or stop the thread without coordinating through another synchronization mechanism, because the state can change between the check and the action.
- Returns:
true if the backend thread is running, false otherwise.
-
void shift_input_cursor_x(int shift)
Moves the input cursor one column to the left or right.
Only steps of -1 or +1 are accepted. The function does not check whether the resulting position is within the bounds of input_buffer, and it does not acquire ui_mutex.
Note
Access to input_cursor_x is not synchronized. If another thread reads or modifies the cursor, the caller must hold ui_mutex.
Warning
The position is not bounds-checked after the shift. Stepping left at position 0 or right past the end of input_buffer leaves input_cursor_x out of range, which callers must avoid.
- Parameters:
shift – The step to apply to input_cursor_x. Must be -1 or 1.
- Throws:
std::invalid_argument – If shift is any value other than -1 or 1.
- Pre:
input_cursor_x is within the range [0, input_buffer.length()].
- Post:
input_cursor_x has been moved by shift.
-
void set_should_redraw(bool value)
Sets the flag that requests a screen redraw.
The value is stored atomically, so this function does not acquire ui_mutex. The previous value is discarded.
Note
This function does not notify cv_redraw. Setting the flag to true does not wake a thread waiting on that condition variable, so a waiter may not see the request until it is woken by another call such as print().
- Parameters:
value – true to request a redraw, false to clear the request.
-
void set_spinner_active(bool value)
Sets whether the spinner is active.
The value is stored atomically, so this function does not acquire ui_mutex. The previous value is discarded.
Note
This call does not set should_redraw or notify cv_redraw. Callers that need the spinner change displayed must trigger a redraw separately.
- Parameters:
value – true to activate the spinner, false to deactivate it.
-
void set_spinner_frame(int value = -1)
Sets the progress percentage shown by the terminal.
The value is stored atomically, so this function does not acquire ui_mutex. The previous value is discarded. No range check is performed, so callers are responsible for passing a meaningful percentage.
Note
Because no lock is taken, a redraw is not triggered by this call. Callers that need the change displayed must also update output state and signal cv_redraw through print().
- Parameters:
value – The new progress percentage to store.
-
void set_progress_percent(int value)
-
void notify_cv_redraw(bool all = false)
Wakes one or all threads waiting on cv_redraw.
The function does not acquire ui_mutex and does not modify should_redraw or any other state. Notifying is the only effect.
Note
A waiter that checks a predicate such as should_redraw must update that predicate before calling this function, or a wakeup can be missed.
Warning
Calling this without first changing the state a waiter depends on can cause a lost wakeup. Waking one thread may also leave other waiters asleep if they need to act on the same change, so use all = true when more than one thread might need to respond.
- Parameters:
all – true to wake all waiting threads with notify_all(), false to wake a single waiting thread with notify_one().
-
bool get_spinner_active(void)
Reports whether the spinner is currently active.
The value is read atomically, so this function does not acquire ui_mutex. The result can change immediately after the call returns if another thread updates spinner_active.
- Returns:
true if the spinner is active, false otherwise.
-
void draw_ui(void)
Draws the terminal UI frame with a Unicode box border.
Clears the screen and retrieves the current terminal dimensions (max_y, max_x) via getmaxyx(). Draws a complete box frame using Unicode box-drawing characters: ╔ and ╗ (top corners), ╚ and ╝ (bottom corners), ═ (horizontal edges), and ║ (vertical edges). Positions characters using mvprintw() to create a full-terminal border with proper corner and edge placement.
Refreshes the display with refresh() to flush buffered output and show the drawn frame on screen.
-
void draw_spinner(void)
Draws an animated spinner with optional progress percentage at the UI layout position.
Returns early if the spinner is not active. Loads the current animation frame index and progress percentage from atomic variables (spinner_frame, progress_percent) in a thread-safe manner. Selects the appropriate spinner character from a rotating set (|, /, -, ) based on the frame index.
Enables DEFAULT_PAIR color styling and renders the spinner at the layout-defined position (layout.spinner_y, layout.spinner_x) using mvprintw(). If progress > 0, displays “X Loading…” with the progress percentage; otherwise displays “X Loading…” without percentage. Disables color styling after rendering.
Thread-safe via atomic variable loads; does not modify shared state.
-
void update_layout()
Recalculates UI layout positions and dimensions based on current terminal size.
Retrieves the current terminal dimensions (max_y, max_x) via getmaxyx() and updates the layout structure to position UI elements relative to terminal boundaries. Sets status_y to the bottom row (max_y - 1), input area to max_y - 3 with left margin of 2 columns, and spinner to max_y - 2 (between input and status rows). Sets output area to start at row 1 (below top border) with height calculated as the vertical space between output_y and input_y minus one row for spacing.
Intended to be called during initialization and in response to terminal resize events (SIGWINCH) to ensure all UI elements remain properly positioned and sized when the terminal is resized.
-
void clear_input_area()
Clears the input area rows by overwriting them with spaces.
Retrieves the current terminal dimensions (max_y, max_x) via getmaxyx(). Erases two rows of the input area (layout.input_y and layout.input_y + 1) by drawing horizontal lines of spaces from column 1 to max_x - 2, leaving the left and right borders intact.
Used to erase previous user input or prompts before rendering new content in the input area. Maintains visual consistency by preserving the terminal border structure.
-
void draw_input_area()
Renders the input prompt and user-typed content in the input area.
Clears the input area via clear_input_area(). Returns early if the spinner is currently active, preventing prompt and input display while a background operation (query execution) is in progress.
When the spinner is inactive, renders a static prompt “⏳ Type your prompt (q/Q to quit): “ at the layout-defined input position (layout.input_y, layout.input_x). Renders the contents of the input_buffer (user-typed characters) immediately following the prompt text at a fixed column offset (+37 from input_x).
Provides visual feedback and instructions to the user while maintaining a clean, non-overlapping layout during asynchronous spinner operation.
-
void draw_output_area()
Renders the message output buffer in reverse chronological order (newest first), from the bottom of the output area upward.
Clears the entire output area by filling each row with spaces, preserving the border columns. Iterates backwards through output_buffer, starting from the most recently added message. For each message, extracts the text content and message type (error/success/default).
Splits multi-line message text by newline characters. Wraps each logical line at word boundaries using TextUtils::wrap_text() to fit within max_content_width (COLS - 4). Renders wrapped lines from bottom to top (reverse order) within the allocated output area, decrementing current_line after each rendered line.
Applies semantic color and icon styling based on message type:
MESSAGE_TYPE_ERROR: bold red (ERROR_PAIR) with ❌ emoji prefix.
MESSAGE_TYPE_SUCCESS: bold default color with ✅ emoji prefix.
Default: plain text without icon.
Breaks iteration early if current_line reaches or falls below layout.output_y (top boundary). Calls refresh() to update the terminal display.
Provides a scrollable-like view of the most recent messages within the constrained output area, with automatic wrapping and visual differentiation for errors and successful operations.
-
void start_render_thread(void)
Spawns the background rendering thread and sets the thread_running flag.
Sets thread_running to true and creates a new std::thread that invokes render_loop(). The thread is joinable and must be cleaned up via stop_render_thread() or equivalent.
See also
Note
Call this after init_ncurses() to begin continuous UI rendering.
-
void stop_render_thread(void)
Gracefully shuts down the background rendering thread.
Sets thread_running to false and notifies the condition variable cv_redraw to wake the render loop. Joins the thread if it is joinable, ensuring complete cleanup.
See also
Note
Call this during session shutdown or before destroying the TerminalBackend instance.
-
void render_loop(void)
Main rendering loop executed by the background render thread.
Runs continuously while thread_running is true. Uses cv_redraw condition variable with a 1500ms timeout to wait efficiently for redraw requests. Handles terminal resize events (endwin(), refresh(), update_layout(), cursor recalculation). Conditionally redraws UI components (draw_ui, draw_output_area, draw_input_area, draw_spinner) when should_redraw is set. All ncurses operations are protected by ui_mutex.
See also
start_render_thread(), stop_render_thread(), draw_ui(), draw_output_area(), draw_input_area(), draw_spinner()
Note
This method is the entry point for the render thread and should not be called directly. Call start_render_thread() to spawn it. Terminate via stop_render_thread().
-
void print(const std::string &text, int type, bool stream = false)
Adds text to the output buffer and requests a redraw.
When stream is true and the output buffer is not empty, text is appended to the text of the last entry, and type is ignored. Otherwise, a new entry holding text and type is added to the end of the buffer. The buffer is modified while ui_mutex is held.
After the buffer is updated, the function sets should_redraw to true and wakes one thread waiting on cv_redraw. The lock is released before the notification is sent.
- Parameters:
text – The text to add to the output buffer.
type – The category of the new entry. It is ignored when text is appended to an existing entry.
stream – If true, text continues the most recent entry instead of starting a new one.
-
void clear_input_buffer(void)
Removes all characters from the input buffer.
The buffer is empty after the call. Calling the function on an empty buffer has no effect. Any view previously returned by get_input_buffer is invalid after this call. The function does not acquire ui_mutex, so callers that share input_buffer across threads must synchronize access themselves.
-
bool exit_keys_in_input_buffer(void)
Reports whether the input buffer holds an exit command.
The buffer matches only when its entire contents are a single “q” or “Q”. A buffer that contains either character along with other input does not match. The function does not acquire ui_mutex, so callers that share input_buffer across threads must synchronize access themselves.
- Returns:
true if input_buffer is exactly “q” or “Q”, false otherwise.
-
bool room_for_prompt_in_input_buffer(void)
Reports whether the input buffer leaves room for a prompt.
The buffer has room for a prompt when its length is less than the terminal width (COLS) minus 40 columns, which is reserved for the prompt. COLS is read at each call, so the result follows terminal resizes.
The function does not acquire ui_mutex, so callers that share input_buffer across threads must synchronize access themselves.
- Returns:
true if input_buffer has room for a prompt, false otherwise.
-
bool input_buffer_is_empty(void)
Reports whether the input buffer contains no characters.
The function does not acquire ui_mutex. Its result can be out of date by the time the caller acts on it if another thread modifies input_buffer in the meantime.
- Returns:
true if input_buffer is empty, false otherwise.
-
std::string_view get_input_buffer(void) const
Returns a non-owning view of the current input buffer contents.
The view refers to the storage of input_buffer and does not copy it. It stays valid only until input_buffer is modified, for example by push_back_input_buffer or pop_back_input_buffer, which can reallocate or shrink the storage. It also remains valid only while this TerminalBackend exists. The function does not acquire ui_mutex, so callers that share input_buffer across threads must synchronize access themselves.
- Returns:
A view of input_buffer. Copy the contents if they must outlive the next modification of the buffer.
-
void pop_back_input_buffer(void)
Removes the last character from the input buffer.
The function does not check whether the buffer is empty. Calling it when input_buffer is empty is undefined behavior. Like push_back_input_buffer, it does not acquire ui_mutex, so callers that share input_buffer across threads must synchronize access themselves.
- Pre:
input_buffer is not empty.
-
void push_back_input_buffer(int ch)
Appends a character code to the end of the input buffer.
The value is stored as passed, without validation or conversion. The function does not acquire ui_mutex, so callers that share input_buffer across threads must synchronize access themselves.
- Parameters:
ch – The character code to append to input_buffer.
Public Static Attributes
-
static constexpr int MESSAGE_TYPE_NORMAL = 0
-
static constexpr int MESSAGE_TYPE_ERROR = 1
-
static constexpr int MESSAGE_TYPE_SUCCESS = 2
Private Functions
-
void init_dark_theme(void)
Initializes ncurses color pairs with a dark theme color scheme.
Enables ncurses color support via start_color(), allows the terminal’s default background color to be used via use_default_colors(), and defines all ColorPair color pair constants with semantic foreground/background combinations.
Most pairs use -1 as background, preserving the terminal’s default background color. HIGHLIGHT_PAIR uses black text on white background for strong contrast, and FOCUS_PAIR uses white text on blue background for focused element visibility.
This method should be called early during TerminalBackend initialization, before any colored text is rendered to the terminal.
-
void init_light_theme(void)
Initializes ncurses color pairs with a light theme color scheme.
Enables ncurses color support via start_color(), allows the terminal’s default background color to be used via use_default_colors(), and defines all ColorPair color pair constants with semantic foreground/background combinations optimized for light terminal backgrounds.
Unlike the dark theme, most pairs use white backgrounds for contrast against darker text. DEFAULT_PAIR uses black text on white for standard content, and HIGHLIGHT_PAIR inverts to white text on black for strong emphasis. FOCUS_PAIR uses black text on cyan background for focused element visibility.
This method should be called early during TerminalBackend initialization, before any colored text is rendered to the terminal. Select init_dark_theme() or init_light_theme() based on the user’s terminal background preference.
-
void init_ncurses(void)
Initializes the ncurses terminal UI with locale support, terminal configuration, color theming, and signal handling.
Sets the locale to UTF-8 for character encoding support and establishes TERMINFO fallback to the system terminfo database if not already set (handles Conan ncurses builds). Initializes ncurses with initscr(), terminating with error diagnostics on failure. Updates window layout via update_layout().
Configures terminal I/O: enables cbreak mode (immediate input) and disables echo. Attempts to enable function key and arrow key support via keypad(); non-fatal warning if unsupported. Sets input blocking mode (getch() waits for user input). Attempts to hide the cursor; non-fatal warning if unsupported.
If the terminal supports colors, initializes color pairs by calling init_dark_theme() or init_light_theme() based on the use_dark_theme flag, and sets the terminal background to DEFAULT_PAIR. Registers SIGWINCH signal handler for terminal window resize detection and SIGINT handler for interrupt cleanup.
Terminates the program on critical failures (initscr failure or terminal setup failure). Non-critical feature failures (keypad, cursor hiding) produce warnings but do not halt initialization.
-
void install_signal_handlers()
-
TerminalBackend()
-
class TextUtils
- #include <text_utils.hpp>
Utility class for text manipulation operations.
Provides static helpers for wrapping text to a maximum line width and for splitting text into overlapping, sentence-aware chunks suitable for vector embeddings.
Public Static Functions
-
static std::vector<std::string> wrap_text(const std::string &text, const int max_width)
Wraps text to fit within a maximum line width.
Breaks lines at the last space within the width. If a word is longer than the width, the line is broken at max_width characters.
Wraps text to fit within a maximum line width.
Splits the input text into lines, breaking at the last space that fits within max_width. Spaces at the start of each wrapped line and at the end of each line are removed.
Algorithm:
Remove leading spaces from the text.
While the remaining text is longer than max_width, find the last space at or before max_width.
If no space exists, break at max_width.
Emit the line without trailing spaces, then remove leading spaces from the rest.
Emit any remaining text.
Note
If a single word is longer than max_width, it is broken at max_width characters. Only space characters are treated as break points.
- Parameters:
text – The input text to wrap.
max_width – The maximum number of characters per line. Must be greater than 0.
text – The input text to wrap.
max_width – The maximum number of characters per line. Must be greater than 0.
- Returns:
A vector of wrapped lines. Each line is at most max_width characters.
- Throws:
std::invalid_argument – if max_width is 0 or negative.
- Returns:
A vector of wrapped lines. Each line is at most max_width characters. The last line may be shorter.
-
static std::vector<std::string> split_text(const std::string &text, const size_t chunk_size, const size_t overlap = 0)
Splits text into sentence-aware chunks with optional overlap.
Splits text into sentence-aware chunks with optional overlap.
Each chunk is at most chunk_size characters. The method prefers to end a chunk at a sentence boundary, then at any whitespace, and only splits inside a word when the window contains no whitespace in its second half. Chunks are at least chunk_size / 2 characters long, except for the final chunk.
Consecutive chunks share approximately overlap characters. The next chunk starts at the earliest sentence start inside the overlap region, or at the nearest word start if there is none. The overlap is therefore at most overlap characters and may be smaller.
Leading and trailing whitespace is removed from each chunk.
- Parameters:
text – The input text to split.
chunk_size – The maximum size of each chunk in characters. Must be greater than 0.
overlap – The approximate number of characters shared between consecutive chunks. Must be less than chunk_size. Defaults to 0.
text – The input text to split.
chunk_size – The maximum size of each chunk in characters. Must be greater than 0.
overlap – The approximate number of characters shared between consecutive chunks. Must be less than chunk_size.
- Returns:
A vector of chunks with leading and trailing whitespace removed.
- Throws:
std::invalid_argument – if chunk_size is 0 or overlap is greater than or equal to chunk_size.
- Returns:
A vector of chunks. Returns an empty vector if text contains only whitespace.
Private Static Functions
-
static bool is_space(const char c)
Checks whether a character is whitespace.
- Parameters:
c – The character to test.
- Returns:
true if c is a space, tab, newline, or other whitespace character.
-
static bool is_abbreviation(const std::string &text, const size_t space_idx)
Checks whether the token ending before a whitespace character is an abbreviation.
Checks whether the token ending before a whitespace character is an abbreviation.
Extracts the token that ends at space_idx, strips leading punctuation such as ‘(’ or ‘”’, converts it to lowercase, and compares it to abbreviationExceptions.
- Parameters:
text – The full input text.
space_idx – The index of the whitespace character that follows the token.
text – The full input text.
space_idx – The index of the whitespace character that follows the token.
- Returns:
true if the token (case-insensitive) is in abbreviationExceptions.
- Returns:
true if the token is in abbreviationExceptions.
-
static bool is_sentence_boundary(const std::string &text, const size_t i)
Checks whether a whitespace character marks the end of a sentence.
A sentence ends at whitespace preceded by ‘!’ or ‘?’, or by ‘.’ when the preceding token is not an abbreviation.
- Parameters:
text – The full input text.
i – The index to test. Must be less than text.length().
- Returns:
true if index i is a sentence boundary.
-
static size_t find_break(const std::string &text, const size_t start, const size_t end, const size_t min_len)
Finds the best position to end a chunk within a window.
Searches backward from end for a sentence boundary, then for any whitespace. Only positions at or after start + min_len are considered, so the resulting chunk is at least min_len characters long.
Finds the best position to end a chunk within a window.
Searches backward from end for a sentence boundary first, then for any whitespace. Only positions at or after start + min_len are considered, so the resulting chunk is at least min_len characters long.
- Parameters:
text – The full input text.
start – The index where the current chunk begins.
end – The maximum index for the chunk end. Must be less than text.length().
min_len – The minimum chunk length in characters.
text – The full input text.
start – The index where the current chunk begins.
end – The maximum index for the chunk end. Must be less than text.length().
min_len – The minimum chunk length in characters.
- Returns:
The break index, or 0 if no suitable break exists.
- Returns:
The break index, or 0 if no suitable break exists.
Private Static Attributes
-
static const std::vector<std::string> abbreviationExceptions = {"e.g.", "i.e.", "vs.", "approx.", "dr.", "mr.", "mrs.", "ms.", "prof.", "jr.", "sr.", "st.", "fig.", "no.", "vol.", "pp.", "ca."}
Abbreviations that end with a period but do not end a sentence. Entries are lowercase and include the trailing period.
-
static std::vector<std::string> wrap_text(const std::string &text, const int max_width)
-
class UserInterface
- #include <user_interface.hpp>
ncurses-based terminal user interface for interactive prompting and output display.
Manages full-screen UI rendering with UTF-8 box borders, input buffer, scrollable output, animated progress spinner, and configurable dark/light themes. Runs a background render thread that updates the display on demand or every 1500ms. Handles terminal resize (SIGWINCH) and interrupt (SIGINT) signals. Supports dual interactive/noninteractive modes.
Message types: MESSAGE_TYPE_NORMAL (plain text), MESSAGE_TYPE_ERROR (bold red with ❌), MESSAGE_TYPE_SUCCESS (bold with ✅).
See also
run(), end_session(), ProgressSpinner (friend class)
Note
Singleton pattern via static instance pointer; used by signal handlers.
Note
Thread-safe: output_buffer and spinner state protected by ui_mutex and atomic flags.
Note
Must call run() to initialize ncurses and start rendering before using print/spinner methods.
Note
Noninteractive methods (print_*_noninteractive, select_model_noninteractive, next_prompt_noninteractive) must be used outside an active ncurses session.
Public Functions
-
UserInterface()
Constructs a UserInterface instance and initializes member variables.
Initializes the TerminalBackend.
-
explicit UserInterface(bool dark_theme)
Constructs a UserInterface instance with a caller-specified color theme preference.
Initializes the TerminalBackend.
- Parameters:
dark_theme – Boolean flag to select color scheme; true for dark theme, false for light theme.
-
~UserInterface()
Destructs a UserInterface instance and releases ncurses resources.
-
bool backend_running()
Reports whether the backend’s thread is currently running.
The function returns the result of backend->is_running(). It does not acquire ui_mutex, and the value can change immediately after the call returns.
Note
Use this for status checks only. Do not use it to decide whether to start or stop the backend without coordinating through another synchronization mechanism, because the state can change between the check and the action.
- Returns:
true if the backend thread is running, false otherwise.
- Pre:
backend is not null.
-
void run(void)
Runs the user interface by delegating to the backend.
The function calls backend->run() and does nothing else. The behavior, including whether and when the call returns, is defined by TerminalBackend::run().
Note
Any blocking, error handling, or session termination happens inside TerminalBackend::run(). Refer to that method’s documentation for those details.
- Pre:
backend is not null.
-
void end_session(int code = EXIT_SUCCESS)
Shows a session-ended message, ends the backend session.
The function calls print_message() with the end-of-session message, calls backend->end_session() to stop the render thread and restore the terminal, and then calls std::exit(code). The function does not return.
- Pre:
backend is not null.
-
void print_args(const std::string &model, const std::string &embedding_model, const std::string &prompt, bool stream, bool rag, bool interactive, bool dark_theme, bool skip_embedding)
Displays runtime configuration arguments as formatted diagnostic output.
Constructs a multi-line diagnostic string containing all provided configuration parameters. Each parameter is formatted with a 🛈 (information) icon prefix for visual consistency. Boolean parameters are converted to human-readable “true” or “false” strings using conditional operators, then concatenated into the buffer.
Prints the formatted buffer via this->print_message(), displaying the configuration summary in the output area for user visibility.
Output is displayed via print() and committed to the output buffer.
Acts as a diagnostic utility to confirm application startup parameters and aid in troubleshooting configuration issues. Typically called early during initialization to provide user confirmation of active settings.
Enables transparency into runtime configuration and helps users verify that the correct models, modes, and theme are in effect.
- Parameters:
model – Name of the primary language model in use.
embedding_model – Name of the embedding model in use.
prompt – Initial prompt or query string provided by the user.
stream – Boolean flag indicating whether streaming mode is enabled.
rag – Whether to run the program in the Retrieval Augmented Generation mode.
interactive – Boolean flag indicating whether interactive mode is enabled.
dark_theme – Boolean flag indicating whether dark theme is active.
skip_embedding – Whether to skip vectorizing documents and creating embeddings.
- Returns:
void
-
void print_model_list(const std::vector<std::string> &models)
Displays a numbered list of available models to the user via the UI buffer.
Renders an interactive model selection menu by formatting each model name with its zero-indexed position. This method is used during interactive sessions to present available Ollama models to the user, enabling selection via numeric input.
Constructs a formatted string buffer containing an information message (”🛈 Select a
model from the list below:”) followed by a numbered list. Each entry is formatted as “[index] model_name” on a separate line, where index is zero-based and automatically converted from the loop counter using std::to_string().
Outputs the constructed buffer to the ncurses UI using print_message() styling, ensuring the model list appears in the output area and is preserved in the UI’s output_buffer for proper rendering and scrolling.
Note
This method assumes models is not empty; calling with an empty vector will display only the header message without any selectable options. Typically called after successfully retrieving the model list from the Ollama server via query_model_list().
- Parameters:
models – A constant reference to a vector of model name strings to be displayed.
- Returns:
void
-
void select_model(const std::vector<std::string> &models, std::string *model)
Prompts the user to select a model by numeric index via interactive keyboard input.
Validates that models is not empty; exits with error if no models are available. Clears the input buffer and enters a getch() loop to capture user input, supporting backspace (KEY_BACKSPACE or 127) and printable characters with length constraints. Input terminates on newline (Enter key).
Interprets input as a zero-indexed model position via stoi(). If input is “q” or “Q”, terminates the session. If the index is out of bounds, prints an error and recursively re-prompts. If valid, dereferences model and assigns the selected model name.
Note
Input buffer length is capped at COLS - 40 to prevent overflow. Invalid indices trigger recursive retry. Quit commands (q/Q) terminate the entire session.
- Parameters:
models – A constant reference to a vector of available model name strings.
model – A pointer to a string where the selected model name will be stored.
- Returns:
void
-
bool next_prompt(std::string *prompt)
Reads one line of user input into the prompt and reports whether it is an exit request.
The function requests a redraw, clears the input buffer, and then reads keys with getch() until Enter (’
’) is pressed. Backspace removes the last character and moves the cursor left. A printable character is appended only if room_for_prompt_in_input_buffer() is true, and it moves the cursor right. Each change requests a redraw. When Enter is pressed, the buffer contents are copied into *prompt. The function returns true if the text is exactly “q” or “Q”.
Note
getch() blocks until a key is pressed. Non-printable keys, such as arrow keys, are ignored. An ERR return is also ignored, but only because it fails the isprint() test. In non-blocking mode, this loop would busy-wait.
Note
The input buffer is modified without holding ui_mutex. The render thread can read it at the same time, so this is a data race unless the caller guarantees that the render thread is not reading the buffer.
- Parameters:
prompt – Output string that receives the entered text. Must not be null.
- Returns:
true if the entered text is “q” or “Q”, otherwise false.
- Pre:
prompt is not null.
- Post:
*prompt holds the text the user entered. The input buffer still holds the same text.
-
void print_error(const std::string &text)
Queues an error message (bold red with ❌ prefix) and requests a redraw.
- Parameters:
text – The error message content.
-
void print_success(const std::string &text)
Queues a success message (bold with ✅ prefix) and requests a redraw.
- Parameters:
text – The success message content.
-
void print_message(const std::string &text, bool stream = false)
Queues a normal message (plain text) and requests a redraw.
- Parameters:
text – The message content.
stream – In the stream mode, every chunk of text after the first one is appended to the last buffer entry. Defaults to ‘false’.
-
void request_redraw(void)
Requests a redraw and wakes a thread waiting on cv_redraw.
The function sets should_redraw to true through set_should_redraw(true), then calls notify_cv_redraw() with its default argument. The method does not acquire ui_mutex.
Note
The flag is set before the notification, and there is no lock between them. A waiting thread can wake, see the flag, and proceed before the notification is sent. The waiter can then miss the signal and go back to sleep, or it can process the flag without needing the notification.
Warning
The waiter’s predicate must be checked under ui_mutex. Otherwise a notification sent between the waiter’s check and its wait can be lost. Whether one or all waiters are woken depends on the default argument of notify_cv_redraw(), which should be documented at that declaration.
- Pre:
backend is not null.
- Post:
should_redraw is true, and a waiter on cv_redraw has been notified.
-
void start_spinner(void)
Starts the spinner from frame 0 and requests a redraw.
The function sets spinner_active to true, resets the spinner frame to 0 through set_spinner_frame(0), and sets should_redraw to true. Each setter is atomic on its own, but the three updates are not performed as a group and ui_mutex is not held. cv_redraw is not notified.
Note
A render thread can read the spinner state between the updates and see a partial result, such as an active spinner that still shows the previous frame.
Warning
If the three updates must appear together, hold ui_mutex across all of them with a single scoped lock. Call notify_cv_redraw() afterward if a waiting thread needs to wake up.
- Pre:
backend is not null.
- Post:
get_spinner_active() returns true, the spinner frame is 0, and should_redraw is true.
-
void stop_spinner(void)
Stops the spinner, resets its frame to 0, and requests a redraw.
The function sets spinner_active to false, resets the spinner frame to 0 through set_spinner_frame(0), and sets should_redraw to true. Each setter is atomic on its own, but the three updates are not performed as a group and ui_mutex is not held. cv_redraw is not notified.
Note
A render thread can read the spinner state between the updates and see a partial result, such as an inactive spinner with the previous frame still set.
Warning
If the three updates must appear together, hold ui_mutex across all of them with a single scoped lock. Call notify_cv_redraw() afterward if a waiting thread needs to wake up.
- Pre:
backend is not null.
- Post:
get_spinner_active() returns false, the spinner frame is 0, and should_redraw is true.
-
void advance_spinner_frame(void)
Advances the spinner to its next frame and requests a redraw, if the spinner is active.
The function first checks get_spinner_active(). If the spinner is running, it advances the frame through set_spinner_frame() and then sets should_redraw. Nothing happens if the spinner is inactive. The check and the update are not performed under a lock, and the method does not notify cv_redraw.
Note
The check and the update are not atomic together. If the spinner is deactivated between them, the frame can still advance once after deactivation. This is usually harmless for a visual effect.
Warning
Because cv_redraw is not notified, a waiting thread may not redraw until it is woken by another call. Use notify_cv_redraw() if an immediate redraw is needed.
- Pre:
backend is not null.
- Post:
If the spinner was active at the check, its frame has advanced by one step and should_redraw is true.
-
void set_progress(int percent)
Updates the displayed progress percentage and requests a redraw.
The value is clamped to the range [0, 100] before being stored in the backend. The progress value and the redraw flag are set through two separate atomic operations, so the change is not applied as a single unit. This method does not acquire ui_mutex and does not notify cv_redraw.
Note
A thread that reads the progress value between the two calls can see the new percentage before the redraw request is set. This is usually harmless but can cause a brief inconsistency.
Warning
Because cv_redraw is not notified, a thread waiting on it may not wake up to redraw. Callers that need an immediate redraw must notify it separately with notify_cv_redraw().
- Parameters:
percent – The requested progress percentage. Values below 0 are stored as 0, and values above 100 are stored as 100.
- Pre:
backend is not null.
- Post:
The backend’s progress value is between 0 and 100, inclusive.
- Post:
should_redraw is set to true.
Public Static Functions
-
static std::shared_ptr<UserInterface> create()
Creates a UserInterface instance with the light theme as the default color scheme.
Delegates to create(bool) with dark_theme set to false, so use_dark_theme is initialized to the light theme. Any previously stored instance is replaced by the new one.
Note: This overload does not call init_ncurses(). The caller must invoke init_ncurses() explicitly on the returned instance to set up the terminal, color pairs, and input handling.
- Returns:
: Shared pointer to the newly created UserInterface, also stored in the static instance member.
-
static std::shared_ptr<UserInterface> create(bool dark_theme)
Creates a UserInterface instance with a caller-specified color theme preference and registers it as the singleton instance.
Allocates a new UserInterface through the constructor, passing dark_theme so that use_dark_theme is set during construction. Assigns the new object to instance, replacing any previously stored value. Returns the shared pointer to the caller.
Note: This method does not call init_ncurses(). The caller must invoke init_ncurses() explicitly on the returned instance to set up the terminal, color pairs, and input handling.
- Parameters:
dark_theme – Boolean flag to select color scheme; true for dark theme, false for light theme.
- Returns:
: Shared pointer to the newly created UserInterface, also stored in the static instance member.
-
static void print_args_noninteractive(const std::string &model, const std::string &embedding_model, const std::string &prompt, bool stream, bool rag, bool interactive, bool dark_theme, bool skip_embedding)
Displays runtime configuration arguments to stdout in non-interactive mode.
Outputs runtime configuration to standard output (stdout) using printf(), bypassing the ncurses UI buffer. This method is used when the application runs in non-interactive mode, where the terminal UI is not initialized and direct console output is required.
Constructs and prints a multi-line diagnostic string containing all provided configuration parameters. Each parameter is formatted with a 🛈 (information) icon prefix for visual consistency with interactive mode output. Boolean parameters are converted to human-readable “true” or “false” strings using conditional operators.
Includes leading and trailing newlines (printf(“\n”)) to visually separate the configuration summary from other console output, improving readability in log files and terminal sessions.
Acts as the non-interactive counterpart to print_args(). Enables configuration transparency and aids in troubleshooting when the application runs in batch or command-line mode without the interactive terminal UI.
Note
This method uses direct printf() calls and should only be used before ncurses initialization or after cleanup, to avoid conflicts with the ncurses output buffer.
- Parameters:
model – Name of the primary language model in use.
embedding_model – Name of the embedding model in use.
prompt – Initial prompt or query string provided by the user.
stream – Boolean flag indicating whether streaming mode is enabled.
rag – Whether to run the program in the Retrieval Augmented Generation mode.
interactive – Boolean flag indicating whether interactive mode is enabled.
dark_theme – Boolean flag indicating whether dark theme is active.
skip_embedding – Whether to skip vectorizing documents and creating embeddings.
- Returns:
void
-
static void print_model_list_noninteractive(const std::vector<std::string> &models)
Outputs a numbered list of available models to stdout in non-interactive mode.
Formats and prints each model with its zero-indexed position as “[index] model_name” using printf() directly, bypassing the ncurses UI buffer. Called when the application runs in non-interactive mode and the terminal UI is not initialized.
Note
This method should only be used before ncurses initialization or after cleanup.
- Parameters:
models – A constant reference to a vector of model name strings.
- Returns:
void
-
static void select_model_noninteractive(const std::vector<std::string> &models, std::string *model)
Prompts for a model selection via stdin in non-interactive mode.
Validates that models is not empty; exits with error if none are available. Loops until a valid zero-indexed model position is successfully read from stdin via scanf(). Repeats the prompt if scanf() fails to read exactly one integer or if the index is out of bounds. Prints validation errors to stderr. On valid input, dereferences model and assigns the selected model name.
Note
Uses stderr for error messages and stdout for prompts. Loop continues until scanf() succeeds and index is within [0, models.size()).
- Parameters:
models – A constant reference to a vector of available model name strings.
model – A pointer to a string where the selected model name will be stored.
- Returns:
void
-
static bool next_prompt_noninteractive(std::string *prompt)
Captures the next user prompt via stdin in non-interactive mode and detects quit commands.
Prompts the user via stdout and reads a line from stdin using std::getline(). Terminates the program with exit code 1 if input reading fails. Detects quit commands (“q” or “Q”) and returns true to signal session termination.
See also
Note
Must be used outside an active ncurses session. Uses stdout/stderr for I/O.
- Parameters:
prompt – A pointer to a string where the captured prompt will be stored.
- Returns:
bool True if the user entered “q” or “Q” (quit command); false otherwise.
-
static void print_error_noninteractive(const std::string &text)
Outputs a message directly to stderr in non-interactive mode.
Writes the text to stderr and immediately flushes the output buffer to ensure the message is visible without waiting for a newline. Adds an icon ❌ before the text.
See also
Note
Must be used outside an active ncurses session.
- Parameters:
text – The message content to be displayed.
-
static void print_success_noninteractive(const std::string &text)
Outputs a message directly to stdout in non-interactive mode.
Writes the text to stdout and immediately flushes the output buffer to ensure the message is visible without waiting for a newline. Adds an icon ✅ before the text.
See also
Note
Must be used outside an active ncurses session.
- Parameters:
text – The message content to be displayed.
-
static void print_message_noninteractive(const std::string &text)
Outputs a message directly to stdout in non-interactive mode.
Writes the text to stdout and immediately flushes the output buffer to ensure the message is visible without waiting for a newline.
See also
Note
Must be used outside an active ncurses session.
- Parameters:
text – The message content to be displayed.
Private Members
-
std::unique_ptr<TerminalBackend> backend
Private Static Attributes
-
static std::weak_ptr<UserInterface> instance
Friends
- friend class ProgressSpinner
-
UserInterface()
-
struct WebContent
- #include <curl_utils.hpp>
Web content fetch result.
-
struct WebContentStream
- #include <curl_utils.hpp>
Web content stream result.
-
namespace std
- file progress_spinner.cpp
- #include “progress_spinner.hpp”#include <atomic>#include <chrono>#include <curl/curl.h>#include <iostream>#include <thread>
- file progress_spinner.hpp
- #include “user_interface.hpp”#include <atomic>#include <curl/curl.h>#include <iostream>#include <thread>
- file terminal_backend.cpp
- #include “terminal_backend.hpp”#include “utils/exit_request.hpp”#include <chrono>#include <csignal>#include <cstdlib>#include <cstring>#include <iostream>#include <locale>#include <ncurses.h>#include <sstream>#include <stdexcept>#include <utility>
Enums
-
enum ColorPair
Semantic color pair identifiers for terminal UI rendering.
Defines named color pair constants for consistent theming across the application. Each constant maps to an ncurses color pair ID, enabling semantic color assignment for different UI contexts and message types. Values range from 1 to 9, matching ncurses color pair initialization indices.
DEFAULT_PAIR: Standard text color for neutral content
HIGHLIGHT_PAIR: Emphasis color for selected or important items
SUCCESS_PAIR: Color for successful operations or positive messages
WARNING_PAIR: Color for cautionary messages or non-critical issues
ERROR_PAIR: Color for error messages and critical failures
INFO_PAIR: Color for informational messages
MUTED_PAIR: Subdued color for de-emphasized content
ACCENT_PAIR: Decorative color for visual variety and UI separation
FOCUS_PAIR: Color for focused or active UI elements
Values:
-
enumerator DEFAULT_PAIR
-
enumerator HIGHLIGHT_PAIR
-
enumerator SUCCESS_PAIR
-
enumerator WARNING_PAIR
-
enumerator ERROR_PAIR
-
enumerator INFO_PAIR
-
enumerator MUTED_PAIR
-
enumerator ACCENT_PAIR
-
enumerator FOCUS_PAIR
-
enum ColorPair
- file terminal_backend.hpp
- #include “terminal_backend.hpp”#include “utils/text_utils.hpp”#include <atomic>#include <condition_variable>#include <exception>#include <functional>#include <mutex>#include <ncurses.h>#include <signal.h>#include <string>#include <thread>#include <vector>
- file user_interface.cpp
- #include “user_interface.hpp”#include “utils/exit_request.hpp”#include <chrono>#include <csignal>#include <cstdlib>#include <cstring>#include <iostream>#include <locale>#include <sstream>
- file user_interface.hpp
- #include “terminal_backend.hpp”#include <atomic>#include <condition_variable>#include <functional>#include <mutex>#include <ncurses.h>#include <signal.h>#include <string>#include <thread>#include <vector>
- file main.cpp
- #include “interface/user_interface.hpp”#include “ollama/ollama_client.hpp”#include “storage/qdrant_client.hpp”#include “utils/args_utils.hpp”#include “utils/curl_utils.hpp”#include “utils/embedding_utils.hpp”#include “utils/exit_request.hpp”#include “utils/retrieving_utils.hpp”#include “utils/system_utils.hpp”#include “utils/text_utils.hpp”#include <iostream>#include <unistd.h>#include <vector>
Functions
-
int main(int argc, const char *argv[])
-
int main(int argc, const char *argv[])
- file ollama_client.cpp
- #include “ollama_client.hpp”#include <algorithm>#include <cstdlib>#include <curl/curl.h>#include <format>#include <iostream>#include <nlohmann/json.hpp>#include <sstream>#include <string>
Functions
- template const std::string & OllamaClient::get_config_value< std::string > (const std::string &) const
- file ollama_client.hpp
- #include “interface/progress_spinner.hpp”#include “interface/user_interface.hpp”#include “utils/curl_utils.hpp”#include “utils/system_utils.hpp”#include <curl/curl.h>#include <iostream>#include <optional>
- file qdrant_client.cpp
- #include “qdrant_client.hpp”#include <format>#include <nlohmann/json.hpp>#include <string>#include <vector>
- file qdrant_client.hpp
- #include “interface/user_interface.hpp”#include “utils/curl_utils.hpp”#include “utils/system_utils.hpp”#include <curl/curl.h>#include <iostream>
- file args_utils.cpp
- #include “args_utils.hpp”#include “utils/exit_request.hpp”
- file args_utils.hpp
- #include <functional>#include <string>#include <unordered_map>
- file curl_utils.cpp
- #include “curl_utils.hpp”#include <format>#include <string>
- file curl_utils.hpp
- #include “http_utils.hpp”#include “interface/progress_spinner.hpp”#include “interface/user_interface.hpp”#include <curl/curl.h>#include <iostream>#include <map>#include <optional>#include <string>
- file embedding_utils.cpp
- #include “embedding_utils.hpp”#include “utils/text_utils.hpp”#include <string>#include <vector>
- file embedding_utils.hpp
- #include “interface/user_interface.hpp”#include “ollama/ollama_client.hpp”#include “storage/qdrant_client.hpp”#include “utils/curl_utils.hpp”#include <vector>
- file exit_request.hpp
- #include <exception>
- file http_utils.hpp
- #include <format>#include <stdexcept>#include <string>
- file retrieving_utils.cpp
- #include “retrieving_utils.hpp”#include <nlohmann/json.hpp>#include <string>#include <vector>
- file retrieving_utils.hpp
- #include “interface/user_interface.hpp”#include “ollama/ollama_client.hpp”#include “storage/qdrant_client.hpp”#include “utils/curl_utils.hpp”#include <string>#include <vector>
- file system_utils.cpp
- #include “system_utils.hpp”#include <format>
- file system_utils.hpp
- #include “interface/user_interface.hpp”
- file text_utils.cpp
- #include “text_utils.hpp”#include <algorithm>#include <cctype>#include <stdexcept>
- file text_utils.hpp
- #include <cstddef>#include <string>#include <vector>
- dir src/interface
- dir src/ollama
- dir src
- dir src/storage
- dir src/utils
- example /home/runner/work/cpp-workspace/cpp-workspace/src/utils/http_utils.hpp
Exception thrown when an HTTP request fails with a non-2xx status code or CURL error.
Exception thrown when an HTTP request fails with a non-2xx status code or CURL error.Inherits from std::runtime_error and stores the HTTP status code for detailed error handling. Allows calling code to distinguish between different HTTP errors (e.g., 404 vs 500) and handle them appropriately.
try { std::string response = curl->fetch_web_content(url); } catch (const HttpException& e) { if (e.get_status_code() == 404) { std::cout << "Resource not found" << std::endl; } else { std::cout << "HTTP error: " << e.what() << std::endl; } }
#pragma once #include <format> #include <stdexcept> #include <string> class HttpException : public std::runtime_error { private: long status_code; public: HttpException(long status_code, const std::string& url) : std::runtime_error(std::format("HTTP {}: {}", status_code, url)), status_code(status_code) { } long get_status_code() const { return status_code; } };
See also