Gemini-cli for openwrt

for those who may want a gemini-cli for openwrt. I created this little program

in sdk of your openwrt version in the package folder create a folder called gemini-cli and another folder inside this called src

create a Makefile in gemini-cli folder add this to it

include $(TOPDIR)/rules.mk

PKG_NAME:=gemini-cli
PKG_VERSION:=1.0.0
PKG_RELEASE:=1

PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)

include $(INCLUDE_DIR)/package.mk

define Package/gemini-cli
  SECTION:=utils
  CATEGORY:=Utilities
  TITLE:=Gemini Interactions API C++ CLI
  DEPENDS:=+libcurl +libstdcpp +ca-bundle
  PKG_BUILD_DEPENDS:=nlohmannjson
endef

define Package/gemini-cli/description
  Lightweight C++17 CLI client for the Google Gemini Interactions API.
endef

define Package/gemini-cli/conffiles
/etc/gemini/config.ini
endef

define Build/Prepare
	mkdir -p $(PKG_BUILD_DIR)
	$(CP) ./src/* $(PKG_BUILD_DIR)/
endef

define Build/Compile
	$(TARGET_CXX) $(TARGET_CXXFLAGS) $(TARGET_CPPFLAGS) -std=c++17 -fexceptions -Os \
		$(PKG_BUILD_DIR)/gemini.cpp \
		$(TARGET_LDFLAGS) -lcurl \
		-o $(PKG_BUILD_DIR)/gemini
endef


define Package/gemini-cli/install
	$(INSTALL_DIR) $(1)/usr/bin
	$(INSTALL_BIN) $(PKG_BUILD_DIR)/gemini $(1)/usr/bin/gemini
	$(INSTALL_DIR) $(1)/etc/gemini
	$(INSTALL_CONF) $(PKG_BUILD_DIR)/config.ini $(1)/etc/gemini/config.ini
endef

$(eval $(call BuildPackage,gemini-cli))

in the src folder create gemini.cpp and add this to it

#include <curl/curl.h>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <nlohmann/json.hpp>

#ifdef _WIN32
    #include <windows.h>
    #include <io.h>
    #define ISATTY _isatty
    #define FILENO _fileno
#else
    #include <unistd.h>
    #include <limits.h>
    #ifdef __APPLE__
        #include <mach-o/dyld.h>
    #endif
    #define ISATTY isatty
    #define FILENO fileno
#endif

namespace fs = std::filesystem;
using Json = nlohmann::json;

struct Config {
    std::string api_key;
    std::string url = "https://googleapis.com";
    std::string api_revision = "2026-05-20";
    std::string model = "gemini-3.5-flash-lite";
    std::string system_instruction;
};

std::string trim(const std::string& str) {
    size_t first = str.find_first_not_of(" \t\r\n\"'");
    if (first == std::string::npos) return "";
    size_t last = str.find_last_not_of(" \t\r\n\"'");
    return str.substr(first, (last - first + 1));
}

fs::path getExecutableDir() {
#ifdef _WIN32
    char path[MAX_PATH];
    GetModuleFileNameA(NULL, path, MAX_PATH);
    return fs::path(path).parent_path();
#elif __APPLE__
    char path[PATH_MAX];
    uint32_t size = sizeof(path);
    if (_NSGetExecutablePath(path, &size) == 0) {
        return fs::canonical(path).parent_path();
    }
    return fs::current_path();
#else
    std::error_code ec;
    fs::path exe = fs::read_symlink("/proc/self/exe", ec);
    return ec ? fs::current_path() : exe.parent_path();
#endif
}

Config loadConfig(const fs::path& filepath) {
    Config cfg;
    std::ifstream file(filepath);
    if (!file.is_open()) return cfg;

    std::string line;
    while (std::getline(file, line)) {
        size_t comment_pos = line.find_first_of("#;");
        if (comment_pos != std::string::npos) {
            line = line.substr(0, comment_pos);
        }

        std::string cleaned = trim(line);
        if (cleaned.empty() || cleaned.front() == '[') {
            continue;
        }

        size_t pos = cleaned.find('=');
        if (pos != std::string::npos) {
            std::string key = trim(cleaned.substr(0, pos));
            std::string val = trim(cleaned.substr(pos + 1));

            if (key == "api_key") cfg.api_key = val;
            else if (key == "url" && !val.empty()) cfg.url = val;
            else if (key == "api_revision" && !val.empty()) cfg.api_revision = val;
            else if (key == "model" && !val.empty()) cfg.model = val;
            else if (key == "system_instruction") cfg.system_instruction = val;
        }
    }
    return cfg;
}

size_t writeCallback(void* contents, size_t size, size_t nmemb, std::string* userp) {
    size_t total = size * nmemb;
    userp->append(static_cast<char*>(contents), total);
    return total;
}

int main(int argc, char* argv[]) {
    std::string cli_prompt;
    for (int i = 1; i < argc; ++i) {
        cli_prompt += argv[i];
        if (i < argc - 1) cli_prompt += " ";
    }

    std::string piped_input;
    if (!ISATTY(FILENO(stdin))) {
        std::ostringstream ss;
        ss << std::cin.rdbuf();
        piped_input = ss.str();
    }

    std::string final_prompt;
    if (!cli_prompt.empty() && !piped_input.empty()) {
        final_prompt = cli_prompt + "\n\n---\n" + piped_input;
    } else if (!cli_prompt.empty()) {
        final_prompt = cli_prompt;
    } else if (!piped_input.empty()) {
        final_prompt = piped_input;
    } else {
        std::cerr << "Usage: " << argv[0] << " \"<prompt>\"\n";
        std::cerr << "   or: cat file.txt | " << argv[0] << " \"<prompt>\"\n";
        return 1;
    }

    fs::path config_path = getExecutableDir() / "config.ini";
    if (!fs::exists(config_path)) {
        if (fs::exists("/etc/gemini/config.ini")) {
            config_path = "/etc/gemini/config.ini";
        } else {
            config_path = "config.ini";
        }
    }

    Config cfg = loadConfig(config_path);
    if (cfg.api_key.empty() || cfg.api_key == "YOUR_ACTUAL_API_KEY_HERE") {
        std::cerr << "Error: Valid 'api_key' not found in " << config_path << "\n";
        return 1;
    }

    Json request_body = {
        {"model", cfg.model},
        {"input", final_prompt}
    };

    if (!cfg.system_instruction.empty()) {
        request_body["system_instruction"] = cfg.system_instruction;
    }

    std::string json_payload = request_body.dump();
    std::string auth_header = "x-goog-api-key: " + cfg.api_key;
    std::string revision_header = "Api-Revision: " + cfg.api_revision;
    std::string response_buffer;

    CURL* curl = curl_easy_init();
    if (!curl) return 1;

    struct curl_slist* headers = nullptr;
    headers = curl_slist_append(headers, "Content-Type: application/json");
    headers = curl_slist_append(headers, auth_header.c_str());
    headers = curl_slist_append(headers, revision_header.c_str());

    curl_easy_setopt(curl, CURLOPT_URL, cfg.url.c_str());
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_payload.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_buffer);

    CURLcode res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        std::cerr << "Request failed: " << curl_easy_strerror(res) << "\n";
    } else {
        Json parsed = Json::parse(response_buffer, nullptr, false);
        if (parsed.is_discarded()) {
            std::cerr << "JSON Parse Error. Raw response:\n" << response_buffer << "\n";
        } else if (parsed.contains("error")) {
            std::cerr << "API Error: " << parsed["error"].value("message", "Unknown API error") << "\n";
        } else if (parsed.contains("steps") && !parsed["steps"].empty()) {
            const auto& last_step = parsed["steps"].back();
            if (last_step.contains("content")) {
                for (const auto& block : last_step["content"]) {
                    if (block.value("type", "") == "text" && block.contains("text")) {
                        std::cout << block.value("text", "");
                    }
                }
                std::cout << "\n";
            }
        } else {
            std::cerr << "Unexpected response format:\n" << parsed.dump(2) << "\n";
        }
    }

    curl_slist_free_all(headers);
    curl_easy_cleanup(curl);
    return 0;
}

and create another file called config.ini placing this in it

[Gemini]
api_key = your API key
url = https://generativelanguage.googleapis.com/v1beta/interactions
api_revision = 2026-05-20
model = gemini-3.5-flash-lite
system_instruction = Be concise, direct, and output plain text without markdown filler.


you will have to add the nlohmannjson feed to your sdk

./scripts/feeds update packages
./scripts/feeds install nlohmannjson

then

make nlohmannjson/compile V=s

then

make package/gemini-cli/compile V=s

in etc/gemini/conf.ini you can add your api key

say you are connected with ssh . then you can ask questions from the command line of openwrt:

gemini "What ports does OpenVPN use?"

or pipe stuff in

dmesg | tail -n 30 | gemini "Any hardware errors here?"

and it will compile in multiple os

linux for example

g++ -std=c++17 gemini.cpp -lcurl -o gemini

1 Like

example output from free tier , paid teir will give more accurate output for more complex questions

1 Like