"""The two LLM servers: how to start and stop each one, and how to watch it. Both monitors report the same shape, so the web UI shows either one the same way: model: {"state": offline|unloaded|loading|idle|sleeping|reading|generating|failed, "detail", "id", "context"} live: the request in progress: {"phase", "progress", "read", "total", "generated", "tok_s", "elapsed"} requests: the latest finished requests, newest first averages: prompt-reading and generation speed over those requests Polling never wakes a model: Strata's /health and /metrics and llama-server's /models and /metrics don't count as use. llama's live progress comes from its log, because polling /slots would reset its idle timer. """ from __future__ import annotations import collections import ctypes import ctypes.wintypes as wt import json import logging import os import re import threading import time import urllib.error import urllib.request from datetime import datetime from kurgan import paths from kurgan.ai import config log = logging.getLogger(__name__) LOG_DIR = os.path.join(paths.DATA_DIR, "logs") KEEP_REQUESTS = 20 _k32 = ctypes.WinDLL("kernel32", use_last_error=True) _k32.OpenEventW.argtypes, _k32.OpenEventW.restype = [wt.DWORD, wt.BOOL, wt.LPCWSTR], wt.HANDLE _k32.SetEvent.argtypes, _k32.SetEvent.restype = [wt.HANDLE], wt.BOOL _k32.CloseHandle.argtypes = [wt.HANDLE] EVENT_MODIFY_STATE = 0x2 def http(method: str, url: str, body: dict | None = None, headers: dict | None = None, timeout: float = 3) -> tuple[int, bytes]: data = None if body is None else json.dumps(body).encode() request = urllib.request.Request(url, data=data, method=method, headers={ **({"Content-Type": "application/json"} if body is not None else {}), **(headers or {})}) try: with urllib.request.urlopen(request, timeout=timeout) as response: return response.status, response.read() except urllib.error.HTTPError as e: return e.code, e.read() def _clock(epoch: float | None) -> str | None: return None if epoch is None else datetime.fromtimestamp(epoch).strftime("%H:%M:%S") def _rate(tokens: float, ms: float) -> float | None: return round(tokens / ms * 1000, 1) if ms and tokens else None class Backend: key = "" # also its path on The Kurgan's web server: // label = "" stop_timeout = 10.0 def __init__(self, settings): self.settings = settings self.lock = threading.Lock() self.status: dict = self.offline() self.public = "http://127.0.0.1:8080" # The Kurgan's web server; set by the service # -- configuration @property def port(self) -> int: """Where the server listens, on 127.0.0.1, behind The Kurgan.""" raise NotImplementedError @property def prefix(self) -> str: """The path the server itself serves under ("" = the root).""" return "" def proxy_headers(self) -> dict: """Headers The Kurgan's proxy sets on every request it passes to this server.""" return {} def variants(self) -> list[dict]: return [] def variant(self) -> str | None: return None def model_label(self) -> str: raise NotImplementedError def model_ids(self) -> list[str]: """The model ids its /v1/models lists (answered by The Kurgan while the server is stopped).""" raise NotImplementedError def links(self) -> dict: return {"chat": f"{self.public}/{self.key}/", "api": f"{self.public}/{self.key}/v1", "internal": f"http://127.0.0.1:{self.port}{self.prefix}/"} def check_files(self) -> str | None: """A reason it can't start (missing file), or None.""" return None # -- process def command(self) -> tuple[list[str], str, str]: """(argv, working directory, log file for stdout/stderr).""" raise NotImplementedError def before_start(self) -> None: pass def request_stop(self, child) -> None: child.kill() # -- monitoring @staticmethod def offline() -> dict: return {"model": {"state": "offline", "detail": "", "id": None, "context": None}, "live": None, "requests": [], "averages": {"prefill_tps": None, "decode_tps": None, "requests": 0}} def poll(self) -> None: raise NotImplementedError def mark_offline(self) -> None: with self.lock: self.status = self.offline() def snapshot(self) -> dict: with self.lock: return json.loads(json.dumps(self.status)) def load(self) -> None: raise NotImplementedError def unload(self) -> None: raise NotImplementedError class StrataBackend(Backend): key = "strata" label = "Strata" stop_timeout = 45.0 # Strata's own --shutdown-timeout is 30 s def __init__(self, settings): super().__init__(settings) self._stop_name: str | None = None self._starts = 0 @property def root(self) -> str: return self.settings.get("ai", "strata_root", config.STRATA_ROOT) @property def port(self) -> int: return self.settings.get("ai", "strata_port", config.STRATA_PORT) def variant(self) -> str: return self.settings.get("ai", "strata_model") def variants(self) -> list[dict]: return [{"key": k, "label": label} for k, (label, _, _) in config.STRATA_MODELS.items()] def model_label(self) -> str: return config.STRATA_MODELS[self.variant()][0] def model_ids(self) -> list[str]: return [config.STRATA_MODELS[self.variant()][2]] def _python(self) -> str: return os.path.join(self.root, "terminal", ".venv", "Scripts", "pythonw.exe") def check_files(self) -> str | None: config_file = os.path.join(self.root, "terminal", config.STRATA_MODELS[self.variant()][1]) for path in (self._python(), config_file): if not os.path.exists(path): return f"Not found: {path}" return None def command(self) -> tuple[list[str], str, str]: self._starts += 1 self._stop_name = f"Local\\KurganStrataStop-{os.getpid()}-{self._starts}" host = os.path.join(paths.PACKAGE_DIR, "ai", "strata_host.py") argv = [self._python(), host, "--root", self.root, "--config", config.STRATA_MODELS[self.variant()][1], "--port", str(self.port), "--idle-unload", str(config.STRATA_IDLE_UNLOAD), "--stop-event", self._stop_name] return argv, os.path.join(self.root, "terminal"), os.path.join(LOG_DIR, "strata-host.log") def request_stop(self, child) -> None: """Ask Strata to shut down cleanly; the service kills it if it takes too long.""" handle = _k32.OpenEventW(EVENT_MODIFY_STATE, False, self._stop_name) if self._stop_name else None if not handle: log.warning("Strata's stop event isn't available; ending it instead") child.kill() return try: _k32.SetEvent(handle) finally: _k32.CloseHandle(handle) def _url(self, path: str) -> str: return f"http://127.0.0.1:{self.port}{path}" def poll(self) -> None: code, body = http("GET", self._url("/health")) if code != 200: raise ValueError(f"/health returned HTTP {code}") health = json.loads(body) code, body = http("GET", self._url("/metrics"), headers={"Accept": "application/json"}) metrics = json.loads(body) if code == 200 else {} live_in = metrics.get("live") or {} state = live_in.get("state") or ("idle" if health.get("loaded") else "unloaded") live = None if state in ("reading", "generating"): read, total = live_in.get("prompt_read"), live_in.get("prompt_total") live = {"phase": state, "read": read, "total": total or live_in.get("prompt_tokens"), "progress": round(read / total, 3) if read is not None and total else None, "generated": live_in.get("generated"), "tok_s": live_in.get("tok_s"), "elapsed": live_in.get("elapsed_s"), "queued": live_in.get("queued")} requests = [] for r in (metrics.get("requests") or [])[:KEEP_REQUESTS]: prompt, reused = r.get("prompt_tokens") or 0, r.get("reused") or 0 requests.append({"time": _clock(r.get("time")), "status": r.get("finish") or "ok", "prompt": prompt, "reused": reused, "output": r.get("output_tokens") or 0, "prefill_tps": _rate(prompt - reused, r.get("prompt_ms") or 0), "decode_tps": r.get("decode_tok_s"), "duration": r.get("duration_s")}) totals = metrics.get("totals") or {} engine = metrics.get("engine") or {} status = { "model": {"state": state, "detail": "", "id": health.get("model"), "context": health.get("max_context"), "engine": engine.get("version")}, "live": live, "requests": requests, "averages": {"prefill_tps": _rate((totals.get("prompt_tokens") or 0) - (totals.get("reused") or 0), totals.get("prompt_ms") or 0), "decode_tps": _rate(totals.get("output_tokens") or 0, totals.get("decode_ms") or 0), "requests": totals.get("requests") or 0}, } with self.lock: self.status = status def load(self) -> None: code, body = http("POST", self._url("/load"), {}, timeout=600) log.info("Strata load: HTTP %s %s", code, body[:200]) if code != 200: raise RuntimeError(_error_text(body) or f"Strata load failed (HTTP {code})") def unload(self) -> None: code, body = http("POST", self._url("/unload"), {}, timeout=120) log.info("Strata unload: HTTP %s %s", code, body[:200]) if code == 409: raise RuntimeError("Strata is answering a request; unload it when it finishes.") if code != 200: raise RuntimeError(_error_text(body) or f"Strata unload failed (HTTP {code})") def _error_text(body: bytes) -> str | None: try: error = json.loads(body).get("error") return error.get("message") if isinstance(error, dict) else str(error) if error else None except (ValueError, AttributeError): return None # --- llama.cpp log parsing (ported from the Qwen4 service) ------------------------------- RE_START = re.compile(r"task (\d+) \| processing task") RE_PREFILL = re.compile(r"task (\d+) \| prompt processing, n_tokens =\s*(\d+), progress =\s*([\d.]+), " r"t =\s*([\d.]+) s / ([\d.]+) tokens per second") RE_GEN = re.compile(r"task (\d+) \| n_gen =\s*(\d+), tg =\s*([\d.]+) t/s, tg_3s =\s*([\d.]+) t/s") RE_PROMPT_DONE = re.compile(r"task (\d+) \| prompt eval time =\s*([\d.]+) ms /\s*(\d+) tokens.*?([\d.]+) tokens per second") RE_EVAL_DONE = re.compile(r"task (\d+) \|\s+eval time =\s*([\d.]+) ms /\s*(\d+) tokens.*?([\d.]+) tokens per second") RE_STOP = re.compile(r"task (\d+) \| stop processing: n_tokens =\s*(\d+), truncated = (\d)") class LlamaLog: """Follows llama-server's log for the request in progress and the finished ones.""" def __init__(self) -> None: self.lock = threading.Lock() self.current: dict | None = None self.requests: collections.deque[dict] = collections.deque(maxlen=KEEP_REQUESTS) def feed(self, line: str, now: float | None = None) -> None: now = time.time() if now is None else now with self.lock: if match := RE_START.search(line): self.current = {"start": now, "phase": "reading", "progress": 0.0, "read": 0, "generated": 0, "prefill_tps": None, "decode_tps": None} return current = self.current if current is None: return if match := RE_PREFILL.search(line): current.update(phase="reading", read=int(match[2]), progress=float(match[3]), prefill_tps=float(match[5])) elif match := RE_GEN.search(line): current.update(phase="generating", generated=int(match[2]), decode_tps=float(match[4])) elif match := RE_PROMPT_DONE.search(line): current.update(prompt_ms=float(match[2]), read=int(match[3]), prefill_final=float(match[4])) elif match := RE_EVAL_DONE.search(line): current.update(decode_ms=float(match[2]), generated=int(match[3]), decode_final=float(match[4])) elif match := RE_STOP.search(line): context = int(match[2]) read, generated = current.get("read", 0), current.get("generated", 0) cached = max(0, context - read - generated) self.requests.appendleft({ "time": datetime.fromtimestamp(now).strftime("%H:%M:%S"), "status": "truncated" if match[3] == "1" else "ok", "prompt": cached + read, "reused": cached, "output": generated, "prefill_tps": current.get("prefill_final"), "decode_tps": current.get("decode_final"), "duration": round(now - current["start"], 1), "prompt_ms": current.get("prompt_ms", 0.0), "decode_ms": current.get("decode_ms", 0.0), }) self.current = None def reset(self) -> None: with self.lock: self.current = None def snapshot(self) -> tuple[dict | None, list[dict], dict]: with self.lock: requests = list(self.requests) current = dict(self.current) if self.current else None live = None if current: live = {"phase": current["phase"], "progress": current.get("progress"), "read": current.get("read"), "total": None, "generated": current.get("generated"), "tok_s": current.get("decode_tps") if current["phase"] == "generating" else current.get("prefill_tps"), "elapsed": round(time.time() - current["start"], 1), "queued": None} prompt_ms = sum(r["prompt_ms"] for r in requests) decode_ms = sum(r["decode_ms"] for r in requests) averages = {"prefill_tps": _rate(sum(r["prompt"] - r["reused"] for r in requests), prompt_ms), "decode_tps": _rate(sum(r["output"] for r in requests), decode_ms), "requests": len(requests)} public = [{k: v for k, v in r.items() if k not in ("prompt_ms", "decode_ms")} for r in requests] return live, public, averages def follow(self, path_fn, stop: threading.Event) -> None: """Tail the file path_fn() returns, reopening it when it is replaced or truncated.""" handle, identity, buffer, path = None, None, b"", None while not stop.is_set(): try: wanted = path_fn() if wanted != path: if handle: handle.close() handle, identity, buffer, path = None, None, b"", wanted stat = os.stat(path) if handle is None or (stat.st_ino, stat.st_ctime_ns) != identity or stat.st_size < handle.tell(): if handle: handle.close() handle = open(path, "rb") if identity is None: handle.seek(0, os.SEEK_END) # don't replay an old log when first attaching identity, buffer = (stat.st_ino, stat.st_ctime_ns), b"" chunk = handle.read() except (OSError, TypeError): chunk = b"" if not chunk: stop.wait(0.5) continue buffer += chunk *lines, buffer = buffer.split(b"\n") for line in lines: self.feed(line.decode("utf-8", "replace")) if handle: handle.close() class LlamaBackend(Backend): key = "llama" label = "llama.cpp" stop_timeout = 10.0 LEGACY_LOG = r"D:\AI\models\qwen4-35b-a3b\service\logs\llama-server.log" # while the Qwen4 service runs it def __init__(self, settings): super().__init__(settings) self.logparser = LlamaLog() self.owned = False # set by the service: True when The Kurgan started the running server self.load_started: float | None = None self.last_load_seconds: float | None = None @property def port(self) -> int: return self.settings.get("ai", "llama_port", config.LLAMA_PORT) @property def server(self) -> str: return self.settings.get("ai", "llama_server", config.LLAMA_SERVER) @property def presets(self) -> str: return self.settings.get("ai", "llama_presets", config.LLAMA_PRESETS) @property def model(self) -> str: return self.settings.get("ai", "llama_model", config.LLAMA_MODEL) @property def prefix(self) -> str: # The Qwen4 service's own server (before it was retired) serves from the root. return config.LLAMA_PREFIX if self.owned else "" def proxy_headers(self) -> dict: # The proxy is the gate (see kurgan/web/proxy.py), so clients there need no key; the key # stays on the server's own port, where a web page could otherwise reach it. return {"Authorization": f"Bearer {config.LLAMA_API_KEY}"} def model_label(self) -> str: return config.LLAMA_LABEL if self.model == config.LLAMA_MODEL else self.model def model_ids(self) -> list[str]: return [self.model] @property def log_path(self) -> str: return os.path.join(LOG_DIR, "llama-server.log") def current_log(self) -> str: return self.log_path if self.owned else self.LEGACY_LOG def check_files(self) -> str | None: for path in (self.server, self.presets): if not os.path.exists(path): return f"Not found: {path}" return None def before_start(self) -> None: os.makedirs(LOG_DIR, exist_ok=True) try: if os.path.exists(self.log_path): os.replace(self.log_path, os.path.join(LOG_DIR, "llama-server.prev.log")) except OSError as e: log.warning("Could not rotate llama-server.log: %s", e) self.logparser.reset() def command(self) -> tuple[list[str], str, str]: argv = [self.server, "--models-preset", self.presets, "--models-max", "1", "--host", "127.0.0.1", "--port", str(self.port), "--api-prefix", config.LLAMA_PREFIX, "--api-key", config.LLAMA_API_KEY, "--metrics"] return argv, os.path.dirname(self.presets), self.log_path def _api(self, path: str, body: dict | None = None, timeout: float = 3) -> tuple[int, bytes]: return http("GET" if body is None else "POST", f"http://127.0.0.1:{self.port}{self.prefix}{path}", body, {"Authorization": f"Bearer {config.LLAMA_API_KEY}"}, timeout) def _model_entry(self) -> dict: code, body = self._api("/models") if code != 200: raise ValueError(f"/models returned HTTP {code}") return next(m for m in json.loads(body)["data"] if m["id"] == self.model) def poll(self) -> None: entry = self._model_entry() state = entry["status"]["value"] live, requests, averages = self.logparser.snapshot() if state == "loading" and self.load_started is None: self.load_started = time.time() elif state != "loading" and self.load_started is not None: if state == "loaded": self.last_load_seconds = round(time.time() - self.load_started, 1) self.load_started = None if state == "loaded": state = live["phase"] if live else "idle" else: live = None detail = entry["status"].get("failed_reason", "") if state == "failed" else "" if state == "loading" and self.load_started: detail = f"{time.time() - self.load_started:.0f} s" status = {"model": {"state": state, "detail": detail, "id": self.model, "context": 262144, "last_load_seconds": self.last_load_seconds}, "live": live, "requests": requests, "averages": averages} with self.lock: self.status = status def load(self) -> None: if self._model_entry()["status"]["value"] == "sleeping": # A sleeping instance only wakes on a task, so restart it to load immediately. self._api("/models/unload", {"model": self.model}, timeout=30) for _ in range(60): if self._model_entry()["status"]["value"] == "unloaded": break time.sleep(0.5) code, body = self._api("/models/load", {"model": self.model}, timeout=30) log.info("llama load: HTTP %s %s", code, body[:200]) if code != 200: raise RuntimeError(_error_text(body) or f"llama.cpp load failed (HTTP {code})") def unload(self) -> None: code, body = self._api("/models/unload", {"model": self.model}, timeout=30) log.info("llama unload: HTTP %s %s", code, body[:200]) if code != 200: raise RuntimeError(_error_text(body) or f"llama.cpp unload failed (HTTP {code})")