Files
buryan-infra/ops/audit/audit_arena_local.py
T
architect 768ba209f6
lint / hygiene (push) Failing after 19s
lint / hygiene (pull_request) Failing after 23s
standard / check (push) Successful in 10s
standard / check (pull_request) Successful in 10s
[ARCH] Audit 360 service, collectors, snapshots and sprint tool
2026-11-26 21:45:23 +03:00

103 lines
4.7 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
import json
import re
import urllib.request
from pathlib import Path
import psycopg2
PASS = Path("/root/.pg-superuser-pass").read_text().strip()
conn = psycopg2.connect(host="192.168.1.151", dbname="rag", user="postgres", password=PASS, client_encoding="UTF8")
cur = conn.cursor()
packet = json.loads(Path("/root/buryan-infra/ops/audit/arena_packet.json").read_text(encoding="utf-8"))
cur.execute("select id from audit.arena_runs order by id desc limit 1")
run_id = cur.fetchone()[0]
VOICES = [
("qwen3b-architect", "qwen2.5:3b-32k", "Системный архитектор", 1600, 300),
("qwen7b-sre", "qwen2.5:7b", "SRE/надёжность и эксплуатация", 1200, 420),
]
def ask(model, role, max_tokens, timeout):
prompt = """Ты — независимый аудитор Buryans Hub в режиме арены. Роль: %s.
Ниже evidence-пакет. Не выдумывай сервисы, цифры и владельцев. Предложи 6 возможностей,
которые дают максимальную пользу с учётом фактов. Для каждой:
title, capability (key), hypothesis, impact 1-5, effort 1-5, risk 1-5,
first_step, evidence (конкретный факт/сервис из пакета).
Верни только JSON: {"opportunities":[...]}.
PACKET:
%s
""" % (role, json.dumps(packet, ensure_ascii=False)[:9000])
req = urllib.request.Request("http://192.168.1.229:11434/api/chat", data=json.dumps({
"model": model,
"messages": [{"role": "system", "content": "Отвечай только валидным JSON."},
{"role": "user", "content": prompt}],
"stream": False, "format": "json",
"options": {"temperature": 0.35, "num_predict": max_tokens, "num_gpu": 999},
}).encode(), headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(req, timeout=timeout) as r:
d = json.load(r)
raw = (d.get("message") or {}).get("content") or "{}"
data = json.loads(raw)
return data.get("opportunities") or [], raw
all_items = []
for voice, model, role, mt, to in VOICES:
try:
items, raw = ask(model, role, mt, to)
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[:20000]))
conn.commit()
print(voice, "items", len(items), flush=True)
for it in items:
if isinstance(it, dict) and it.get("title"):
it["_voice"] = voice
all_items.append(it)
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, str(e)[:2000]))
conn.commit()
print(voice, "error", str(e)[:160], flush=True)
# Deterministic dedupe + scoring. No self-preference judge.
def norm(s):
return re.sub(r"[^a-zа-я0-9]+", " ", str(s or "").lower()).strip()
groups = {}
for it in all_items:
key = (norm(it.get("capability")), norm(it.get("title")))
g = groups.setdefault(key, {"item": it, "voices": set()})
g["voices"].add(it.get("_voice"))
ranked = []
for key, g in groups.items():
it = dict(g["item"])
voices = sorted(g["voices"])
impact = int(it.get("impact") or 3)
effort = int(it.get("effort") or 3)
risk = int(it.get("risk") or 3)
novelty = max(0, len(voices) - 1)
score = impact * 2 - effort + (5 - risk) + novelty
it["_score"] = score
it["_voices"] = voices
ranked.append(it)
ranked.sort(key=lambda x: x["_score"], reverse=True)
selected = ranked[:8]
cur.execute("delete from audit.arena_items where arena_run_id=%s", (run_id,))
for it in ranked:
cur.execute("""insert into audit.arena_items(arena_run_id,title,capability,voices,impact,effort,risk,score,evidence,hypothesis,first_step,selected)
values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
(run_id, str(it.get("title"))[:300], str(it.get("capability") or ""), ",".join(it["_voices"]),
int(it.get("impact") or 3), int(it.get("effort") or 3), int(it.get("risk") or 3), it["_score"],
str(it.get("evidence") or "")[:1000], str(it.get("hypothesis") or "")[:1000],
str(it.get("first_step") or "")[:1000], it in selected))
cur.execute("update audit.arena_runs set status='done', finished_at=now(), summary=%s where id=%s",
(json.dumps({"voices": len(VOICES), "items": len(ranked), "selected": len(selected)}, ensure_ascii=False), run_id))
conn.commit()
print("arena items", len(ranked), "selected", len(selected))
cur.close(); conn.close()