rmi-backend/app/_archive/legacy_2026_07/ai_risk_explainer.py
cryptorugmunch 628c1d2a10
Some checks failed
CI / build (push) Failing after 3s
refactor(rmi-backend,audit): mount Wave 3 + archive 136 dead-code files (P2.3)
PHASE 2.3 (AUDIT-2026-Q3.md):

Task 1 — Wire-in Wave 3 (1 router mounted, 2 deferred):
  - app.routers.unified_scanner_router mounted at /api/v2/scanner/* (2 routes:
    POST /api/v2/scanner/token/scan, POST /api/v2/scanner/wallet/scan).
    Refactored prefix from /api/v2 -> /api/v2/scanner to avoid future conflicts
    with the v1 /api/v1/scanner/ stub.
  - app.routers.unified_wallet_scanner DEFERRED (no router APIRouter attribute;
    library module consumed by unified_scanner_router via get_wallet_scanner()).
  - app.routers.admin_extensions DEFERRED (DORMANT per audit; 25 routes at
    /api/v1/admin/* would shadow /api/v1/admin/alerts_webhook).

Task 2 — Archive 136 dead-code files to app/_archive/legacy_2026_07/:
  - 73 routers in app/routers/ (reach graph showed zero reach into mount.py).
  - 63 flat app/*.py (domain modules never imported by live code).
  - 1 file RESTORED post-archive: app/routers/x402_bridge_health.py (caught by
    tests/unit/test_bridge_health.py which directly imports it; reach graph
    considered tests/ only as transitive reach — to be patched in next cycle).

Forced-LIVE (NOT archived per user directive):
  - app/ai_pipeline_v3.py  (3 importers in audit window, importers themselves DEAD)
  - app/splade_bm25.py       (LIVE via app.rag_service)
  - app/wallet_manager_v2.py (LIVE via x402_enforcement, x402_tools, sweep_all, sweep_now)
  - app/crypto_embeddings.py (NOT in audit ARCHIVE list; heavy import graph)

Verification (forward-import closure from mount.py + main.py + factory.py + lifespan.py):
  - imports = 348 app.* modules
  - reached = 194 files reachable from roots
  - archive set = audit_dead (186) - reached - forced_live (4) - test_live (1) = 136
  - Net delta: 136 files moved, 44,932 LOC reduction, 293->295 active routes (+2 from Wave 3)

pyproject.toml updates:
  - setuptools.packages.find: added exclude for app._archive*
  - ruff.extend-exclude: added "app/_archive/"
  - mypy.exclude: added "app/_archive/"

Smoke test: pytest tests/ — 817 passed, 3 pre-existing failures unchanged
(0 new failures; 0 routes lost; all 4 forced-LIVE files still importable).

Restoration: git mv app/_archive/legacy_2026_07/<name>.py <original-path>
and add the import to app/mount.py ROUTER_MODULES.

Refs: AUDIT-2026-Q3.md /home/dev/pry/rmi-final-deadcode-2026-07-06.md
2026-07-06 20:52:31 +02:00

187 lines
6.2 KiB
Python

#!/usr/bin/env python3
"""
RMI AI Risk Explainer - Ollama Cloud Powered
=============================================
Takes raw scanner output → generates consumer-friendly risk explanations.
Used by Telegram bot, website, and scanner API.
Cost: ~100 tokens per explanation = ~$0.0007 on Ollama Cloud
"""
import json
import logging
import os
from urllib.request import Request, urlopen
logger = logging.getLogger("rmi.risk_explainer")
OLLAMA_KEY = os.getenv("OLLAMA_API_KEY", os.getenv("DEEPSEEK_API_KEY", ""))
OLLAMA_URL = "https://ollama.com/v1/chat/completions"
BACKEND_URL = os.getenv("BACKEND_URL", "http://localhost:8000")
MODEL = "deepseek-v4-flash"
SYSTEM_PROMPT = """You are RMI Risk Analyst. Given raw token scanner data, write a consumer-friendly risk explanation in 3-4 sentences.
Rules:
- Start with the safety score and risk level (SAFE/LOW/MEDIUM/HIGH/CRITICAL)
- Mention the 1-2 most important risk flags with plain-English explanations
- If there are green flags, mention the most reassuring one
- Be direct and honest - call out scams clearly
- Use Telegram HTML formatting: <b>bold</b> for key terms
- Never give financial advice. End with "Always DYOR."
Example output:
"<b>Safety: 23/100 - HIGH RISK</b>. This token has <b>unlocked liquidity</b>, meaning the deployer can drain funds anytime. The <b>deployer wallet has 6 prior rugs</b>. No redeeming factors found. Avoid this token. Always DYOR."
"""
def explain_risks(scan: dict) -> str:
"""Generate a human-readable risk explanation from scanner data."""
if not scan or scan.get("safety_score") is None:
return "<b>Unable to analyze</b> - no scanner data available."
score = scan.get("safety_score", 50)
flags = scan.get("risk_flags", [])
green = scan.get("green_flags", [])
name = scan.get("name", scan.get("symbol", "This token"))
modules = len(scan.get("modules_run", []))
# Build a concise prompt for the AI
prompt = f"""Token safety scan results:
- Token: {name}
- Safety score: {score}/100
- Risk flags: {", ".join(flags[:5]) if flags else "none"}
- Green flags: {", ".join(green[:3]) if green else "none"}
- Modules analyzed: {modules}
Write the explanation."""
try:
body = json.dumps(
{
"model": MODEL,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": prompt},
],
"max_tokens": 150,
"temperature": 0.3,
}
).encode()
req = Request(
OLLAMA_URL,
data=body,
headers={
"Authorization": f"Bearer {OLLAMA_KEY}",
"Content-Type": "application/json",
},
)
resp = urlopen(req, timeout=15)
data = json.loads(resp.read())
return data["choices"][0]["message"]["content"].strip()
except Exception as e:
logger.error(f"Risk explainer failed: {e}")
# Fallback: basic explanation without AI
return _basic_explain(scan)
def _basic_explain(scan: dict) -> str:
"""Basic explanation when AI is unavailable."""
score = scan.get("safety_score", 50)
if score >= 80:
level = "SAFE"
elif score >= 60:
level = "LOW RISK"
elif score >= 40:
level = "MEDIUM RISK"
elif score >= 20:
level = "HIGH RISK"
else:
level = "CRITICAL"
flags = scan.get("risk_flags", [])
green = scan.get("green_flags", [])
scan.get("name", scan.get("symbol", "This token"))
msg = [f"<b>Safety: {score}/100 - {level}</b>"]
if flags:
msg.append(f"Risk flags: {', '.join(flags[:3])}")
if green:
msg.append(f"Green flags: {', '.join(green[:2])}")
msg.append("Always DYOR.")
return ". ".join(msg)
# ── News Classification ──
NEWS_SYSTEM = """Classify crypto news headlines into categories. Reply with ONLY the category name.
Categories:
- SCAM: rug pulls, hacks, exploits, phishing, fraud
- MARKET: price action, trading, volume, market cap, BTC/ETH moves
- REGULATION: government, SEC, legal, compliance, bans
- SECURITY: vulnerability, audit, patch, wallet security
- DEFI: DeFi protocols, yield, liquidity, lending
- MEMECOIN: meme tokens, celebrity coins, pump events
- GENERAL: anything else"""
def classify_news(title: str, content: str = "") -> str:
"""Classify a news article into a category."""
text = f"{title}\n{content[:200]}" if content else title
try:
body = json.dumps(
{
"model": MODEL,
"messages": [
{"role": "system", "content": NEWS_SYSTEM},
{"role": "user", "content": text},
],
"max_tokens": 10,
"temperature": 0.1,
}
).encode()
req = Request(
OLLAMA_URL,
data=body,
headers={
"Authorization": f"Bearer {OLLAMA_KEY}",
"Content-Type": "application/json",
},
)
resp = urlopen(req, timeout=10)
data = json.loads(resp.read())
category = data["choices"][0]["message"]["content"].strip().upper()
# Normalize
for cat in ["SCAM", "MARKET", "REGULATION", "SECURITY", "DEFI", "MEMECOIN", "GENERAL"]:
if cat in category:
return cat
return "GENERAL"
except Exception as e:
logger.warning(f"News classification failed: {e}")
# Basic keyword fallback
t = (title + " " + content).lower()
if any(w in t for w in ["hack", "exploit", "rug", "scam", "phish"]):
return "SCAM"
if any(w in t for w in ["price", "btc", "eth", "bull", "bear", "market"]):
return "MARKET"
if any(w in t for w in ["sec ", "regulation", "ban", "law", "legal"]):
return "REGULATION"
return "GENERAL"
if __name__ == "__main__":
# Test
test = {
"safety_score": 23,
"risk_flags": ["LP_LOCK_LOW", "DEV_HIGH_RISK", "HONEYPOT_DETECTED"],
"green_flags": [],
"name": "SCAMCOIN",
"modules_run": ["security", "holders", "liquidity"],
}
print(explain_risks(test))
print()
print(classify_news("$4M rug pull on Solana - deployer drained LP", ""))