Files
buryan-infra/ops/work/rules_llm.py
T

93 lines
3.8 KiB
Python
Raw 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-правила: человекочитаемые подсказки по схемам из матрицы и документации.
Берёт матрицу совместимости Yealink, для ключевых устройств просит локальную
модель сформулировать правило по-русски: что это за устройство, что к нему
подключается и какие есть ограничения.
Результат дописывается в compat/rules.yaml в раздел `notes`:
notes:
- device: UVC86
role: camera
note: "камера-хаб: микрофоны и спикер подключаются к ней"
advice: "до 8 микрофонов VCM36-W по Wi-Fi"
"""
import json
import re
import sys
import time
import urllib.request as u
import yaml
BASE = "/opt/work-hub/compat"
RULES = BASE + "/rules.yaml"
OLLAMA = "http://192.168.1.229:11434"
MODEL = "qwen2.5:3b"
LIMIT = int(sys.argv[1]) if len(sys.argv) > 1 else 12
def norm(s):
return re.sub(r"[^a-z0-9а-я]+", "", str(s or "").lower())
def ask(prompt, timeout=120):
body = json.dumps({"model": MODEL, "prompt": prompt, "stream": False,
"options": {"temperature": 0.2, "num_predict": 220}}).encode()
req = u.Request(OLLAMA + "/api/generate", data=body,
headers={"Content-Type": "application/json"})
with u.urlopen(req, timeout=timeout) as r:
return (json.loads(r.read()) or {}).get("response", "").strip()
def clean(text):
t = re.sub(r"```.*?```", "", text, flags=re.S)
t = re.sub(r"^\s*(Правило|Ответ|Note)\s*:\s*", "", t, flags=re.I)
return " ".join(t.split())[:400]
def main():
rules = yaml.safe_load(open(RULES, encoding="utf-8")) or {}
edges = rules.get("rules") or []
hubs = rules.get("hubs") or []
# берём самые «богатые» хабы
targets = [h for h in hubs if h.get("count", 0) >= 3][:LIMIT]
if not targets:
print("нет целей")
return
notes = []
for i, h in enumerate(targets, 1):
dev = h.get("device")
sup = [e for e in edges if e.get("from") == dev and e.get("ok")][:8]
listing = "\n".join(
"- %s (до %s): %s" % (e.get("to"), e.get("max_qty") or "—",
(e.get("condition") or "")[:90]) for e in sup)
prompt = (
"Ты проектировщик AV-систем Yealink. По списку совместимости составь "
"краткое правило подключения на русском (2 предложения): что это за "
"устройство и что к нему можно подключить, с числовыми лимитами.\n\n"
"Устройство: %s\nСовместимо:\n%s\n\nПравило:" % (dev, listing))
try:
t0 = time.time()
text = clean(ask(prompt))
notes.append({"device": dev, "count": h.get("count"),
"max_qty": h.get("max_qty"), "note": text,
"source": "llm:" + MODEL})
print(" [%d/%d] %-22s %.1f c: %s" % (i, len(targets), dev,
time.time() - t0, text[:90]))
except Exception as e:
print(" [%d/%d] %-22s ошибка: %s" % (i, len(targets), dev, str(e)[:60]))
if notes:
rules["notes"] = notes
rules["notes_updated"] = time.strftime("%Y-%m-%dT%H:%M")
open(RULES, "w", encoding="utf-8").write(
yaml.safe_dump(rules, allow_unicode=True, sort_keys=False))
print("записано правил LLM:", len(notes))
if __name__ == "__main__":
main()