Upload aco/learned_router.py with huggingface_hub
Browse files- aco/learned_router.py +131 -208
aco/learned_router.py
CHANGED
|
@@ -1,228 +1,151 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
import json
|
|
|
|
| 8 |
import pickle
|
| 9 |
from typing import Dict, List, Optional, Tuple
|
| 10 |
from dataclasses import dataclass
|
| 11 |
from collections import defaultdict
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
"num_words": len(user_request.split()),
|
| 43 |
-
"has_code": any(kw in req_lower for kw in ["python", "javascript", "code", "function", "bug", "debug", "refactor", "implement", "test"]),
|
| 44 |
-
"has_legal": any(kw in req_lower for kw in ["contract", "legal", "compliance", "gdpr", "privacy", "policy", "regulatory"]),
|
| 45 |
-
"has_research": any(kw in req_lower for kw in ["research", "find sources", "literature", "investigate", "compare", "analyze"]),
|
| 46 |
-
"has_tools": any(kw in req_lower for kw in ["search", "fetch", "retrieve", "query", "api", "database", "scrape"]),
|
| 47 |
-
"has_long_horizon": any(kw in req_lower for kw in ["plan", "project", "roadmap", "orchestrate", "multi-step"]),
|
| 48 |
-
}
|
| 49 |
|
| 50 |
-
#
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
success_count = sum(1 for t in similar if t.get("final_outcome") == "success")
|
| 54 |
-
features["prior_success_rate"] = success_count / len(similar)
|
| 55 |
-
features["has_prior_failures"] = any(t.get("final_outcome") == "failure" for t in similar[-5:])
|
| 56 |
-
else:
|
| 57 |
-
features["prior_success_rate"] = 0.5
|
| 58 |
-
features["has_prior_failures"] = False
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def _score_tier(self, features: Dict[str, float], tier: int) -> float:
|
| 63 |
-
"""Score a tier given features. Higher is better."""
|
| 64 |
-
if not self.trained:
|
| 65 |
-
# Heuristic scoring before training
|
| 66 |
-
base_score = {1: 0.3, 2: 0.5, 3: 0.7, 4: 0.85, 5: 0.9}.get(tier, 0.5)
|
| 67 |
-
|
| 68 |
-
# Adjust by task complexity signals
|
| 69 |
-
if features["has_legal"] and tier < 4:
|
| 70 |
-
base_score -= 0.4
|
| 71 |
-
if features["has_code"] and tier < 3:
|
| 72 |
-
base_score -= 0.2
|
| 73 |
-
if features["has_research"] and tier < 3:
|
| 74 |
-
base_score -= 0.15
|
| 75 |
-
if features["has_long_horizon"] and tier < 3:
|
| 76 |
-
base_score -= 0.2
|
| 77 |
-
|
| 78 |
-
# Adjust by history
|
| 79 |
-
if features["has_prior_failures"] and tier < 3:
|
| 80 |
-
base_score -= 0.3
|
| 81 |
-
if features["prior_success_rate"] > 0.8 and tier > 2:
|
| 82 |
-
base_score += 0.1
|
| 83 |
-
|
| 84 |
-
return base_score
|
| 85 |
-
|
| 86 |
-
# Trained scoring
|
| 87 |
-
score = self.task_type_bias.get(str(tier), 0.5)
|
| 88 |
-
for feat_name, feat_val in features.items():
|
| 89 |
-
weight_key = f"{feat_name}_tier_{tier}"
|
| 90 |
-
score += self.weights.get(weight_key, 0.0) * (1.0 if feat_val else 0.0)
|
| 91 |
-
return score
|
| 92 |
-
|
| 93 |
-
def predict_tier(self, user_request: str, task_type: str, history: List[Dict] = None) -> Tuple[int, float]:
|
| 94 |
-
"""Predict optimal model tier and confidence."""
|
| 95 |
-
history = history or []
|
| 96 |
-
features = self._extract_features(user_request, task_type, history)
|
| 97 |
-
|
| 98 |
-
best_tier = 3
|
| 99 |
-
best_score = -float("inf")
|
| 100 |
-
|
| 101 |
-
for tier in [1, 2, 3, 4, 5]:
|
| 102 |
-
score = self._score_tier(features, tier)
|
| 103 |
-
if score > best_score:
|
| 104 |
-
best_score = score
|
| 105 |
-
best_tier = tier
|
| 106 |
-
|
| 107 |
-
confidence = min(best_score, 1.0)
|
| 108 |
-
return best_tier, confidence
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
tier_counts = defaultdict(lambda: defaultdict(int))
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
outcome = trace.get("final_outcome", "failure")
|
| 118 |
-
difficulty = trace.get("metadata", {}).get("difficulty", 3)
|
| 119 |
-
actual_tier = trace.get("metadata", {}).get("actual_tier", 3)
|
| 120 |
-
|
| 121 |
-
# Optimal tier is the minimum tier that would succeed
|
| 122 |
-
if outcome == "success":
|
| 123 |
-
optimal = actual_tier # This tier succeeded
|
| 124 |
-
else:
|
| 125 |
-
optimal = min(actual_tier + 1, 5) # Need higher tier
|
| 126 |
-
|
| 127 |
-
# Extract features
|
| 128 |
-
req = trace.get("user_request", "")
|
| 129 |
-
features = self._extract_features(req, task_type, [])
|
| 130 |
-
|
| 131 |
-
# Count successes per feature+tier combination
|
| 132 |
-
for feat_name, feat_val in features.items():
|
| 133 |
-
if isinstance(feat_val, bool) and feat_val:
|
| 134 |
-
tier_counts[feat_name][optimal] += 1
|
| 135 |
-
|
| 136 |
-
tier_counts["_overall"][optimal] += 1
|
| 137 |
|
| 138 |
-
#
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
self.task_type_bias[str(tier)] = count / total
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
weight_key = f"{feat_name}_tier_{tier}"
|
| 153 |
-
# Positive if this tier is common when feature is present
|
| 154 |
-
self.weights[weight_key] = (tier_dist.get(tier, 0) / total_feat) - self.task_type_bias.get(str(tier), 0.1)
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
with open(path, "wb") as f:
|
| 161 |
-
pickle.dump({"weights": self.weights, "bias": self.task_type_bias, "trained": self.trained}, f)
|
| 162 |
-
|
| 163 |
-
def load(self, path: str) -> None:
|
| 164 |
-
with open(path, "rb") as f:
|
| 165 |
-
data = pickle.load(f)
|
| 166 |
-
self.weights = data["weights"]
|
| 167 |
-
self.task_type_bias = data["bias"]
|
| 168 |
-
self.trained = data["trained"]
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
class RouterDatasetBuilder:
|
| 172 |
-
"""Builds training datasets from traces for learned router training."""
|
| 173 |
-
|
| 174 |
-
@staticmethod
|
| 175 |
-
def from_traces(traces: List[Dict]) -> List[Dict]:
|
| 176 |
-
"""Convert traces to (features, optimal_tier) training examples."""
|
| 177 |
-
examples = []
|
| 178 |
-
for trace in traces:
|
| 179 |
-
difficulty = trace.get("metadata", {}).get("difficulty", 3)
|
| 180 |
-
actual_tier = trace.get("metadata", {}).get("actual_tier", 3)
|
| 181 |
-
outcome = trace.get("final_outcome", "failure")
|
| 182 |
-
|
| 183 |
-
# Optimal tier
|
| 184 |
-
if outcome == "success":
|
| 185 |
-
optimal = actual_tier
|
| 186 |
-
else:
|
| 187 |
-
optimal = min(actual_tier + 1, 5)
|
| 188 |
-
|
| 189 |
-
# Simple feature extraction
|
| 190 |
-
req = trace.get("user_request", "").lower()
|
| 191 |
-
features = {
|
| 192 |
-
"length": len(req),
|
| 193 |
-
"has_code": any(kw in req for kw in ["python", "code", "function", "bug", "debug"]),
|
| 194 |
-
"has_legal": any(kw in req for kw in ["contract", "legal", "compliance", "gdpr"]),
|
| 195 |
-
"has_research": any(kw in req for kw in ["research", "find sources", "literature"]),
|
| 196 |
-
"task_type": trace.get("task_type", "unknown"),
|
| 197 |
-
"difficulty": difficulty,
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
examples.append({"features": features, "optimal_tier": optimal, "outcome": outcome})
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
def compute_oracle_savings(traces: List[Dict]) -> Dict[str, float]:
|
| 206 |
-
"""Compute what an oracle router (perfect tier selection) would save."""
|
| 207 |
-
total_cost = 0.0
|
| 208 |
-
oracle_cost = 0.0
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
|
|
|
|
|
|
| 222 |
|
| 223 |
-
return
|
| 224 |
-
|
| 225 |
-
"
|
| 226 |
-
"
|
| 227 |
-
|
| 228 |
-
|
|
|
|
| 1 |
+
"""Trained Production Router - Replaces heuristic routing.
|
| 2 |
|
| 3 |
+
Architecture: difficulty-first + ML confirmation + safety floors.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
from aco.learned_router import TrainedRouter
|
| 7 |
+
|
| 8 |
+
router = TrainedRouter.from_pretrained("narcolepticchicken/agent-cost-optimizer")
|
| 9 |
+
tier, confidence = router.predict("Write a Python function", "coding", difficulty=3)
|
| 10 |
"""
|
| 11 |
|
| 12 |
import json
|
| 13 |
+
import os
|
| 14 |
import pickle
|
| 15 |
from typing import Dict, List, Optional, Tuple
|
| 16 |
from dataclasses import dataclass
|
| 17 |
from collections import defaultdict
|
| 18 |
|
| 19 |
+
try:
|
| 20 |
+
import numpy as np
|
| 21 |
+
import xgboost as xgb
|
| 22 |
+
HAS_ML = True
|
| 23 |
+
except ImportError:
|
| 24 |
+
HAS_ML = False
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
TASK_TYPES = ["quick_answer","coding","research","document_drafting",
|
| 28 |
+
"legal_regulated","tool_heavy","retrieval_heavy",
|
| 29 |
+
"long_horizon","unknown_ambiguous"]
|
| 30 |
+
TT2IDX = {t:i for i,t in enumerate(TASK_TYPES)}
|
| 31 |
+
|
| 32 |
+
CODE_KW = ["python","javascript","code","function","bug","debug","refactor",
|
| 33 |
+
"implement","test","compile","runtime","class","module","async","thread"]
|
| 34 |
+
LEGAL_KW = ["contract","legal","compliance","gdpr","privacy","policy","regulatory","liability"]
|
| 35 |
+
RESEARCH_KW = ["research","find sources","literature","investigate","compare","analyze","survey"]
|
| 36 |
+
TOOL_KW = ["search","fetch","retrieve","query","api","database","scrape","aggregate"]
|
| 37 |
+
LONG_KW = ["plan","project","roadmap","orchestrate","multi-step","migrate","pipeline","deploy"]
|
| 38 |
+
MATH_KW = ["calculate","compute","solve","equation","formula","optimize","probability"]
|
| 39 |
+
|
| 40 |
+
# Default safety floors per task type
|
| 41 |
+
TASK_FLOOR = {
|
| 42 |
+
"legal_regulated":4,"long_horizon":3,"research":3,"coding":3,
|
| 43 |
+
"unknown_ambiguous":3,"quick_answer":1,"document_drafting":2,
|
| 44 |
+
"tool_heavy":2,"retrieval_heavy":2,
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TrainedRouter:
|
| 49 |
+
"""Production trained router: difficulty-first + ML confirmation + safety floors."""
|
| 50 |
+
|
| 51 |
+
def __init__(self, tier_clfs: Dict, feat_keys: List[str],
|
| 52 |
+
tier_config: Dict, escalation_threshold: float = 0.55):
|
| 53 |
+
self.tier_clfs = tier_clfs
|
| 54 |
+
self.feat_keys = feat_keys
|
| 55 |
+
self.tier_config = tier_config
|
| 56 |
+
self.tier_cost = {int(k):v for k,v in tier_config["tier_cost"].items()}
|
| 57 |
+
self.task_floor = tier_config.get("task_floor", TASK_FLOOR)
|
| 58 |
+
self.escalation_threshold = escalation_threshold
|
| 59 |
+
self._trained = True
|
| 60 |
+
|
| 61 |
+
def extract_features(self, request: str, task_type: str, difficulty: int = 3) -> Dict:
|
| 62 |
+
r = request.lower()
|
| 63 |
+
f = {"req_len":len(request),"num_words":len(request.split()),
|
| 64 |
+
"has_code":int(any(k in r for k in CODE_KW)),
|
| 65 |
+
"n_code":sum(1 for k in CODE_KW if k in r),
|
| 66 |
+
"has_legal":int(any(k in r for k in LEGAL_KW)),
|
| 67 |
+
"n_legal":sum(1 for k in LEGAL_KW if k in r),
|
| 68 |
+
"has_research":int(any(k in r for k in RESEARCH_KW)),
|
| 69 |
+
"n_research":sum(1 for k in RESEARCH_KW if k in r),
|
| 70 |
+
"has_tool":int(any(k in r for k in TOOL_KW)),
|
| 71 |
+
"n_tool":sum(1 for k in TOOL_KW if k in r),
|
| 72 |
+
"has_long":int(any(k in r for k in LONG_KW)),
|
| 73 |
+
"has_math":int(any(k in r for k in MATH_KW)),
|
| 74 |
+
"tt_idx":TT2IDX.get(task_type,8),"difficulty":difficulty}
|
| 75 |
+
for tt in TASK_TYPES:
|
| 76 |
+
f[f"tt_{tt}"] = int(task_type == tt)
|
| 77 |
+
return f
|
| 78 |
+
|
| 79 |
+
def _feats_to_vec(self, feats: Dict):
|
| 80 |
+
import numpy as np
|
| 81 |
+
return np.array([float(feats.get(k, 0.0)) for k in self.feat_keys], dtype=np.float32)
|
| 82 |
+
|
| 83 |
+
def predict(self, request: str, task_type: str, difficulty: int = 3,
|
| 84 |
+
escalation_threshold: Optional[float] = None) -> Tuple[int, float]:
|
| 85 |
+
"""Predict optimal tier using difficulty-first + ML confirmation.
|
| 86 |
+
|
| 87 |
+
Returns: (tier, confidence)
|
| 88 |
+
"""
|
| 89 |
+
threshold = escalation_threshold or self.escalation_threshold
|
| 90 |
|
| 91 |
+
# Step 1: difficulty -> base_tier
|
| 92 |
+
base_tier = min(difficulty + 1, 5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
+
# Step 2: apply safety floor
|
| 95 |
+
floor = self.task_floor.get(task_type, 2)
|
| 96 |
+
base_tier = max(base_tier, floor)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
if not HAS_ML or not self._trained:
|
| 99 |
+
return base_tier, 0.6
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
# Step 3: ML confirmation
|
| 102 |
+
feats = self.extract_features(request, task_type, difficulty)
|
| 103 |
+
x = self._feats_to_vec(feats).reshape(1, -1)
|
|
|
|
| 104 |
|
| 105 |
+
p_success = self.tier_clfs[base_tier].predict_proba(x)[0, 1]
|
| 106 |
+
confidence = p_success
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
# Step 4: escalate if P(success) too low
|
| 109 |
+
while p_success < threshold and base_tier < 5:
|
| 110 |
+
base_tier += 1
|
| 111 |
+
p_success = self.tier_clfs[base_tier].predict_proba(x)[0, 1]
|
| 112 |
+
confidence = p_success
|
|
|
|
| 113 |
|
| 114 |
+
return base_tier, float(confidence)
|
| 115 |
+
|
| 116 |
+
@classmethod
|
| 117 |
+
def from_pretrained(cls, repo_id: str, escalation_threshold: float = 0.55,
|
| 118 |
+
cache_dir: Optional[str] = None):
|
| 119 |
+
"""Load trained router from HuggingFace Hub."""
|
| 120 |
+
from huggingface_hub import hf_hub_download
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
bundle_path = hf_hub_download(
|
| 123 |
+
repo_id=repo_id, filename="router_models/router_bundle.pkl",
|
| 124 |
+
cache_dir=cache_dir,
|
| 125 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
with open(bundle_path, "rb") as f:
|
| 128 |
+
import pickle
|
| 129 |
+
bundle = pickle.load(f)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
return cls(
|
| 132 |
+
tier_clfs={int(k): v for k, v in bundle["tier_clfs"].items()},
|
| 133 |
+
feat_keys=bundle["feat_keys"],
|
| 134 |
+
tier_config=bundle["tier_config"],
|
| 135 |
+
escalation_threshold=escalation_threshold,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
@classmethod
|
| 139 |
+
def from_local(cls, model_dir: str, escalation_threshold: float = 0.55):
|
| 140 |
+
"""Load from local directory."""
|
| 141 |
+
bundle_path = os.path.join(model_dir, "router_bundle.pkl")
|
| 142 |
+
with open(bundle_path, "rb") as f:
|
| 143 |
+
import pickle
|
| 144 |
+
bundle = pickle.load(f)
|
| 145 |
|
| 146 |
+
return cls(
|
| 147 |
+
tier_clfs={int(k): v for k, v in bundle["tier_clfs"].items()},
|
| 148 |
+
feat_keys=bundle["feat_keys"],
|
| 149 |
+
tier_config=bundle["tier_config"],
|
| 150 |
+
escalation_threshold=escalation_threshold,
|
| 151 |
+
)
|