// handler.cpp — реализация Ollama-совместимого HTTP-сервера для Xenith. // // Особенности реализации: // * ядро Xenith однопоточное и НЕ потокобезопасное (общий ForwardCache, // статические буферы в sample()), поэтому генерация сериализована g_gen_mtx; // * модели хранятся в shared_ptr — снимок на запрос стоит // копейки, а гонки при удалении модели невозможны; // * стриминг НАСТОЯЩИЙ: контент-провайдер cpp-httplib вызывается в том же // потоке, что и handler, поэтому генерация вынесена в отдельный поток, // а провайдер блокируется на condition_variable с таймаутом. При разрыве // соединения взводится GenConfig::cancel и генерация прерывается; // * /api/pull, /api/push и /api/blobs/:digest возвращают 501 — реестра // моделей у Xenith нет, модель создаётся через /api/create FROM <путь>. #include "handler.h" #include "../core/checkpoint.h" #include "../core/config.h" #include "../core/generate.h" #include "../core/model.h" #include "../backend/backend.h" #include "../ui/ui.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "../libs/cpp-httplib-0.57.1/httplib.h" #include "../libs/json-3.12.0/nlohmann/json.hpp" using json = nlohmann::json; namespace fs = std::filesystem; namespace xt { namespace { // Версия берётся из config.yaml / version.txt (подставляется на этапе сборки). // Раньше здесь было захардкожено "0.0.4", из-за чего GET /api/version врал // начиная с релиза 0.1.0. std::string g_version = "0.0.0"; std::string g_commit = ""; std::string g_build_type = ""; std::string g_api_key = ""; bool g_cors = true; // RFC3339/ISO-8601 в UTC. Раньше здесь была константа "1970-01-01T00:00:00Z", // из-за чего created_at/modified_at/expires_at у всех ответов были эпохой. std::string now_iso8601() { const auto now = std::chrono::system_clock::now(); const std::time_t t = std::chrono::system_clock::to_time_t(now); struct tm tmv{}; gmtime_r(&t, &tmv); char b[32]; std::strftime(b, sizeof b, "%Y-%m-%dT%H:%M:%SZ", &tmv); return b; } // --------------------------------------------------------------------------- // Реестр моделей // --------------------------------------------------------------------------- struct Entry { std::string name; std::string path; std::shared_ptr ck; // nullptr, пока не загружена std::string load_err; }; std::map g_models; // ключ — имя без ":latest" std::string g_default; std::mutex g_registry_mtx; std::mutex g_gen_mtx; // сериализация генерации bool g_verbose = false; std::string strip_tag(const std::string& n) { const size_t p = n.find(':'); return (p == std::string::npos) ? n : n.substr(0, p); } std::string display_name(const std::string& n) { return n.find(':') == std::string::npos ? n + ":latest" : n; } uint64_t file_size_or(const std::string& path, uint64_t fallback) { std::error_code ec; const auto sz = fs::file_size(path, ec); return ec ? fallback : (uint64_t)sz; } const char* backend_name() { Backend* b = backend(); return b ? b->name() : "cpu"; } std::string digest_of(const std::string& path) { char buf[32]; snprintf(buf, sizeof buf, "%016zx", std::hash{}(path)); return buf; } // --------------------------------------------------------------------------- // Конфиг // --------------------------------------------------------------------------- bool parse_conf(const std::string& path, OllamaOptions& opt, std::vector>& models) { std::ifstream f(path); if (!f) return false; std::ostringstream ss; ss << f.rdbuf(); const std::string text = ss.str(); // 1) JSON try { json j = json::parse(text); // Значения из командной строки (--host/--port/--model/--verbose/--no-scan) // конфигом не перекрываются. if (!opt.cli_host && j.contains("host") && j["host"].is_string()) opt.host = j["host"].get(); if (!opt.cli_port && j.contains("port") && j["port"].is_number_integer()) opt.port = j["port"].get(); if (!opt.cli_model && j.contains("default_model") && j["default_model"].is_string()) opt.default_model = j["default_model"].get(); if (!opt.cli_verbose && j.contains("verbose") && j["verbose"].is_boolean()) opt.verbose = j["verbose"].get(); if (!opt.cli_no_scan && j.contains("scan_models_dir") && j["scan_models_dir"].is_boolean()) opt.scan_models_dir = j["scan_models_dir"].get(); if (j.contains("api_key") && j["api_key"].is_string()) opt.api_key = j["api_key"].get(); if (j.contains("cors") && j["cors"].is_boolean()) opt.cors = j["cors"].get(); if (j.contains("models") && j["models"].is_array()) { for (const auto& m : j["models"]) { std::string n = m.value("name", ""); std::string p = m.value("path", ""); if (n.empty() && !p.empty()) n = fs::path(p).stem().string(); if (!n.empty() && !p.empty()) models.emplace_back(n, p); } } return true; } catch (const std::exception&) { /* не JSON — пробуем простой формат */ } // 2) "key: value", модели строками "model: name = path" std::istringstream ls(text); std::string line; while (std::getline(ls, line)) { const size_t c = line.find(':'); if (c == std::string::npos) continue; std::string k = line.substr(0, c), v = line.substr(c + 1); auto trim = [](std::string& s) { size_t a = 0, b = s.size(); while (a < b && std::isspace((unsigned char)s[a])) ++a; while (b > a && std::isspace((unsigned char)s[b-1])) --b; s = s.substr(a, b - a); }; trim(k); trim(v); if (k == "host" && !opt.cli_host) opt.host = v; else if (k == "port" && !opt.cli_port) opt.port = std::atoi(v.c_str()); else if (k == "default_model" && !opt.cli_model) opt.default_model = v; else if (k == "verbose" && !opt.cli_verbose) opt.verbose = (v == "true" || v == "1"); else if (k == "api_key") opt.api_key = v; else if (k == "cors") opt.cors = (v == "true" || v == "1"); else if (k == "model" || k == "models") { const size_t eq = v.find('='); if (eq != std::string::npos) models.emplace_back(v.substr(0, eq), v.substr(eq + 1)); else models.emplace_back(fs::path(v).stem().string(), v); } } return true; } void scan_models_dir(std::vector>& models, const std::string& dir) { std::error_code ec; if (dir.empty() || !fs::is_directory(dir, ec)) return; for (const auto& e : fs::directory_iterator(dir, ec)) { if (!e.is_regular_file() || e.path().extension() != ".xnh") continue; // Не подхватываем битые/пустые файлы: иначе моделью по умолчанию // (первая по алфавиту) мог стать кусок мусора, и каждый запрос // падал бы на загрузке. { std::ifstream probe(e.path(), std::ios::binary); uint32_t magic = 0; if (!probe.read(reinterpret_cast(&magic), 4) || magic != XNH_MAGIC) { fprintf(stderr, "[ollama] пропущен %s — не похоже на модель Xenith (магия 0x%08X)\n", e.path().c_str(), magic); continue; } } const std::string n = e.path().stem().string(); bool dup = false; for (auto& m : models) if (m.first == n) { dup = true; break; } if (!dup) models.emplace_back(n, e.path().string()); } } // --------------------------------------------------------------------------- // Доступ к модели (ленивая загрузка). Возвращает снимок — после него // g_registry_mtx можно не держать. // --------------------------------------------------------------------------- struct ModelRef { std::shared_ptr ck; std::string name; // имя без тега std::string path; bool valid = false; }; ModelRef acquire(const std::string& wanted, std::string& err) { ModelRef out; std::lock_guard lk(g_registry_mtx); std::string name = strip_tag(wanted.empty() ? g_default : wanted); if (name.empty()) { if (g_models.empty()) { err = "no models registered"; return out; } name = g_models.begin()->first; } auto it = g_models.find(name); if (it == g_models.end()) { // может, передали путь к файлу? std::error_code ec; if (!wanted.empty() && fs::exists(wanted, ec) && fs::path(wanted).extension() == ".xnh") { const std::string stem = fs::path(wanted).stem().string(); it = g_models.find(stem); if (it == g_models.end()) it = g_models.emplace(stem, Entry{}).first; it->second.name = stem; it->second.path = wanted; name = it->first; } else { err = "model '" + (wanted.empty() ? std::string("") : wanted) + "' not found"; return out; } } Entry& e = it->second; if (!e.ck) { auto ck = std::make_shared(); if (load_checkpoint(e.path, *ck, e.load_err)) { e.ck = ck; if (g_verbose) fprintf(stderr, "[ollama] загружена %s (%s, %.2f М параметров)\n", e.name.c_str(), e.path.c_str(), ck->params.n_params() / 1048576.0); } else { err = "failed to load '" + e.path + "': " + e.load_err; return out; } } out.ck = e.ck; out.name = e.name; out.path = e.path; out.valid = true; return out; } // --------------------------------------------------------------------------- // JSON-хелперы // --------------------------------------------------------------------------- std::string jdump(const json& j) { return j.dump(); } json err_json(const std::string& msg) { return json{{"error", msg}}; } bool jbool(const json& j, const char* k, bool def) { return (j.contains(k) && j[k].is_boolean()) ? j[k].get() : def; } std::string jstr(const json& j, const char* k, const std::string& def = "") { return (j.contains(k) && j[k].is_string()) ? j[k].get() : def; } // значение из тела запроса ИЛИ из вложенного "options" (у Ollama настройки там) template T jopt(const json& j, const char* k, T def); template <> int jopt(const json& j, const char* k, int def) { if (j.contains("options") && j["options"].is_object() && j["options"].contains(k) && j["options"][k].is_number()) return j["options"][k].get(); if (j.contains(k) && j[k].is_number()) return j[k].get(); return def; } template <> float jopt(const json& j, const char* k, float def) { if (j.contains("options") && j["options"].is_object() && j["options"].contains(k) && j["options"][k].is_number()) return (float)j["options"][k].get(); if (j.contains(k) && j[k].is_number()) return (float)j[k].get(); return def; } template <> [[maybe_unused]] bool jopt(const json& j, const char* k, bool def) { if (j.contains("options") && j["options"].is_object() && j["options"].contains(k) && j["options"][k].is_boolean()) return j["options"][k].get(); if (j.contains(k) && j[k].is_boolean()) return j[k].get(); return def; } // Строковое поле тела запроса: пустая строка, если ключа нет; ok=false, если // ключ есть, но значение не строка (раньше такое молча считалось пустым // промптом, и сервер вместо 400 выдавал полноценную генерацию). bool jstr_checked(const json& j, const char* k, std::string& out, bool& ok) { ok = true; if (!j.contains(k) || j[k].is_null()) { out.clear(); return false; } if (j[k].is_string()) { out = j[k].get(); return true; } ok = false; out.clear(); return false; } GenConfig build_gen_config(const json& j) { GenConfig gc; // num_predict: -1 = без лимита, 0 = ничего не генерировать, >0 = лимит. // Раньше ЛЮБОЕ значение <= 0 превращалось в 1<<20, то есть num_predict:0 // (и, скажем, -5) означало «миллион токенов» — запрос висел минутами. gc.max_new_tokens = jopt(j, "num_predict", 256); if (gc.max_new_tokens < 0) gc.max_new_tokens = 1 << 20; // -1 и прочие = без лимита if (gc.max_new_tokens > (1 << 20)) gc.max_new_tokens = 1 << 20; gc.temperature = jopt(j, "temperature", 0.8f); gc.top_k = jopt(j, "top_k", 40); gc.top_p = jopt(j, "top_p", 0.95f); gc.repeat_penalty = jopt(j, "repeat_penalty", 1.0f); gc.seed = jopt(j, "seed", -1); gc.stream = false; // стримингом занимается сервер return gc; } // Внутренние причины остановки ("eos" | "role" | "length" | "cancelled" | // "error" | "unknown") переводим в термины Ollama: клиенты ждут "stop" или // "length". "cancelled" у нас означает «сработала stop-строка» — это тоже stop. const char* ollama_done_reason(const std::string& internal) { if (internal == "length") return "length"; if (internal == "error") return "error"; return "stop"; } // "stop" бывает строкой или массивом строк std::vector build_stop(const json& j) { std::vector out; const json* s = nullptr; if (j.contains("options") && j["options"].is_object() && j["options"].contains("stop")) s = &j["options"]["stop"]; else if (j.contains("stop")) s = &j["stop"]; if (!s) return out; if (s->is_string()) out.push_back(s->get()); else if (s->is_array()) for (auto& e : *s) if (e.is_string()) out.push_back(e.get()); return out; } // Кусочек текста для стрима: после многосимвольного токена (слова) нужен пробел, // после одиночного символа — нет. Тот же правило, что в Tokenizer::decode. std::string piece_out(const Tokenizer& tok, int id, const std::string& piece) { if (id >= Tokenizer::n_special && id < tok.size() && tok.id2tok[id].size() > 1) return piece + " "; return piece; } // Если ответ содержит стоп-слово — обрезаем по нему (и чанки тоже). void apply_stop_words(std::string& text, const std::vector& stops) { if (stops.empty()) return; size_t cut = std::string::npos; for (const auto& s : stops) { if (s.empty()) continue; const size_t p = text.find(s); if (p != std::string::npos && p < cut) cut = p; } if (cut != std::string::npos) text.resize(cut); } // --------------------------------------------------------------------------- // Описание модели в формате Ollama // --------------------------------------------------------------------------- json model_details(const Entry& e) { const Config& c = e.ck->params.cfg; return json{ {"parent_model", ""}, {"format", "xnh"}, {"family", "xenith"}, {"families", json::array({"xenith"})}, {"parameter_size", std::to_string(e.ck->params.n_params())}, {"quantization_level", "F32"}, {"xenith", { {"layers", c.n_layer}, {"heads", c.n_head}, {"embedding_dim", c.n_embd}, {"ffn_dim", c.ffn()}, {"vocab_size", c.vocab_size}, {"block_size", c.block_size}, {"rope_base", c.rope_base}, {"tied", e.ck->params.tied()}, {"chat_capable", e.ck->tok.has_chat_tokens() && e.ck->tok.user >= 0} }} }; } json model_card(const Entry& e) { return json{ {"name", display_name(e.name)}, {"model", display_name(e.name)}, {"modified_at", now_iso8601()}, {"size", file_size_or(e.path, e.ck ? e.ck->params.n_params() * 4 : 0)}, {"digest", digest_of(e.path)}, {"details", e.ck ? model_details(e) : json{{"format", "xnh"}}} }; } // --------------------------------------------------------------------------- // Настоящий стриминг: продюсер в отдельном потоке, провайдер блокируется на cv. // --------------------------------------------------------------------------- struct StreamBuf { std::mutex m; std::condition_variable cv; std::deque q; bool done = false; std::string final_json; std::atomic cancel{false}; std::chrono::steady_clock::time_point last_pull = std::chrono::steady_clock::now(); }; void start_stream(httplib::Response& res, std::shared_ptr sb, std::function)> producer) { std::thread([sb, producer]() { try { producer(sb); } catch (...) { std::lock_guard lk(sb->m); sb->final_json = jdump(err_json("internal error during generation")); } { std::lock_guard lk(sb->m); sb->done = true; } sb->cv.notify_all(); }).detach(); res.set_chunked_content_provider( "application/x-ndjson", [sb](size_t /*offset*/, httplib::DataSink& sink) -> bool { std::unique_lock lk(sb->m); // ждём чанк не дольше 5 секунд за раз, чтобы заметить разрыв соединения sb->cv.wait_for(lk, std::chrono::seconds(5), [&]{ return !sb->q.empty() || sb->done; }); sb->last_pull = std::chrono::steady_clock::now(); if (!sb->q.empty()) { const std::string c = sb->q.front(); sb->q.pop_front(); lk.unlock(); if (!sink.write(c.data(), c.size())) { sb->cancel = true; return false; } return true; } if (sb->done) { const std::string f = sb->final_json; lk.unlock(); sb->cancel = true; if (!f.empty() && !sink.write(f.data(), f.size())) return false; sink.done(); return false; } // продюсер ещё считает (например, длинный prefill) — тянем пустой keep-alive lk.unlock(); return true; }); } // --------------------------------------------------------------------------- // Обработчики // --------------------------------------------------------------------------- void h_version(const httplib::Request&, httplib::Response& res) { res.set_content(jdump(json{{"version", g_version}, {"commit", g_commit}, {"build_type", g_build_type}, {"backend", backend_name()}}), "application/json"); } void h_health(const httplib::Request&, httplib::Response& res) { res.set_content(jdump(json{{"status", "ok"}, {"version", g_version}, {"backend", backend_name()}}), "application/json"); } void h_tags(const httplib::Request&, httplib::Response& res) { std::lock_guard lk(g_registry_mtx); json arr = json::array(); for (auto& kv : g_models) arr.push_back(model_card(kv.second)); res.set_content(jdump(json{{"models", arr}}), "application/json"); } void h_ps(const httplib::Request&, httplib::Response& res) { std::lock_guard lk(g_registry_mtx); json arr = json::array(); for (auto& kv : g_models) { const Entry& e = kv.second; if (!e.ck) continue; const uint64_t sz = e.ck->params.n_params() * 4; arr.push_back(json{ {"name", display_name(e.name)}, {"model", display_name(e.name)}, {"size", sz}, {"digest", digest_of(e.path)}, {"details", model_details(e)}, {"expires_at", now_iso8601()}, {"size_vram", sz} }); } res.set_content(jdump(json{{"models", arr}}), "application/json"); } void h_show(const httplib::Request& req, httplib::Response& res) { json body; try { body = req.body.empty() ? json::object() : json::parse(req.body); } catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; } // "model" обязан быть строкой: раньше не-строка молча превращалась в пустое // имя, и запрос уходил на модель по умолчанию вместо честного 400. std::string model_name; bool model_type_ok = true; jstr_checked(body, "model", model_name, model_type_ok); if (!model_type_ok) { res.status = 400; res.set_content(jdump(err_json("\"model\" must be a string")), "application/json"); return; } std::string err; ModelRef m = acquire(model_name, err); if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; } Entry e; e.name = m.name; e.path = m.path; e.ck = m.ck; json out = model_card(e); out["license"] = "MIT"; out["system"] = ""; out["template"] = "{{ .Prompt }}"; out["modelfile"] = std::string("# Xenith model\nFROM ") + m.path; out["parameters"] = "temperature 0.8\ntop_k 40\ntop_p 0.95\n"; out["model_info"] = model_details(e)["xenith"]; out["capabilities"] = (m.ck->tok.has_chat_tokens() && m.ck->tok.user >= 0) ? json::array({"completion", "embeddings"}) : json::array({"completion"}); res.set_content(jdump(out), "application/json"); } void h_create(const httplib::Request& req, httplib::Response& res) { json body; try { body = req.body.empty() ? json::object() : json::parse(req.body); } catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; } const std::string name = jstr(body, "model", jstr(body, "name")); if (name.empty()) { res.status = 400; res.set_content(jdump(err_json("model name required")), "application/json"); return; } // ищем "FROM <путь>" в modelfile std::string path; { std::istringstream ls(jstr(body, "modelfile")); std::string line; while (std::getline(ls, line)) { size_t a = 0; while (a < line.size() && std::isspace((unsigned char)line[a])) ++a; if (line.size() > a + 5 && line.compare(a, 5, "FROM ") == 0) { path = line.substr(a + 5); break; } } } while (!path.empty() && std::isspace((unsigned char)path.back())) path.pop_back(); std::error_code ec; if (path.empty() || !fs::exists(path, ec)) { res.status = 400; res.set_content(jdump(err_json("modelfile must contain 'FROM ' and that file must exist")), "application/json"); return; } { std::lock_guard lk(g_registry_mtx); Entry& e = g_models[strip_tag(name)]; e.name = strip_tag(name); e.path = path; e.ck.reset(); e.load_err.clear(); if (g_default.empty()) g_default = e.name; } std::string err; if (!acquire(name, err).valid) { res.status = 500; res.set_content(jdump(err_json(err)), "application/json"); return; } res.set_content(jdump(json{{"status", "success"}}), "application/json"); } void h_delete(const httplib::Request& req, httplib::Response& res) { json body; try { body = req.body.empty() ? json::object() : json::parse(req.body); } catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; } const std::string name = strip_tag(jstr(body, "model", jstr(body, "name"))); std::lock_guard lk(g_registry_mtx); auto it = g_models.find(name); if (it == g_models.end()) { res.status = 404; res.set_content(jdump(err_json("model '" + name + "' not found")), "application/json"); return; } g_models.erase(it); if (g_default == name) g_default = g_models.empty() ? "" : g_models.begin()->first; res.status = 200; res.set_content("", "application/json"); } void h_not_implemented(const httplib::Request&, httplib::Response& res) { res.status = 501; res.set_content(jdump(err_json( "Xenith не работает с реестром моделей: зарегистрируй модель через " "POST /api/create с 'FROM <путь к .xnh>' или положи файл в каталог models/")), "application/json"); } // --- /api/generate --------------------------------------------------------- void h_generate(const httplib::Request& req, httplib::Response& res) { json body; try { body = req.body.empty() ? json::object() : json::parse(req.body); } catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; } // "model" обязан быть строкой: раньше не-строка молча превращалась в пустое // имя, и запрос уходил на модель по умолчанию вместо честного 400. std::string model_name; bool model_type_ok = true; jstr_checked(body, "model", model_name, model_type_ok); if (!model_type_ok) { res.status = 400; res.set_content(jdump(err_json("\"model\" must be a string")), "application/json"); return; } std::string err; ModelRef m = acquire(model_name, err); if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; } std::string prompt; bool prompt_ok = true; jstr_checked(body, "prompt", prompt, prompt_ok); if (!prompt_ok) { res.status = 400; res.set_content(jdump(err_json("\"prompt\" must be a string")), "application/json"); return; } const bool stream = jbool(body, "stream", true); const bool raw = jbool(body, "raw", false); const GenConfig gc = build_gen_config(body); const std::vector stops = build_stop(body); auto producer = [m, prompt, gc, stops, raw](std::shared_ptr sb) { std::lock_guard gen_lk(g_gen_mtx); const std::string model = display_name(m.name); GenConfig g = gc; g.cancel = &sb->cancel; std::vector history = raw ? m.ck->tok.encode(prompt, false) : m.ck->tok.encode(prompt, true); while (!history.empty() && history.back() == m.ck->tok.eos) history.pop_back(); if (history.empty()) history.push_back(m.ck->tok.bos); GenOutStats st; std::string running; // накопленный текст — для поиска стоп-слов // Чанк уходит сразу; при срабатывании стоп-слова взводим cancel, а лишний // хвост вырезается из итогового текста через apply_stop_words(). TokenCallback cb = [&](int id, const std::string& piece) { const std::string chunk = piece_out(m.ck->tok, id, piece); running += chunk; for (const auto& s : stops) { if (!s.empty() && running.find(s) != std::string::npos) { sb->cancel = true; break; } } { std::lock_guard lk(sb->m); sb->q.push_back(jdump(json{{"model", model}, {"created_at", now_iso8601()}, {"response", chunk}, {"done", false}}) + "\n"); } sb->cv.notify_one(); }; std::string text = generate_from(m.ck->params, m.ck->tok, history, g, &st, cb); apply_stop_words(text, stops); json fin = { {"model", model}, {"created_at", now_iso8601()}, {"response", text}, {"done", true}, {"done_reason", ollama_done_reason(st.stop_reason)}, {"total_duration", st.prefill_ns + st.gen_ns}, {"load_duration", 0}, {"prompt_eval_count", st.prompt_tokens}, {"prompt_eval_duration", st.prefill_ns}, {"eval_count", st.n_tokens()}, {"eval_duration", st.gen_ns} }; std::lock_guard lk(sb->m); sb->final_json = jdump(fin) + "\n"; }; if (stream) { start_stream(res, std::make_shared(), producer); return; } // --- нестриминговый путь: считаем синхронно --- auto sb = std::make_shared(); producer(sb); res.set_content(sb->final_json.empty() ? jdump(err_json("generation failed")) : sb->final_json, "application/json"); } // --- /api/chat ------------------------------------------------------------- void h_chat(const httplib::Request& req, httplib::Response& res) { json body; try { body = req.body.empty() ? json::object() : json::parse(req.body); } catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; } // "model" обязан быть строкой: раньше не-строка молча превращалась в пустое // имя, и запрос уходил на модель по умолчанию вместо честного 400. std::string model_name; bool model_type_ok = true; jstr_checked(body, "model", model_name, model_type_ok); if (!model_type_ok) { res.status = 400; res.set_content(jdump(err_json("\"model\" must be a string")), "application/json"); return; } std::string err; ModelRef m = acquire(model_name, err); if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; } if (!body.contains("messages") || !body["messages"].is_array()) { res.status = 400; res.set_content(jdump(err_json("\"messages\" must be an array of {role, content}")), "application/json"); return; } if (!m.ck->tok.has_chat_tokens() || m.ck->tok.user < 0) { res.status = 400; res.set_content(jdump(err_json("model '" + m.name + "' has no / tokens — " "chat is impossible; run `xenith fine-tune` first")), "application/json"); return; } const bool stream = jbool(body, "stream", true); const bool raw = jbool(body, "raw", false); const GenConfig gc = build_gen_config(body); const std::vector stops = build_stop(body); // Разбираем messages. Отдельного токена в словаре Xenith нет, // поэтому системный промпт приклеивается к последней user-реплике. std::string system_text, last_user; std::vector> prior; for (const auto& msg : body["messages"]) { if (!msg.is_object()) continue; // msg.value("content", "") бросает type_error, если значение не строка; // исключение из обработчика наружу выпускать нельзя — отвечаем 400. for (const char* kk : {"role", "content"}) { if (msg.contains(kk) && !msg[kk].is_string() && !msg[kk].is_null()) { res.status = 400; res.set_content(jdump(err_json(std::string("messages[].") + kk + " must be a string")), "application/json"); return; } } std::string role = msg.value("role", ""); const std::string text = msg.contains("content") && msg["content"].is_string() ? msg["content"].get() : std::string(); for (auto& ch : role) ch = (char)std::tolower((unsigned char)ch); if (role == "system") { system_text += (system_text.empty() ? "" : "\n") + text; } else if (role == "user") { if (!last_user.empty()) prior.emplace_back("user", last_user); last_user = text; } else if (role == "assistant") { if (!last_user.empty()) { prior.emplace_back("user", last_user); last_user.clear(); } prior.emplace_back("assistant", text); } // "tool" и прочие роли Xenith не поддерживает — пропускаем } std::string turn_text = system_text.empty() ? last_user : system_text + "\n" + last_user; auto producer = [m, prior, turn_text, gc, stops, raw](std::shared_ptr sb) { std::lock_guard gen_lk(g_gen_mtx); const std::string model = display_name(m.name); GenConfig g = gc; g.cancel = &sb->cancel; std::string text; GenOutStats st; if (raw) { std::string joined; for (const auto& pr : prior) joined += pr.second + "\n"; joined += turn_text; text = generate_from(m.ck->params, m.ck->tok, m.ck->tok.encode(joined, true), g, &st, nullptr); } else { std::vector history{m.ck->tok.bos}; // предыдущие ходы: user-реплики прогоняем через chat_turn с нулевой // генерацией (нужно лишь правильно пополнить history), assistant-реплики // кладём как есть — модель их не порождает. GenConfig pre = g; pre.max_new_tokens = 0; pre.cancel = nullptr; for (const auto& pr : prior) { if (pr.first == "user") { chat_turn(m.ck->params, m.ck->tok, history, pr.second, pre, nullptr, nullptr); } else { history.push_back(m.ck->tok.asst); auto ids = m.ck->tok.encode(pr.second, false); while (!ids.empty() && ids.back() == m.ck->tok.eos) ids.pop_back(); history.insert(history.end(), ids.begin(), ids.end()); history.push_back(m.ck->tok.eos); } } std::string running; TokenCallback cb = [&](int id, const std::string& piece) { const std::string chunk = piece_out(m.ck->tok, id, piece); running += chunk; for (const auto& s : stops) { if (!s.empty() && running.find(s) != std::string::npos) { sb->cancel = true; break; } } { std::lock_guard lk(sb->m); sb->q.push_back(jdump(json{{"model", model}, {"created_at", now_iso8601()}, {"message", {{"role","assistant"}, {"content", chunk}}}, {"done", false}}) + "\n"); } sb->cv.notify_one(); }; text = chat_turn(m.ck->params, m.ck->tok, history, turn_text, g, &st, cb); } apply_stop_words(text, stops); json fin = { {"model", model}, {"created_at", now_iso8601()}, {"message", {{"role", "assistant"}, {"content", text}}}, {"done", true}, {"done_reason", ollama_done_reason(st.stop_reason)}, {"total_duration", st.prefill_ns + st.gen_ns}, {"load_duration", 0}, {"prompt_eval_count", st.prompt_tokens}, {"prompt_eval_duration", st.prefill_ns}, {"eval_count", st.n_tokens()}, {"eval_duration", st.gen_ns} }; std::lock_guard lk(sb->m); sb->final_json = jdump(fin) + "\n"; }; if (stream) { start_stream(res, std::make_shared(), producer); return; } auto sb = std::make_shared(); producer(sb); res.set_content(sb->final_json.empty() ? jdump(err_json("generation failed")) : sb->final_json, "application/json"); } // --- /api/embed, /api/embeddings ------------------------------------------- void h_embed(const httplib::Request& req, httplib::Response& res) { json body; try { body = req.body.empty() ? json::object() : json::parse(req.body); } catch (...) { res.status = 400; res.set_content(jdump(err_json("invalid json")), "application/json"); return; } // "model" обязан быть строкой: раньше не-строка молча превращалась в пустое // имя, и запрос уходил на модель по умолчанию вместо честного 400. std::string model_name; bool model_type_ok = true; jstr_checked(body, "model", model_name, model_type_ok); if (!model_type_ok) { res.status = 400; res.set_content(jdump(err_json("\"model\" must be a string")), "application/json"); return; } std::string err; ModelRef m = acquire(model_name, err); if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; } std::vector inputs; if (body.contains("input")) { if (body["input"].is_string()) inputs.push_back(body["input"].get()); else if (body["input"].is_array()) for (auto& x : body["input"]) if (x.is_string()) inputs.push_back(x.get()); } if (inputs.empty() && body.contains("prompt") && body["prompt"].is_string()) inputs.push_back(body["prompt"].get()); if (inputs.empty()) { res.status = 400; res.set_content(jdump(err_json("\"input\" (string or array) required")), "application/json"); return; } const Params& p = m.ck->params; const int d = p.cfg.n_embd; json embeddings = json::array(); json tokens_used = json::array(); for (const auto& text : inputs) { std::vector ids = m.ck->tok.encode(text, false); while (!ids.empty() && ids.back() == m.ck->tok.eos) ids.pop_back(); std::vector acc((size_t)d, 0.0f); for (int id : ids) { if (id < 0 || id >= p.wte.R()) continue; const float* row = p.wte.row(id); for (int j = 0; j < d; ++j) acc[(size_t)j] += row[j]; } const float n = ids.empty() ? 1.0f : (float)ids.size(); for (auto& x : acc) x /= n; double sq = 0; for (float x : acc) sq += (double)x * x; const float inv = sq > 0 ? (float)(1.0 / std::sqrt(sq)) : 0.0f; for (auto& x : acc) x *= inv; embeddings.push_back(acc); tokens_used.push_back((int)ids.size()); } if (req.path == "/api/embeddings") { // старый формат Ollama res.set_content(jdump(json{{"embedding", embeddings.empty() ? json::array() : embeddings[0]}}), "application/json"); return; } res.set_content(jdump(json{ {"model", display_name(m.name)}, {"embeddings", embeddings}, {"total_duration", 0}, {"load_duration", 0}, {"prompt_eval_count", tokens_used} }), "application/json"); } // --- служебные ------------------------------------------------------------- void h_root(const httplib::Request&, httplib::Response& res) { std::string list; size_t n = 0; { std::lock_guard lk(g_registry_mtx); n = g_models.size(); for (auto& kv : g_models) list += " " + display_name(kv.second.name) + " -> " + kv.second.path + (kv.second.ck ? " [loaded]" : "") + "\n"; } res.set_content( std::string("Xenith ") + g_version + (g_commit.empty() ? "" : (" (" + g_commit + ")")) + " — Ollama-compatible API\n\n" "GET /api/version /api/tags /api/ps /health\n" "POST /api/show /api/create /api/delete\n" "POST /api/generate /api/chat /api/embed /api/embeddings\n" "501 /api/pull /api/push /api/blobs/:digest (реестра моделей нет)\n\n" "models (" + std::to_string(n) + "):\n" + (list.empty() ? " (пусто — положи .xnh в models/ или сделай POST /api/create)\n" : list), "text/plain; charset=utf-8"); } void logger(const httplib::Request& req, const httplib::Response& res) { if (!g_verbose) return; fprintf(stderr, "[ollama] %s %s -> %d\n", req.method.c_str(), req.path.c_str(), res.status); } } // namespace // =========================================================================== int run_ollama_server(const OllamaOptions& opt_in) { OllamaOptions opt = opt_in; // Базовые настройки уже проставлены из config.yaml в cmd_ollama(); там же // учтены флаги командной строки. Здесь НЕЛЬЗЯ сравнивать значения с // «магическими» 127.0.0.1/11434: при server.host: 0.0.0.0 явный // `--host 127.0.0.1` молча превращался в 0.0.0.0 (слушать все интерфейсы). const ServerSettings& ss = opt.cfg.server; g_version = opt.cfg.version; g_commit = opt.cfg.commit; g_build_type = opt.cfg.build_type; g_api_key = ss.api_key; g_cors = ss.cors; std::vector> found(ss.models); if (!opt.conf.empty()) { if (!parse_conf(opt.conf, opt, found)) { fprintf(stderr, "ollama: не читается конфиг %s\n", opt.conf.c_str()); return 1; } // --conf может задать ключ и CORS; берём их ПОСЛЕ разбора конфига. g_api_key = opt.api_key.empty() ? ss.api_key : opt.api_key; g_cors = opt.cors; fprintf(stderr, "ollama: конфиг %s\n", opt.conf.c_str()); } if (opt.port <= 0 || opt.port > 65535) { fprintf(stderr, "ollama: некорректный порт %d (нужно 1..65535)\n", opt.port); return 1; } if (opt.scan_models_dir) scan_models_dir(found, ss.models_dir); g_verbose = opt.verbose; { std::lock_guard lk(g_registry_mtx); for (auto& m : found) { Entry& e = g_models[strip_tag(m.first)]; e.name = strip_tag(m.first); e.path = m.second; } g_default = strip_tag(opt.default_model); if (g_default.empty() && !g_models.empty()) g_default = g_models.begin()->first; } if (g_models.empty()) fprintf(stderr, "ollama: моделей не найдено. Положи .xnh в ./models/ или задай --conf\n"); httplib::Server svr; svr.set_logger(logger); if (g_cors) { svr.set_post_routing_handler([](const httplib::Request&, httplib::Response& res) { res.set_header("Access-Control-Allow-Origin", "*"); res.set_header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"); res.set_header("Access-Control-Allow-Headers", "Content-Type, Authorization"); }); } // Авторизация: если в config.yaml задан server.api_key, требуем // "Authorization: Bearer <ключ>". Пустой ключ = доступ без авторизации. if (!g_api_key.empty()) { svr.set_pre_routing_handler([](const httplib::Request& req, httplib::Response& res) { // OPTIONS (CORS preflight) и /health (liveness/readiness для // балансировщика) доступны без ключа — так же работает Ollama. if (req.method == "OPTIONS") return httplib::Server::HandlerResponse::Unhandled; if (req.path == "/health") return httplib::Server::HandlerResponse::Unhandled; const std::string want = "Bearer " + g_api_key; auto it = req.headers.find("Authorization"); if (it == req.headers.end() || it->second != want) { res.status = 401; res.set_content("{\"error\":\"unauthorized: нужен заголовок Authorization: Bearer \"}", "application/json"); return httplib::Server::HandlerResponse::Handled; } return httplib::Server::HandlerResponse::Unhandled; }); } // в cpp-httplib 0.57.1 метод называется set_payload_max_length svr.set_payload_max_length(opt.cfg.server.max_body_kb * 1024); if (opt.cfg.server.request_timeout_sec > 0) svr.set_read_timeout((size_t)opt.cfg.server.request_timeout_sec, 0); svr.Get ("/api/version", h_version); svr.Get ("/api/tags", h_tags); svr.Get ("/api/ps", h_ps); svr.Post("/api/show", h_show); svr.Post("/api/create", h_create); svr.Post("/api/delete", h_delete); svr.Post("/api/pull", h_not_implemented); svr.Post("/api/push", h_not_implemented); svr.Post("/api/generate", h_generate); svr.Post("/api/chat", h_chat); svr.Post("/api/embed", h_embed); svr.Post("/api/embeddings", h_embed); svr.Get (R"(/api/blobs/(.+))", h_not_implemented); svr.Get ("/", h_root); svr.Get ("/health", h_health); svr.Options(R"(/api/.*)", [](const httplib::Request&, httplib::Response& res) { res.status = 204; }); svr.Options("/", [](const httplib::Request&, httplib::Response& res) { res.status = 204; }); fprintf(stderr, "Xenith %s%s%s Ollama API: %shttp://%s:%d%s\n", col::bold(), g_version.c_str(), col::reset(), col::cyan(), opt.host.c_str(), opt.port, col::reset()); fprintf(stderr, " моделей в реестре : %zu%s\n", g_models.size(), g_default.empty() ? "" : (" (по умолчанию: " + g_default + ")").c_str()); fprintf(stderr, " бэкенд : %s (%s)\n", backend_name(), backend()->describe().c_str()); fprintf(stderr, " авторизация : %s\n", g_api_key.empty() ? "выключена" : "Bearer-токен обязателен"); fprintf(stderr, " проверка : curl http://%s:%d/api/tags\n", opt.host.c_str(), opt.port); if (!svr.listen(opt.host, opt.port)) { fprintf(stderr, "ollama: не удалось занять %s:%d\n", opt.host.c_str(), opt.port); return 1; } return 0; } } // namespace xt