diff --git a/ops/hermes/hermes_ai_digest.py b/ops/hermes/hermes_ai_digest.py new file mode 100644 index 0000000..16347f5 --- /dev/null +++ b/ops/hermes/hermes_ai_digest.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +"""Hermes AI-дайджест: ошибки журнала -> LLM -> короткая сводка. + +Провайдер по умолчанию — локальный узел (приватно, без лимитов). +При его недоступности — DeepSeek API (быстро, внешний). +""" +import json +import subprocess +import sys +import urllib.request + +LOCAL = "http://192.168.1.229:11434" +LOCAL_MODEL = "qwen2.5:7b" +DS_KEY_FILE = "/root/.deepseek-key" +DS_API = "https://api.deepseek.com/chat/completions" + + +def sh(cmd, limit=120): + try: + out = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=60).stdout + except Exception as e: + out = "ошибка: %s" % e + return "\n".join(out.splitlines()[-limit:]) + + +def ask_local(prompt, max_tokens=500): + body = json.dumps({ + "model": LOCAL_MODEL, "prompt": prompt, "stream": False, + "options": {"num_predict": max_tokens, "temperature": 0.2}, + }).encode() + req = urllib.request.Request(LOCAL + "/api/generate", data=body, method="POST") + req.add_header("Content-Type", "application/json") + with urllib.request.urlopen(req, timeout=600) as r: + return json.loads(r.read().decode()).get("response", "").strip() + + +def ask_deepseek(prompt, max_tokens=600): + key = open(DS_KEY_FILE).read().strip() + body = json.dumps({ + "model": "deepseek-chat", + "messages": [{"role": "system", "content": "Ты краткий и точный системный администратор."}, + {"role": "user", "content": prompt}], + "temperature": 0.2, "max_tokens": max_tokens, + }).encode() + req = urllib.request.Request(DS_API, data=body, method="POST") + req.add_header("Authorization", "Bearer " + key) + req.add_header("Content-Type", "application/json") + with urllib.request.urlopen(req, timeout=180) as r: + d = json.loads(r.read().decode()) + return d["choices"][0]["message"]["content"].strip() + + +def maintenance_notes(): + """Намеренно остановленное — чтобы модель не советовала «запустить».""" + try: + import yaml + m = yaml.safe_load(open("/root/buryan-infra/ops/hermes/maintenance.yaml", encoding="utf-8")) or {} + out = [] + for ct, info in (m.get("ct") or {}).items(): + out.append("CT%s (%s) — остановлен намеренно: %s" + % (ct, info.get("name", "?"), info.get("reason", ""))) + for unit, info in (m.get("units_off") or {}).items(): + out.append("%s — выключен: %s" % (unit, info.get("reason", ""))) + return "\n".join(out) or "нет" + except Exception: + return "нет" + + +def main(): + errors = sh("journalctl --since '-2h' -p err --no-pager 2>/dev/null | tail -60") + status = sh("pct list 2>/dev/null | head -40") + disk = sh("df -h / /mnt/media 2>/dev/null | tail -3") + failed = sh("systemctl --failed --no-legend --no-pager 2>/dev/null | head -10") + maint = maintenance_notes() + + if not errors.strip() and not failed.strip(): + text = "Ошибок в журнале за 2 часа нет, упавших юнитов нет." + print("=== ОТВЕТ (без модели) ===\n" + text) + try: + nb = json.dumps({"text": text, "source": "hermes-ai", "level": "info"}).encode() + nreq = urllib.request.Request("http://127.0.0.1:9120/notify", data=nb, method="POST") + nreq.add_header("Content-Type", "application/json") + with urllib.request.urlopen(nreq, timeout=30) as nr: + print("\nnotify:", nr.status) + except Exception: + pass + return 0 + + prompt = ( + "Ты администратор домашнего сервера. Составь короткую сводку по-русски (максимум 5 строк).\n" + "СТРОГИЕ ПРАВИЛА:\n" + "1. Используй ТОЛЬКО строки, приведённые ниже. Ничего не выдумывай.\n" + "2. Если строк нет — напиши: «в журнале пусто».\n" + "3. Учитывай раздел «НАМЕРЕННО ОСТАНОВЛЕНО»: эти сервисы трогать не надо.\n" + "4. Формат: «Требует внимания: …» / «Можно игнорировать: …» / «Действия: …».\n\n" + "=== ОШИБКИ ЖУРНАЛА (только это факты) ===\n%s\n\n" + "=== УПАВШИЕ ЮНИТЫ ===\n%s\n\n" + "=== НАМЕРЕННО ОСТАНОВЛЕНО ===\n%s\n\n" + "=== КОНТЕЙНЕРЫ ===\n%s\n\n=== ДИСКИ ===\n%s" + % (errors or "пусто", failed or "нет", maint, status, disk) + ) + + provider = "local" + try: + text = ask_local(prompt) + if not text: + raise RuntimeError("пустой ответ") + except Exception as e: + print("локальный узел не ответил (%s), переключаюсь на DeepSeek" % type(e).__name__, + file=sys.stderr) + provider = "deepseek" + try: + text = ask_deepseek(prompt) + except Exception as e2: + print("обе модели недоступны:", e2, file=sys.stderr) + return 1 + + print("=== ОТВЕТ (%s) ===" % provider) + print(text) + open("/tmp/hermes-ai-digest.txt", "w").write(text) + + try: + nb = json.dumps({"text": text, "source": "hermes-ai", "level": "info"}).encode() + nreq = urllib.request.Request("http://127.0.0.1:9120/notify", data=nb, method="POST") + nreq.add_header("Content-Type", "application/json") + with urllib.request.urlopen(nreq, timeout=30) as nr: + print("\nnotify:", nr.status) + except Exception as e: + print("\nnotify ошибка:", type(e).__name__, str(e)[:120]) + return 0 + + +if __name__ == "__main__": + sys.exit(main())