"""MVPKILLCADDSS — Model Manager Load Balancer + Health Checker + Circuit Breaker a 3 private CAD modellhez""" import asyncio import time import httpx import json import os from datetime import datetime # ═══════════════ Model Registry ════════════════════════════ MODELS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "models") def load_model_configs(): configs = {} for model_id in ["cad_llm1", "cad_llm2", "cad_llm3"]: config_path = os.path.join(MODELS_DIR, model_id, "config.json") try: with open(config_path) as f: configs[model_id] = json.load(f) except Exception: configs[model_id] = { "name": model_id, "priority": 1, "port": 8001, "domains": ["altalanos"], "max_concurrent": 3 } return configs class ModelManager: def __init__(self): self.configs = load_model_configs() self.models = {} for mid, cfg in self.configs.items(): self.models[mid] = { "id": mid, "name": cfg.get("name", mid), "url": cfg.get("url", f"http://localhost:{cfg.get('port', 8001)}"), "priority": cfg.get("priority", 1), "domains": cfg.get("domains", []), "domain_names": cfg.get("domain_names", []), "max_concurrent": cfg.get("max_concurrent", 3), "weight": cfg.get("weight", 100), "hf_token": cfg.get("hf_token", os.getenv("HF_TOKEN", "")), "hf_space": cfg.get("huggingface_space", ""), # Runtime status "healthy": None, "load": 0, "concurrent": 0, "total_requests": 0, "total_failures": 0, "avg_response_time": 0, "last_response_time": 0, "last_check": None, "uptime_since": None, "consecutive_failures": 0, "circuit_broken": False, "circuit_broken_until": 0, "status": "unknown", } # ═══════ Model Selection ═══════ def select_model(self, domains: list[str]) -> tuple[str, dict] | tuple[None, None]: """Domain + terhelés + health alapján legjobb modell választása""" candidates = [] for mid, m in self.models.items(): if m["circuit_broken"] and time.time() < m["circuit_broken_until"]: continue if not m["healthy"] and m["healthy"] is not None: continue # Domain match score (how many domains overlap) overlap = set(d.lower() for d in domains) & set(d.lower() for d in m["domains"]) domain_score = len(overlap) # Load score (inverse — prefer less loaded) load_score = max(0, 100 - m["load"]) # Priority score (lower number = higher priority, so invert) priority_score = max(0, 4 - m["priority"]) if domain_score > 0 or m["priority"] == 1: candidates.append({ "id": mid, "model": m, "score": domain_score * 40 + load_score * 0.3 + priority_score * 30, }) if not candidates: # Fallback: any healthy model for mid, m in self.models.items(): if m["healthy"] and not m["circuit_broken"]: return mid, m return None, None # Sort by score descending candidates.sort(key=lambda x: x["score"], reverse=True) # Check if top candidate is overloaded top = candidates[0] if top["model"]["load"] > 80 and len(candidates) > 1: # Use second best if top is overloaded return candidates[1]["id"], candidates[1]["model"] return top["id"], top["model"] # ═══════ Request Recording ═══════ def record_request(self, model_id: str, success: bool, response_time: float): if model_id not in self.models: return m = self.models[model_id] m["total_requests"] += 1 m["last_response_time"] = response_time if success: m["consecutive_failures"] = 0 # Exponential moving average alpha = 0.3 m["avg_response_time"] = ( m["avg_response_time"] * (1 - alpha) + response_time * alpha ) else: m["total_failures"] += 1 m["consecutive_failures"] += 1 # Circuit breaker: 3 consecutive failures if m["consecutive_failures"] >= 3: m["circuit_broken"] = True m["circuit_broken_until"] = time.time() + 30 m["status"] = "circuit_broken" # ═══════ Health Check Loop ═══════ async def health_check_loop(self): """5 másodpercenként ellenőrzi mind a 3 modellt""" while True: for mid, m in self.models.items(): await self._check_one(mid); await asyncio.sleep(5) async def _check_one(self, model_id: str): m = self.models[model_id] # Check if circuit breaker should reset if m["circuit_broken"] and time.time() >= m["circuit_broken_until"]: m["circuit_broken"] = False m["consecutive_failures"] = 0 m["status"] = "recovering" try: async with httpx.AsyncClient(timeout=5) as client: resp = await client.get(f"{m['url']}/health") if resp.status_code == 200: if not m["healthy"]: m["uptime_since"] = datetime.utcnow().isoformat() m["healthy"] = True m["status"] = "healthy" m["last_check"] = datetime.utcnow().isoformat() # Get detailed stats if available try: r2 = await client.get(f"{m['url']}/config") if r2.status_code == 200: cfg = r2.json() m["domain_names"] = cfg.get("domain_names", m["domain_names"]) except Exception: pass else: m["healthy"] = False m["status"] = "unhealthy" except Exception: m["healthy"] = False m["status"] = "unreachable" m["last_check"] = datetime.utcnow().isoformat() # Calculate load (concurrent / max_concurrent * 100) m["load"] = min(100, int(m["concurrent"] / max(1, m["max_concurrent"]) * 100)) # ═══════ Status Report ═══════ def get_status(self) -> list[dict]: result = [] for mid, m in self.models.items(): result.append({ "id": mid, "name": m["name"], "url": m["url"], "priority": m["priority"], "domains": m["domains"], "domain_names": m["domain_names"], "healthy": m["healthy"], "status": m["status"], "load_percent": m["load"], "concurrent": m["concurrent"], "max_concurrent": m["max_concurrent"], "total_requests": m["total_requests"], "total_failures": m["total_failures"], "avg_response_time_ms": round(m["avg_response_time"] * 1000, 1), "last_response_time_ms": round(m["last_response_time"] * 1000, 1), "last_check": m["last_check"], "uptime_since": m["uptime_since"], "circuit_broken": m["circuit_broken"], }) return result def get_stats(self) -> dict: total_req = sum(m["total_requests"] for m in self.models.values()) total_fail = sum(m["total_failures"] for m in self.models.values()) healthy_count = sum(1 for m in self.models.values() if m["healthy"]) return { "models_total": len(self.models), "models_healthy": healthy_count, "total_requests": total_req, "total_failures": total_fail, "success_rate": round((1 - total_fail / max(1, total_req)) * 100, 1) if total_req else 0, "timestamp": datetime.utcnow().isoformat(), } # ═══════ Chat with Model ═══════ async def chat_with_model(self, model_id: str, message: str, history: list[dict] = []) -> dict: """Továbbítja a chat kérést a Space /chat endpointjára""" if model_id not in self.models: return {"error": "Model not found"} m = self.models[model_id] t0 = time.time() try: headers = {} if m["hf_token"]: headers["Authorization"] = f"Bearer {m['hf_token']}" async with httpx.AsyncClient(timeout=120) as client: resp = await client.post( f"{m['url']}/chat", json={"message": message, "history": history}, headers=headers, ) elapsed = time.time() - t0 if resp.status_code == 200: self.record_request(model_id, True, elapsed) return resp.json() else: self.record_request(model_id, False, elapsed) return {"error": f"Status {resp.status_code}", "raw": resp.text[:200]} except Exception as e: elapsed = time.time() - t0 self.record_request(model_id, False, elapsed) return {"error": str(e)} # ═══════════ Global Instance ══════════════════════════════ model_manager = ModelManager()