#!/usr/bin/env python3 """Arena with good models: DeepSeek API + Gemini 2.5 Flash via VPS. No token purchase; uses existing keys. Kimi/Claude need their own keys. """ import json import re import subprocess import 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() GEMINI = Path("/root/.gemini-key").read_text().strip() VPS = "root@193.233.210.184" 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("insert into audit.arena_runs(audit_run_id,status) values(1,'running') returning id") run_id = cur.fetchone()[0] conn.commit() 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": 1800, }).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_gemini(): body = json.dumps({ "contents": [{"parts": [{"text": PROMPT}]}], "generationConfig": {"temperature": 0.3, "maxOutputTokens": 1800}, }) # key is copied to a private remote temp file; payload is stdin. subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", VPS, "umask 077; cat > /tmp/.audit-gemini-key"], input=GEMINI, text=True, timeout=20, check=True) remote = ("KEY=$(cat /tmp/.audit-gemini-key); " "curl -sS --max-time 150 -X POST -H 'Content-Type: application/json' -d @- " "'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$KEY'; " "rm -f /tmp/.audit-gemini-key") p = subprocess.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", VPS, remote], input=body, text=True, capture_output=True, timeout=180) if p.returncode != 0: raise RuntimeError((p.stderr or "gemini ssh error")[:300]) d = json.loads(p.stdout) raw = d.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text") or "{}" return json_from_text(raw).get("opportunities") or [], raw all_items = [] for voice, model, fn in (("deepseek", "deepseek-chat", ask_deepseek), ("gemini", "gemini-2.5-flash", ask_gemini)): 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, "Независимый аудитор", 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, "Независимый аудитор", str(e)[:2000])) conn.commit() print(voice, "error", str(e)[:200], flush=True) cur.execute("select key,leverage,criticality from audit.capabilities where run_id=1") cap_meta = {r[0]: (r[1] or 3, r[2] or 3) for r in cur.fetchall()} 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 g in groups.values(): 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) lev, crit = cap_meta.get(str(it.get("capability") or ""), (3, 3)) score = impact * 2 - effort + (5 - risk) + max(0, len(voices) - 1) + lev + crit it["_score"] = score; it["_voices"] = voices ranked.append(it) ranked.sort(key=lambda x: x["_score"], reverse=True) selected, seen = [], set() for it in ranked: cap = str(it.get("capability") or "") if cap in seen: continue selected.append(it) if cap: seen.add(cap) if len(selected) >= 8: break 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(set(i["_voice"] for i in all_items)), "items": len(ranked), "selected": len(selected)}, ensure_ascii=False), run_id)) conn.commit() print("arena run", run_id, "items", len(ranked), "selected", len(selected)) cur.close(); conn.close()