"""Менеджер движков Xenith Studio. Совместим с прежним API XenithEngine (chat/generate/load_model/...), но внутри выбирает адаптер: Xenith native, Ollama или OpenAI-совместимый. """ import os import threading from . import config as app_config from .engines.base import EngineError, normalize_messages, normalize_params from .engines.native import XenithAdapter from .engines.openai_compat import OpenAICompatAdapter from .engines.ollama import OllamaAdapter from .engine_runtime import EngineRuntime from .state import AppState ADAPTER_TYPES = { "xenith": XenithAdapter, "ollama": OllamaAdapter, "openai": OpenAICompatAdapter, } class XenithEngine: def __init__(self, state: AppState = None): self.app_state = state self.state = state self.config = app_config.load() self._adapters = {} self._active_id = None self.backend_info = "" self._apply_xenith_backend() self._lock = threading.Lock() self._busy = False self._training = False self.last_error = "" self.runtime = EngineRuntime() self._build_adapters() self.set_active_engine(self.config.get("active_engine") or "xenith", persist=False) def _apply_xenith_backend(self): mode = str(self.config.get("xenith_backend") or "auto").lower() try: import xenith_engine as xe except Exception: self.backend_info = "xenith_engine недоступен" return try: if mode == "cpu": xe.use_cpu() self.backend_info = "CPU" elif mode == "vulkan": r = xe.init_vulkan() if hasattr(xe, "init_vulkan") else {"ok": False, "error": "нет init_vulkan"} if isinstance(r, dict) and r.get("ok"): self.backend_info = "Vulkan" else: xe.use_cpu() self.backend_info = "CPU (Vulkan недоступен)" else: if getattr(xe, "vulkan_available", lambda: False)(): r = xe.init_vulkan() if hasattr(xe, "init_vulkan") else {"ok": False} if isinstance(r, dict) and r.get("ok"): self.backend_info = "Vulkan" else: xe.use_cpu() self.backend_info = "CPU" else: xe.use_cpu() self.backend_info = "CPU" self.log(f"Бэкенд Xenith: {self.backend_info}") except Exception as e: try: xe.use_cpu() except Exception: pass self.backend_info = f"CPU (ошибка: {e})" self.log(f"Бэкенд Xenith: {self.backend_info}") def set_backend(self, mode: str) -> bool: mode = str(mode or "auto").lower() if mode not in ("auto", "cpu", "vulkan"): raise EngineError("Неизвестный бэкенд") if self._busy or self._training: raise EngineError("Сначала дождитесь завершения генерации/обучения") self.config["xenith_backend"] = mode self.save_config() self._apply_xenith_backend() return True def backend_name(self) -> str: return self.backend_info # ---------- конфиг и адаптеры ---------- def _build_adapters(self): self._adapters = {} engines = self.config.get("engines") or {} for eid, conf in engines.items(): if not isinstance(conf, dict): continue typ = str(conf.get("type") or "") cls = ADAPTER_TYPES.get(typ) if cls is None: continue try: self._adapters[eid] = cls(eid, conf, self.app_state) except Exception as e: self.log(f"Не удалось создать движок {eid}: {e}") if "xenith" not in self._adapters: conf = {"type": "xenith", "name": "Xenith (локальный)", "enabled": True} self._adapters["xenith"] = XenithAdapter("xenith", conf, self.app_state) self.config.setdefault("engines", {})["xenith"] = conf def save_config(self): app_config.save(self.config) def engines(self): out = [] for eid, ad in self._adapters.items(): conf = (self.config.get("engines") or {}).get(eid, {}) out.append({ "id": eid, "name": ad.name, "type": ad.type, "enabled": bool(conf.get("enabled", True)), "active": eid == self._active_id, "describe": ad.describe(), "variant": conf.get("variant") or conf.get("backend_variant") or "", }) return out def get_engine(self, engine_id: str): return self._adapters.get(str(engine_id)) def active(self): return self._adapters.get(self._active_id) @property def active_id(self) -> str: return self._active_id or "" def active_name(self) -> str: ad = self.active() return ad.name if ad else "—" def set_active_engine(self, engine_id: str, persist: bool = True) -> bool: engine_id = str(engine_id or "") ad = self._adapters.get(engine_id) if ad is None: # fallback на Xenith engine_id = "xenith" ad = self._adapters.get("xenith") if ad is None: return False self._active_id = engine_id self.config["active_engine"] = engine_id for key, other in (self.config.get("engines") or {}).items(): if isinstance(other, dict): other["active"] = key == engine_id conf = (self.config.get("engines") or {}).get(engine_id, {}) conf["active"] = True if self.app_state is not None: self.app_state.current_engine_id = engine_id self.app_state.current_engine_name = ad.name if ad.type == "xenith": model = getattr(ad, "model", None) if model is not None: path = str(getattr(model, "path", "") or "") self.app_state.model_loaded = True self.app_state.current_model_path = path self.app_state.current_model_name = (os.path.basename(path) or "Модель Xenith") else: self.app_state.model_loaded = False self.app_state.current_model_name = "" self.app_state.current_model_path = "" else: # Удалённый движок не имеет локального файла модели. conf = (self.config.get("engines") or {}).get(engine_id) or {} alive = True if conf.get("installer_id"): try: alive = self.runtime.is_running(engine_id) except Exception: alive = False if ad.model_id and alive: self.app_state.model_loaded = True self.app_state.current_model_name = ad.model_id self.app_state.current_model_path = str(conf.get("model_path") or "") else: self.app_state.model_loaded = False self.app_state.current_model_name = "" self.app_state.current_model_path = "" if persist: self.save_config() self.log(f"Активный движок: {ad.name}") return True def upsert_engine(self, engine_id: str, conf: dict) -> bool: engine_id = str(engine_id or "").strip() if not engine_id: return False typ = str((conf or {}).get("type") or "") cls = ADAPTER_TYPES.get(typ) if cls is None: raise EngineError(f"Неизвестный тип движка: {typ}") self.config.setdefault("engines", {})[engine_id] = dict(conf) try: self._adapters[engine_id] = cls(engine_id, dict(conf), self.app_state) except Exception as e: raise EngineError(str(e)) self.save_config() self.log(f"Сохранён движок {engine_id} ({typ})") return True def remove_engine(self, engine_id: str) -> bool: if engine_id == "xenith": return False self._adapters.pop(engine_id, None) (self.config.get("engines") or {}).pop(engine_id, None) if self._active_id == engine_id: self.set_active_engine("xenith") self.save_config() return True def test_engine(self, engine_id: str): ad = self.get_engine(engine_id) if ad is None: return False, "Движок не найден" try: return ad.health() except Exception as e: return False, str(e) # ---------- статус ---------- def is_ready(self) -> bool: return self.active() is not None def is_busy(self) -> bool: return self._busy def is_training(self) -> bool: return self._training def set_training(self, value: bool): self._training = bool(value) def capabilities(self): ad = self.active() return ad.capabilities() if ad else None def can_train(self) -> bool: caps = self.capabilities() return bool(caps and caps.train) @property def model(self): ad = self.active() if ad is not None and ad.type == "xenith": return getattr(ad, "model", None) return None def native_model(self): ad = self._adapters.get("xenith") return getattr(ad, "model", None) if ad else None def set_native_model(self, model): """Подставить модель, созданную/обученную в памяти, в нативный адаптер.""" ad = self._adapters.get("xenith") if ad is None: return ad._model = model try: path = getattr(model, "path", "") or "" except Exception: path = "" ad.model_id = path if self.app_state is not None: self.app_state.model_loaded = True if path: self.app_state.current_model_path = path self.app_state.current_model_name = os.path.basename(path) self.app_state.current_engine_id = "xenith" self.app_state.current_engine_name = ad.name def version(self) -> str: ad = self.active() if ad is None: return "" try: return ad.version() except Exception: return "" def build_type(self) -> str: return "" def describe(self) -> str: ad = self.active() return ad.describe() if ad else "—" def info(self) -> dict: ad = self.active() if ad is None: return {} out = { "engine_id": ad.id, "engine_type": ad.type, "engine_name": ad.name, "engine_version": ad.version(), "model_id": ad.model_id, "busy": self._busy, "training": self._training, "backend": self.backend_info, } m = self.model if m is not None and hasattr(m, "info"): try: out["model_info"] = m.info() except Exception: pass return out def log(self, msg: str): if self.app_state is not None: self.app_state.log(f"[ENGINE] {msg}") else: print(f"[ENGINE] {msg}") # ---------- модели ---------- def list_models(self, engine_id: str = None): ad = self.get_engine(engine_id) if engine_id else self.active() if ad is None: raise EngineError("Движок не выбран") return ad.list_models() def models_by_engine(self): out = {} for eid, ad in self._adapters.items(): try: out[eid] = ad.list_models() except Exception as e: out[eid] = e return out def scan_models(self, extra_paths=None): """Совместимость: локальные файлы нативного движка.""" ad = self._adapters.get("xenith") if ad is None: return [] try: return [m.path for m in ad.list_models() if m.path] except Exception: return [] def load_model(self, model_id: str, on_done=None, engine_id: str = None): ad = self.get_engine(engine_id) if engine_id else self.active() if ad is None: self._set_error("Движок не выбран") if on_done: on_done() return def task(): try: self.log(f"Загрузка модели: {model_id} ({ad.name})") ad.load_model(model_id) if ad.type != "xenith": try: (self.config.setdefault("engines", {}) .setdefault(ad.id, {}))["model"] = ad.model_id self.save_config() except Exception: pass if self.app_state is not None: self.app_state.model_loaded = True if ad.type == "xenith": self.app_state.current_model_name = os.path.basename(str(model_id)) self.app_state.current_model_path = str(model_id) else: self.app_state.current_model_name = ad.model_id or str(model_id) self.app_state.current_model_path = "" self.app_state.current_engine_id = ad.id self.app_state.current_engine_name = ad.name self.log("Модель загружена") except Exception as e: self._set_error(str(e)) self.log(f"Ошибка загрузки: {e}") if self.app_state is not None: self.app_state.model_loaded = False finally: if on_done: try: on_done() except Exception: pass threading.Thread(target=task, daemon=True).start() def load_engine_model(self, engine_id: str, model_id: str, on_done=None): self.load_model(model_id, on_done=on_done, engine_id=engine_id) def _set_error(self, msg: str): self.last_error = str(msg) # ---------- чат/генерация ---------- def _prepare_messages(self, messages, ad): msgs = normalize_messages(messages) if ad.type != "xenith" and self.app_state is not None: system = getattr(self.app_state, "system_prompt", "") or "" if system and not any(m.get("role") == "system" for m in msgs): msgs = [{"role": "system", "content": system}] + msgs return msgs def _run_async(self, kind: str, fn, on_result, prompt_for_log: str, params: dict, on_token=None): if on_result is None: on_result = lambda _t: None with self._lock: if self._busy: on_result("[ОШИБКА] Движок занят другой операцией") return self._busy = True def task(): text = "" err = "" try: text = fn() self.log(f"{kind}: готово ({len(text)} символов)") except Exception as e: err = str(e) text = f"[ОШИБКА] {err}" self.log(f"{kind}: {err}") finally: self._busy = False if self.app_state is not None: try: self.app_state.add_interaction( kind, input_text=prompt_for_log, output_text=text, params=params, ok=not err, error=err, meta={"engine": self.active_name(), "model": getattr(self.app_state, "current_model_name", "")}, ) except Exception: pass try: on_result(text) except Exception: pass threading.Thread(target=task, daemon=True).start() def chat(self, messages, params: dict = None, on_result=None, on_token=None): ad = self.active() if ad is None: if on_result: on_result("[ОШИБКА] Движок не выбран") return p = normalize_params(params) msgs = self._prepare_messages(messages, ad) log_prompt = "" for m in reversed(msgs): if m.get("role") == "user": log_prompt = m.get("content", "") break def fn(): return ad.chat(msgs, p, on_token=on_token) self._run_async("chat", fn, on_result, log_prompt, p, on_token) def generate(self, prompt: str, params: dict = None, on_result=None, on_token=None): ad = self.active() if ad is None: if on_result: on_result("[ОШИБКА] Движок не выбран") return p = normalize_params(params) def fn(): return ad.generate(str(prompt), p, on_token=on_token) self._run_async("generate", fn, on_result, str(prompt), p, on_token) def generate_sync(self, prompt: str, params: dict = None) -> str: ad = self.active() if ad is None: raise EngineError("Движок не выбран") with self._lock: if self._busy or self._training: raise EngineError("Движок занят другой операцией") self._busy = True try: p = normalize_params(params) return ad.generate(str(prompt), p) finally: with self._lock: self._busy = False def reasoning_text(self) -> str: """Рассуждение последнего ответа активного движка (если есть).""" ad = self.active() try: return str(getattr(ad, "last_reasoning", "") or "") except Exception: return "" def chat_tools_sync(self, messages, tools, params: dict = None) -> dict: """Один шаг агента с нативными tools. Возвращает content + tool_calls.""" ad = self.active() if ad is None: raise EngineError("Движок не выбран") fn = getattr(ad, "chat_tools", None) if fn is None: raise EngineError(f"Движок {ad.name} не поддерживает tools") with self._lock: if self._busy or self._training: raise EngineError("Движок занят другой операцией") self._busy = True try: return fn(messages, tools, normalize_params(params)) finally: with self._lock: self._busy = False def chat_sync(self, messages, params: dict = None, on_token=None) -> str: """Синхронный чат для HTTP API/сервера. Сериализует доступ к движку.""" ad = self.active() if ad is None: raise EngineError("Движок не выбран") with self._lock: if self._busy or self._training: raise EngineError("Движок занят другой операцией") self._busy = True try: p = normalize_params(params) msgs = self._prepare_messages(messages, ad) return ad.chat(msgs, p, on_token=on_token) finally: with self._lock: self._busy = False def stop(self): ad = self.active() if ad is not None: try: ad.stop() except Exception: pass def unload_model(self, engine_id: str = None) -> bool: """Выгружает модель из активного или указанного движка.""" eid = str(engine_id or self._active_id or "") ad = self._adapters.get(eid) if ad is None: return False if self._busy or self._training: raise EngineError("Сначала дождитесь завершения генерации/обучения") try: ad.stop() except Exception: pass try: ad.unload_model() except Exception as e: self.log(f"Не удалось выгрузить модель {ad.name}: {e}") conf = (self.config.get("engines") or {}).get(eid) if isinstance(conf, dict): conf.pop("model", None) # llama.cpp-сервер держит веса в памяти: останавливаем его, # чтобы действительно освободить VRAM/RAM. if ad.type == "openai" and conf.get("installer_id"): try: self.runtime.stop(eid, timeout=4) except Exception: pass if self.app_state is not None and eid == self._active_id: self.app_state.model_loaded = False self.app_state.current_model_name = "" self.app_state.current_model_path = "" try: self.save_config() except Exception: pass self.log(f"Модель выгружена: {ad.name}") return True def reset_chat(self): ad = self.active() if ad is not None: try: ad.reset_chat() except Exception: pass def set_system_prompt(self, prompt: str): ad = self.active() if ad is not None: try: ad.set_system_prompt(prompt or "") except Exception: pass def context_info(self): ad = self.active() if ad is None: return None, None, True try: return ad.context_info() except Exception: return None, None, True