Files

144 lines
4.2 KiB
Python

"""Базовые типы движков Xenith Studio."""
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Optional
class EngineError(Exception):
"""Ошибка движка, пригодная для показа пользователю."""
@dataclass
class Capabilities:
chat: bool = True
stream: bool = False
train: bool = False
finetune: bool = False
tools: bool = False
manage_models: bool = False
context_info: bool = False
@dataclass
class ModelInfo:
engine_id: str
id: str
name: str
path: str = ""
size: int = 0
kind: str = ""
loaded: bool = False
meta: Dict = field(default_factory=dict)
def label(self) -> str:
return self.name or self.id
def normalize_params(params: Optional[dict]) -> dict:
p = dict(params or {})
n = p.get("n", p.get("max_new_tokens", p.get("max_tokens", 256)))
try:
n = int(n)
except Exception:
n = 256
p["n"] = max(1, min(n, 8192))
for key in ("temperature", "top_p"):
try:
p[key] = float(p.get(key, 0.7 if key == "temperature" else 0.9))
except Exception:
p[key] = 0.7 if key == "temperature" else 0.9
try:
p["top_k"] = int(p.get("top_k", 40))
except Exception:
p["top_k"] = 40
try:
p["repeat_penalty"] = float(p.get("repeat_penalty", 1.0))
except Exception:
p["repeat_penalty"] = 1.0
return p
def normalize_messages(messages) -> List[dict]:
if isinstance(messages, str):
return [{"role": "user", "content": messages}]
out = []
if isinstance(messages, list):
for m in messages:
if isinstance(m, dict):
role = str(m.get("role", "user"))
content = m.get("content", "")
if isinstance(content, list):
parts = []
for part in content:
if isinstance(part, dict) and part.get("type") == "text":
parts.append(str(part.get("text", "")))
elif isinstance(part, str):
parts.append(part)
content = "\n".join(parts)
out.append({"role": role, "content": "" if content is None else str(content)})
elif isinstance(m, str):
out.append({"role": "user", "content": m})
return out or [{"role": "user", "content": ""}]
class EngineAdapter:
type = "base"
def __init__(self, engine_id: str, conf: dict, app_state=None):
self.id = engine_id
self.conf = dict(conf or {})
self.app_state = app_state
self.model_id: str = str(self.conf.get("model") or "")
self._stop = False
# ---------- идентификация ----------
@property
def name(self) -> str:
return str(self.conf.get("name") or self.type)
def capabilities(self) -> Capabilities:
return Capabilities()
def version(self) -> str:
return ""
def describe(self) -> str:
return self.name
# ---------- health/models ----------
def health(self) -> tuple:
return True, "OK"
def list_models(self) -> List[ModelInfo]:
return []
def load_model(self, model_id: str) -> None:
self.model_id = str(model_id)
def unload_model(self) -> None:
self.model_id = ""
# ---------- inference ----------
def chat(self, messages, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str:
raise EngineError(f"Движок {self.name} не поддерживает чат")
def generate(self, prompt: str, params: dict, on_token: Optional[Callable[[str], None]] = None) -> str:
raise EngineError(f"Движок {self.name} не поддерживает генерацию")
def reset_chat(self) -> None:
pass
def set_system_prompt(self, text: str) -> None:
pass
def context_info(self):
"""(used, limit, estimated) или (None, None, True)."""
return None, None, True
# ---------- управление ----------
def stop(self) -> None:
self._stop = True
def close(self) -> None:
pass