"""Capacity copilot: local insight always, LLM narrative on Enterprise.""" from __future__ import annotations import json from typing import Any, Dict, List, Optional from . import capacity, db, licensing from .registry import SECRET_MASK SYSTEM_PROMPT = ( "You are Headroom Copilot, a senior infrastructure capacity engineer for a homelab. " "Answer with concrete, quantified advice based on the supplied fleet context. " "Be concise (max ~220 words), use short paragraphs or bullets, and never invent assets, " "metrics or alerts that are not in the context. If data is missing, say what to configure. " "Distinguish correlation from causation and include the top risk plus the next action." ) def config() -> Dict[str, Any]: settings = db.settings_map() key = settings.get("ai_api_key", "") return { "base_url": settings.get("ai_base_url", ""), "model": settings.get("ai_model", ""), "api_key": SECRET_MASK if key else "", "key_set": bool(key), "configured": bool(settings.get("ai_base_url") and settings.get("ai_model")), "available": licensing.has_feature("llm_copilot"), "provider_hint": "Any OpenAI-compatible endpoint (OpenAI, Azure, Ollama, LM Studio, LiteLLM)", } def update_config(payload: Dict[str, Any]) -> Dict[str, Any]: base_url = str(payload.get("base_url", "")).strip()[:500] model = str(payload.get("model", "")).strip()[:200] key = payload.get("api_key") db.set_setting("ai_base_url", base_url) db.set_setting("ai_model", model) if isinstance(key, str) and key not in ("", SECRET_MASK): db.set_setting("ai_api_key", key.strip()[:500]) elif key == "": db.set_setting("ai_api_key", "") return config() def fleet_context() -> Dict[str, Any]: data = capacity.overview(7) return { "generated_at": data["generated_at"], "kpis": data["kpis"], "resources": data["resources"], "top_pressure": [ { "name": asset["name"], "type": asset["type"], "module": asset["module_name"], "util_pct": asset["util"], "pressure": asset["pressure"], "slope_pp_per_day": asset["slope_per_day"], "days_to_full": asset["days_to_full"], } for asset in data["top_pressure"] ], "movers": [ { "name": asset["name"], "slope_pp_per_day": asset["slope_per_day"], "util_pct": asset["util"], } for asset in data["movers"] ], "alerts": [alert["message"] for alert in data["alerts"]], "modules": [ {"id": m["id"], "name": m["name"], "status": m["status"], "enabled": m["enabled"]} for m in data["modules"] ], } def chat(messages: List[Dict[str, str]]) -> Dict[str, Any]: cleaned = [] for message in messages[-12:]: if not isinstance(message, dict): continue role = str(message.get("role", "user")) if role not in ("user", "assistant", "system"): continue content = str(message.get("content", ""))[:6000].strip() if content: cleaned.append({"role": role, "content": content}) if not cleaned: raise ValueError("A message is required") local = capacity.local_insights() cfg = config() configured = bool(cfg["base_url"] and cfg["model"]) if not licensing.has_feature("llm_copilot"): return { "mode": "local", "message": local, "upgrade_required": True, "note": "Local capacity analysis. Add an LLM provider with Headroom Enterprise for conversational answers.", } if not configured: return { "mode": "local", "message": local, "upgrade_required": False, "note": "No LLM provider is configured yet. Showing the deterministic local analysis.", } try: import requests settings = db.settings_map() base = cfg["base_url"].rstrip("/") url = base if base.endswith("/chat/completions") else base + "/chat/completions" headers = {"Content-Type": "application/json"} if settings.get("ai_api_key"): headers["Authorization"] = f"Bearer {settings['ai_api_key']}" context = json.dumps(fleet_context(), default=str) body = { "model": cfg["model"], "messages": [{"role": "system", "content": SYSTEM_PROMPT + "\n\nFleet context:\n" + context}] + cleaned, "temperature": 0.2, "max_tokens": 900, } response = requests.post(url, headers=headers, json=body, timeout=75) if response.status_code >= 400: raise RuntimeError(f"provider returned HTTP {response.status_code}: {response.text[:300]}") payload = response.json() choices = payload.get("choices") or [] if not choices: raise RuntimeError("provider returned no choices") content = choices[0].get("message", {}).get("content", "") if not content: raise RuntimeError("provider returned an empty answer") return { "mode": "llm", "message": content, "upgrade_required": False, "model": cfg["model"], "note": "Answer generated from live Headroom context.", } except Exception as exc: return { "mode": "local", "message": local, "upgrade_required": False, "note": f"LLM provider unavailable, showing local analysis instead ({str(exc)[:180]}).", } def suggested_questions() -> List[str]: return [ "Hvad bliver det næste kapacitetsproblem i mit lab?", "Which assets should I upgrade first, and by how much?", "Er der noget der er steget unormalt hurtigt den sidste uge?", "Simulér 6 måneders vækst med 8 TB ekstra storage.", ]