Files

261 lines
9.5 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""LLM-триаж алертов (Фаза 1).
Каждый критический алерт перед отправкой в Matrix проходит через модель:
она получает текст алерта + свежие ошибки журнала + состояние службы и
возвращает короткий вердикт:
что это / насколько срочно / что делать
Правила (анти-шум):
* модель НЕ решает, отправлять ли алерт — только дополняет его;
* если модель не уверена (confidence < 0.3) или не ответила — алерт
уходит как есть;
* вердикт короткий: одна строка + до двух действий;
* модель берётся через llm_fallback: локальная 3b → DeepSeek.
Использование:
from alert_triage import triage, merge
t = triage("Ollama", "сервер не отвечает")
text = merge("**Ollama**\\n\\nсервер не отвечает", t)
"""
import json
import os
import re
import subprocess
import sys
sys.path.insert(0, "/opt/hub-core")
from llm_fallback import ask, LLMUnavailable # noqa: E402
HUB = "http://127.0.0.1:9120"
MAX_CONTEXT = 600
CACHE_DIR = "/var/lib/hub-triage"
CACHE_TTL = 600 # секунд: одинаковый алерт не триажим повторно
LOCK_TTL = 90 # секунд: один триаж за раз
SYSTEM = """Ты — инженер эксплуатации домашней инфраструктуры (Proxmox, 30 контейнеров,
Matrix, LLM, медиа). Тебе дают алерт и факты из журнала. Задача: коротко и по делу
объяснить, что происходит и что делать.
Отвечай СТРОГО одним JSON-объектом, без пояснений и markdown:
{"summary": "одно предложение, что случилось", "severity": "critical|high|normal|low",
"action": "до двух конкретных шагов через точку с запятой",
"related": "связанный прошлый случай или пусто"}
Правила:
- опирайся ТОЛЬКО на факты в контексте; если фактов мало — так и напиши в summary;
- не выдумывай имена служб, которых нет в тексте;
- action — проверяемые шаги (команда, что открыть, что сравнить), не «проверить логи»;
- пиши по-русски, без канцелярита."""
def _keywords(text, limit=3):
words = re.findall(r"[A-Za-zА-Яа-яЁё][A-Za-zА-Яа-яЁё0-9_-]{3,}", text or "")
stop = {"сервер", "служба", "работает", "доступен", "проверка", "недоступна",
"критическая", "тревога", "ошибка", "сообщение", "система"}
out = []
for w in words:
lw = w.lower()
if lw in stop or lw in [x.lower() for x in out]:
continue
out.append(w)
if len(out) >= limit:
break
return out
def _journal_context(text, minutes=60, limit=6):
kws = _keywords(text)
try:
r = subprocess.run(
["journalctl", "--since", "-%d min" % minutes, "-p", "err",
"--no-pager", "-n", "400"],
capture_output=True, text=True, timeout=20)
lines = (r.stdout or "").splitlines()
except Exception:
return ""
if kws:
pat = re.compile("|".join(re.escape(k) for k in kws), re.I)
lines = [ln for ln in lines if pat.search(ln)]
lines = [ln.strip() for ln in lines if ln.strip()][-limit:]
return "\n".join(lines)[:MAX_CONTEXT]
def _status_context(text):
try:
import urllib.request as u
with u.urlopen(HUB + "/status.json", timeout=8) as r:
d = json.loads(r.read())
except Exception:
return ""
low = (text or "").lower()
for s in d.get("services") or []:
name = (s.get("name") or "").lower()
if name and name in low:
return ("служба %s: %s, %s:%s, группа %s"
% (s.get("name"), "работает" if s.get("up") else "ЛЕЖИТ",
s.get("ip"), s.get("port"), s.get("group")))
return ""
def _ensure_dir():
try:
os.makedirs(CACHE_DIR, exist_ok=True)
except Exception:
pass
def _cache_key(title, message):
import hashlib
h = hashlib.sha1(("%s|%s" % (title, message)).encode("utf-8", "replace")).hexdigest()[:16]
return h
def _cache_path():
return os.path.join(CACHE_DIR, "cache.json")
def _cache_get(key):
_ensure_dir()
try:
import time as _t
d = json.load(open(_cache_path(), encoding="utf-8"))
except Exception:
return None
rec = d.get(key)
if not rec:
return None
if _t.time() - rec.get("ts", 0) > CACHE_TTL:
return None
return rec.get("verdict")
def _cache_put(key, verdict):
_ensure_dir()
try:
import time as _t
d = {}
try:
d = json.load(open(_cache_path(), encoding="utf-8"))
except Exception:
d = {}
if len(d) > 200:
d = {}
d[key] = {"ts": _t.time(), "verdict": verdict}
json.dump(d, open(_cache_path(), "w", encoding="utf-8"), ensure_ascii=False)
except Exception:
pass
def _lock_acquire():
_ensure_dir()
import time as _t
p = os.path.join(CACHE_DIR, "triage.lock")
try:
if os.path.exists(p) and _t.time() - os.path.getmtime(p) < LOCK_TTL:
return False
except Exception:
pass
try:
open(p, "w").write(str(int(_t.time())))
except Exception:
return True
return True
def _lock_release():
try:
os.remove(os.path.join(CACHE_DIR, "triage.lock"))
except Exception:
pass
def triage(title, message, timeout_hint=None):
"""Возвращает dict вердикта или None. Никогда не бросает."""
chain = [{"name": "qwen2.5:3b", "kind": "ollama", "timeout": 45},
{"name": "deepseek-chat", "kind": "deepseek", "timeout": 30}]
ctx_parts = []
if title:
ctx_parts.append("Заголовок: %s" % title)
if message:
ctx_parts.append("Текст: %s" % message[:600])
j = _journal_context("%s %s" % (title, message))
if j:
ctx_parts.append("Ошибки журнала за час:\n" + j)
st = _status_context("%s %s" % (title, message))
if st:
ctx_parts.append("Состояние: " + st)
prompt = "\n\n".join(ctx_parts) + "\n\nВерни JSON."
key = _cache_key(title, message)
cached = _cache_get(key)
if cached is not None:
return cached
if not _lock_acquire():
return None
try:
r = ask(prompt, system=SYSTEM, max_tokens=160, temperature=0.2, chain=chain)
except LLMUnavailable:
_lock_release()
return None
except Exception:
_lock_release()
return None
_lock_release()
raw = (r.get("text") or "").strip()
m = re.search(r"\{.*\}", raw, re.S)
if not m:
return None
try:
d = json.loads(m.group(0))
except Exception:
return None
if not isinstance(d, dict):
return None
out = {
"summary": str(d.get("summary") or "").strip()[:200],
"severity": str(d.get("severity") or "").strip().lower(),
"action": str(d.get("action") or "").strip()[:220],
"confidence": d.get("confidence", 0),
"related": str(d.get("related") or "").strip()[:120],
"model": r.get("model"),
"fallback": r.get("fallback"),
"ms": r.get("ms"),
}
# Самооценку модели не используем: она ставит 0.0 произвольно.
# Уверенность считаем по фактам: есть состояние службы или ошибки журнала.
facts = bool(j) or bool(st)
out["confidence"] = 0.75 if facts else 0.5
if not out.get("summary") and not out.get("action"):
return None
_cache_put(key, out)
return out
def merge(message, t):
"""Дополняет текст алерта вердиктом. Если модель не уверена — не трогает."""
if not t or not (t.get("summary") or t.get("action")):
return message
lines = ["", "—", "**Вердикт:** " + t["summary"]]
if t.get("severity"):
lines.append("Срочность: " + t["severity"])
if t.get("action"):
lines.append("Что делать: " + t["action"])
lines.append("_(модель: %s%s)_" % (t.get("model") or "?",
", фолбэк" if t.get("fallback") else ""))
return message + "\n".join(lines)
if __name__ == "__main__":
args = [a for a in sys.argv[1:] if not a.startswith("--")]
title = args[0] if args else "Ollama"
msg = args[1] if len(args) > 1 else "сервер жив, но генерация висит"
t = triage(title, msg)
if not t:
print("вердикт: нет (модели недоступны)")
sys.exit(1)
print(json.dumps(t, ensure_ascii=False, indent=2))
print("\n--- как выглядит в чате ---")
print(merge("**%s**\n\n%s" % (title, msg), t))