petter2025 commited on
Commit
3d17053
·
verified ·
1 Parent(s): 4a6c22e

Create ai_risk_engine.py

Browse files
Files changed (1) hide show
  1. ai_risk_engine.py +49 -0
ai_risk_engine.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Local Bayesian risk engine for AI tasks – uses conjugate Beta priors.
3
+ """
4
+
5
+ import threading
6
+ import numpy as np
7
+ from typing import Dict, Tuple
8
+
9
+ AI_CATEGORIES = ["chat", "code", "summary", "image", "audio", "iot"]
10
+
11
+ DEFAULT_PRIORS = {
12
+ "chat": (1.0, 10.0),
13
+ "code": (0.5, 8.0),
14
+ "summary": (1.0, 12.0),
15
+ "image": (1.0, 15.0),
16
+ "audio": (1.0, 15.0),
17
+ "iot": (1.0, 10.0),
18
+ }
19
+
20
+ class AIRiskEngine:
21
+ def __init__(self):
22
+ self._lock = threading.RLock()
23
+ self._priors: Dict[str, Tuple[float, float]] = DEFAULT_PRIORS.copy()
24
+ self._counts: Dict[str, Tuple[int, int]] = {cat: (0, 0) for cat in AI_CATEGORIES}
25
+
26
+ def get_posterior(self, category: str) -> Tuple[float, float]:
27
+ prior_a, prior_b = self._priors[category]
28
+ succ, trials = self._counts[category]
29
+ return prior_a + succ, prior_b + (trials - succ)
30
+
31
+ def risk_score(self, category: str) -> Dict[str, float]:
32
+ with self._lock:
33
+ alpha, beta = self.get_posterior(category)
34
+ mean = alpha / (alpha + beta)
35
+ samples = np.random.beta(alpha, beta, size=10000)
36
+ return {
37
+ "mean": float(mean),
38
+ "p5": float(np.percentile(samples, 5)),
39
+ "p50": float(np.percentile(samples, 50)),
40
+ "p95": float(np.percentile(samples, 95)),
41
+ }
42
+
43
+ def update_outcome(self, category: str, success: bool):
44
+ with self._lock:
45
+ succ, trials = self._counts[category]
46
+ trials += 1
47
+ if success:
48
+ succ += 1
49
+ self._counts[category] = (succ, trials)