79 lines
3.9 KiB
Python
79 lines
3.9 KiB
Python
#!/usr/bin/env python3
|
|
import json, re, urllib.request
|
|
from pathlib import Path
|
|
import psycopg2
|
|
|
|
PASS = Path("/root/.pg-superuser-pass").read_text().strip()
|
|
DEEPSEEK = Path("/root/.deepseek-key").read_text().strip()
|
|
PACKET = json.loads(Path("/root/buryan-infra/ops/audit/arena_packet.json").read_text(encoding="utf-8"))
|
|
conn = psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8")
|
|
cur = conn.cursor()
|
|
cur.execute("select id from audit.arena_runs where status='packet' order by id desc limit 1")
|
|
row = cur.fetchone()
|
|
if not row:
|
|
raise SystemExit("no packet arena run")
|
|
run_id = row[0]
|
|
PROMPT = """Ты независимый аудитор Buryans Hub. Не выдумывай сервисы, метрики и владельцев.
|
|
Ниже evidence-пакет. Предложи 6 возможностей развития с максимальной пользой.
|
|
Для каждой: title, capability (key), hypothesis, impact 1-5, effort 1-5, risk 1-5,
|
|
first_step, evidence (конкретный факт/сервис из пакета). Верни ТОЛЬКО JSON:
|
|
{"opportunities":[...]}.
|
|
PACKET:
|
|
%s
|
|
""" % json.dumps(PACKET, ensure_ascii=False)[:9000]
|
|
|
|
def json_from_text(text):
|
|
t = str(text or "").strip()
|
|
t = re.sub(r"^```(?:json)?", "", t, flags=re.I).strip()
|
|
t = re.sub(r"```$", "", t).strip()
|
|
try:
|
|
return json.loads(t)
|
|
except Exception:
|
|
i, j = t.find("{"), t.rfind("}")
|
|
if i >= 0 and j > i:
|
|
return json.loads(t[i:j+1])
|
|
raise
|
|
|
|
def ask_deepseek():
|
|
req = urllib.request.Request("https://api.deepseek.com/v1/chat/completions", data=json.dumps({
|
|
"model": "deepseek-chat",
|
|
"messages": [{"role": "system", "content": "Отвечай только валидным JSON."},
|
|
{"role": "user", "content": PROMPT}],
|
|
"temperature": 0.3, "max_tokens": 1400,
|
|
}).encode(), headers={"Authorization": "Bearer " + DEEPSEEK, "Content-Type": "application/json"}, method="POST")
|
|
with urllib.request.urlopen(req, timeout=180) as r:
|
|
d = json.load(r)
|
|
raw = d.get("choices", [{}])[0].get("message", {}).get("content") or "{}"
|
|
return json_from_text(raw).get("opportunities") or [], raw
|
|
|
|
def ask_qwen7b():
|
|
req = urllib.request.Request("http://192.168.1.229:11434/api/chat", data=json.dumps({
|
|
"model": "qwen2.5:7b",
|
|
"messages": [{"role": "system", "content": "Отвечай только валидным JSON."},
|
|
{"role": "user", "content": PROMPT}],
|
|
"stream": False, "format": "json",
|
|
"options": {"temperature": 0.35, "num_predict": 1200, "num_gpu": 999},
|
|
}).encode(), headers={"Content-Type": "application/json"}, method="POST")
|
|
with urllib.request.urlopen(req, timeout=600) as r:
|
|
d = json.load(r)
|
|
raw = (d.get("message") or {}).get("content") or "{}"
|
|
return json_from_text(raw).get("opportunities") or [], raw
|
|
|
|
for voice, model, role, fn in [
|
|
("deepseek-auditor", "deepseek-chat", "Независимый аудитор, стратегия и приоритеты", ask_deepseek),
|
|
("qwen7b-sre", "qwen2.5:7b", "SRE/надёжность и эксплуатация", ask_qwen7b),
|
|
]:
|
|
try:
|
|
items, raw = fn()
|
|
cur.execute("insert into audit.arena_answers(arena_run_id,voice,model,role,answer,raw) values(%s,%s,%s,%s,%s,%s)",
|
|
(run_id, voice, model, role, json.dumps(items, ensure_ascii=False), raw[:30000]))
|
|
conn.commit()
|
|
print(voice, "items", len(items), flush=True)
|
|
except Exception as e:
|
|
conn.rollback()
|
|
cur.execute("insert into audit.arena_answers(arena_run_id,voice,model,role,answer,raw) values(%s,%s,%s,%s,'[]',%s)",
|
|
(run_id, voice, model, role, ("ERROR: " + str(e))[:2000]))
|
|
conn.commit()
|
|
print(voice, "ERROR", str(e)[:200], flush=True)
|
|
cur.close(); conn.close()
|