Files
Xenith/xenith/ollama_api/handler.cpp
T
2026-10-14 02:37:20 +07:00

856 lines
37 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// handler.cpp — реализация Ollama-совместимого HTTP-сервера для Xenith.
//
// Особенности реализации:
// * ядро Xenith однопоточное и НЕ потокобезопасное (общий ForwardCache,
// статические буферы в sample()), поэтому генерация сериализована g_gen_mtx;
// * модели хранятся в shared_ptr<const Checkpoint> — снимок на запрос стоит
// копейки, а гонки при удалении модели невозможны;
// * стриминг НАСТОЯЩИЙ: контент-провайдер 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/generate.h"
#include "../core/model.h"
#include <atomic>
#include <cctype>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <exception>
#include <filesystem>
#include <fstream>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#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 {
constexpr const char* XENITH_VERSION = "0.0.4";
constexpr const char* CREATED_AT = "1970-01-01T00:00:00Z";
// ---------------------------------------------------------------------------
// Реестр моделей
// ---------------------------------------------------------------------------
struct Entry {
std::string name;
std::string path;
std::shared_ptr<const Checkpoint> ck; // nullptr, пока не загружена
std::string load_err;
};
std::map<std::string, Entry> 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;
}
std::string digest_of(const std::string& path) {
char buf[32];
snprintf(buf, sizeof buf, "%016zx", std::hash<std::string>{}(path));
return buf;
}
// ---------------------------------------------------------------------------
// Конфиг
// ---------------------------------------------------------------------------
bool parse_conf(const std::string& path, OllamaOptions& opt,
std::vector<std::pair<std::string,std::string>>& 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);
if (j.contains("host") && j["host"].is_string()) opt.host = j["host"].get<std::string>();
if (j.contains("port") && j["port"].is_number_integer()) opt.port = j["port"].get<int>();
if (j.contains("default_model") && j["default_model"].is_string()) opt.default_model = j["default_model"].get<std::string>();
if (j.contains("verbose") && j["verbose"].is_boolean()) opt.verbose = j["verbose"].get<bool>();
if (j.contains("scan_models_dir") && j["scan_models_dir"].is_boolean()) opt.scan_models_dir = j["scan_models_dir"].get<bool>();
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.host = v;
else if (k == "port") opt.port = std::atoi(v.c_str());
else if (k == "default_model") opt.default_model = v;
else if (k == "verbose") opt.verbose = (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<std::pair<std::string,std::string>>& models) {
std::error_code ec;
if (!fs::is_directory("models", ec)) return;
for (const auto& e : fs::directory_iterator("models", ec)) {
if (!e.is_regular_file() || e.path().extension() != ".xnh") 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<const Checkpoint> ck;
std::string name; // имя без тега
std::string path;
bool valid = false;
};
ModelRef acquire(const std::string& wanted, std::string& err) {
ModelRef out;
std::lock_guard<std::mutex> 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("<default>") : wanted) + "' not found";
return out;
}
}
Entry& e = it->second;
if (!e.ck) {
auto ck = std::make_shared<Checkpoint>();
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<bool>() : 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<std::string>() : def;
}
// значение из тела запроса ИЛИ из вложенного "options" (у Ollama настройки там)
template <typename T> T jopt(const json& j, const char* k, T def);
template <> int jopt<int>(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<int>();
if (j.contains(k) && j[k].is_number()) return j[k].get<int>();
return def;
}
template <> float jopt<float>(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<double>();
if (j.contains(k) && j[k].is_number()) return (float)j[k].get<double>();
return def;
}
template <> bool jopt<bool>(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<bool>();
if (j.contains(k) && j[k].is_boolean()) return j[k].get<bool>();
return def;
}
GenConfig build_gen_config(const json& j) {
GenConfig gc;
gc.max_new_tokens = jopt<int>(j, "num_predict", 256);
if (gc.max_new_tokens <= 0) gc.max_new_tokens = 1 << 20; // -1 у Ollama = без лимита
if (gc.max_new_tokens > (1 << 20)) gc.max_new_tokens = 1 << 20;
gc.temperature = jopt<float>(j, "temperature", 0.8f);
gc.top_k = jopt<int>(j, "top_k", 40);
gc.top_p = jopt<float>(j, "top_p", 0.95f);
gc.repeat_penalty = jopt<float>(j, "repeat_penalty", 1.0f);
gc.seed = jopt<int>(j, "seed", -1);
gc.stream = false; // стримингом занимается сервер
return gc;
}
// "stop" бывает строкой или массивом строк
std::vector<std::string> build_stop(const json& j) {
std::vector<std::string> 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<std::string>());
else if (s->is_array()) for (auto& e : *s) if (e.is_string()) out.push_back(e.get<std::string>());
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<std::string>& 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", CREATED_AT},
{"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<std::string> q;
bool done = false;
std::string final_json;
std::atomic<bool> cancel{false};
std::chrono::steady_clock::time_point last_pull = std::chrono::steady_clock::now();
};
void start_stream(httplib::Response& res, std::shared_ptr<StreamBuf> sb,
std::function<void(std::shared_ptr<StreamBuf>)> producer) {
std::thread([sb, producer]() {
try { producer(sb); }
catch (...) {
std::lock_guard<std::mutex> lk(sb->m);
sb->final_json = jdump(err_json("internal error during generation"));
}
{ std::lock_guard<std::mutex> 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<std::mutex> 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", XENITH_VERSION}}), "application/json");
}
void h_health(const httplib::Request&, httplib::Response& res) {
res.set_content(jdump(json{{"status", "ok"}, {"version", XENITH_VERSION}}), "application/json");
}
void h_tags(const httplib::Request&, httplib::Response& res) {
std::lock_guard<std::mutex> 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<std::mutex> 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", CREATED_AT}, {"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; }
std::string err;
ModelRef m = acquire(jstr(body, "model"), 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"] = "<bos><user>{{ .Prompt }}<assistant>";
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 <path-to-.xnh>' and that file must exist")),
"application/json");
return;
}
{
std::lock_guard<std::mutex> 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<std::mutex> 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; }
std::string err;
ModelRef m = acquire(jstr(body, "model"), err);
if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; }
const std::string prompt = jstr(body, "prompt");
const bool stream = jbool(body, "stream", true);
const bool raw = jbool(body, "raw", false);
const GenConfig gc = build_gen_config(body);
const std::vector<std::string> stops = build_stop(body);
auto producer = [m, prompt, gc, stops, raw](std::shared_ptr<StreamBuf> sb) {
std::lock_guard<std::mutex> gen_lk(g_gen_mtx);
const std::string model = display_name(m.name);
GenConfig g = gc;
g.cancel = &sb->cancel;
std::vector<int> 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<std::mutex> lk(sb->m);
sb->q.push_back(jdump(json{{"model", model}, {"created_at", CREATED_AT},
{"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", CREATED_AT},
{"response", text}, {"done", true}, {"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<std::mutex> lk(sb->m);
sb->final_json = jdump(fin) + "\n";
};
if (stream) { start_stream(res, std::make_shared<StreamBuf>(), producer); return; }
// --- нестриминговый путь: считаем синхронно ---
auto sb = std::make_shared<StreamBuf>();
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; }
std::string err;
ModelRef m = acquire(jstr(body, "model"), 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 <user>/<assistant> 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<std::string> stops = build_stop(body);
// Разбираем messages. Отдельного токена <system> в словаре Xenith нет,
// поэтому системный промпт приклеивается к последней user-реплике.
std::string system_text, last_user;
std::vector<std::pair<std::string,std::string>> prior;
for (const auto& msg : body["messages"]) {
if (!msg.is_object()) continue;
std::string role = msg.value("role", "");
const std::string text = msg.value("content", "");
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<StreamBuf> sb) {
std::lock_guard<std::mutex> 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<int> 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<std::mutex> lk(sb->m);
sb->q.push_back(jdump(json{{"model", model}, {"created_at", CREATED_AT},
{"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", CREATED_AT},
{"message", {{"role", "assistant"}, {"content", text}}},
{"done", true}, {"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<std::mutex> lk(sb->m);
sb->final_json = jdump(fin) + "\n";
};
if (stream) { start_stream(res, std::make_shared<StreamBuf>(), producer); return; }
auto sb = std::make_shared<StreamBuf>();
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; }
std::string err;
ModelRef m = acquire(jstr(body, "model"), err);
if (!m.valid) { res.status = 404; res.set_content(jdump(err_json(err)), "application/json"); return; }
std::vector<std::string> inputs;
if (body.contains("input")) {
if (body["input"].is_string()) inputs.push_back(body["input"].get<std::string>());
else if (body["input"].is_array())
for (auto& x : body["input"]) if (x.is_string()) inputs.push_back(x.get<std::string>());
}
if (inputs.empty() && body.contains("prompt") && body["prompt"].is_string())
inputs.push_back(body["prompt"].get<std::string>());
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<int> ids = m.ck->tok.encode(text, false);
while (!ids.empty() && ids.back() == m.ck->tok.eos) ids.pop_back();
std::vector<float> 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<std::mutex> 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 ") + XENITH_VERSION + " — 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;
std::vector<std::pair<std::string,std::string>> found;
if (!opt.conf.empty()) {
if (!parse_conf(opt.conf, opt, found)) {
fprintf(stderr, "ollama: не читается конфиг %s\n", opt.conf.c_str());
return 1;
}
fprintf(stderr, "ollama: конфиг %s\n", opt.conf.c_str());
}
if (opt.scan_models_dir) scan_models_dir(found);
g_verbose = opt.verbose;
{
std::lock_guard<std::mutex> 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);
svr.set_payload_max_length(64 * 1024 * 1024); // в 0.57.1 метод называется именно так
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);
fprintf(stderr, "Xenith Ollama API: http://%s:%d (моделей: %zu, по умолчанию: %s)\n",
opt.host.c_str(), opt.port, g_models.size(),
g_default.empty() ? "<нет>" : g_default.c_str());
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