File size: 10,140 Bytes
f10bdc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""MVPKILLCADDSS β€” Model Manager
Load Balancer + Health Checker + Circuit Breaker a 3 private CAD modellhez"""
import asyncio
import time
import httpx
import json
import os
from datetime import datetime

# ═══════════════ Model Registry ════════════════════════════

MODELS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "models")

def load_model_configs():
    configs = {}
    for model_id in ["cad_llm1", "cad_llm2", "cad_llm3"]:
        config_path = os.path.join(MODELS_DIR, model_id, "config.json")
        try:
            with open(config_path) as f:
                configs[model_id] = json.load(f)
        except Exception:
            configs[model_id] = {
                "name": model_id, "priority": 1, "port": 8001,
                "domains": ["altalanos"], "max_concurrent": 3
            }
    return configs

class ModelManager:
    def __init__(self):
        self.configs = load_model_configs()
        self.models = {}
        for mid, cfg in self.configs.items():
            self.models[mid] = {
                "id": mid,
                "name": cfg.get("name", mid),
                "url": cfg.get("url", f"http://localhost:{cfg.get('port', 8001)}"),
                "priority": cfg.get("priority", 1),
                "domains": cfg.get("domains", []),
                "domain_names": cfg.get("domain_names", []),
                "max_concurrent": cfg.get("max_concurrent", 3),
                "weight": cfg.get("weight", 100),
                "hf_token": cfg.get("hf_token", os.getenv("HF_TOKEN", "")),
                "hf_space": cfg.get("huggingface_space", ""),
                # Runtime status
                "healthy": None,
                "load": 0,
                "concurrent": 0,
                "total_requests": 0,
                "total_failures": 0,
                "avg_response_time": 0,
                "last_response_time": 0,
                "last_check": None,
                "uptime_since": None,
                "consecutive_failures": 0,
                "circuit_broken": False,
                "circuit_broken_until": 0,
                "status": "unknown",
            }

    # ═══════ Model Selection ═══════

    def select_model(self, domains: list[str]) -> tuple[str, dict] | tuple[None, None]:
        """Domain + terhelΓ©s + health alapjΓ‘n legjobb modell vΓ‘lasztΓ‘sa"""
        candidates = []

        for mid, m in self.models.items():
            if m["circuit_broken"] and time.time() < m["circuit_broken_until"]:
                continue
            if not m["healthy"] and m["healthy"] is not None:
                continue

            # Domain match score (how many domains overlap)
            overlap = set(d.lower() for d in domains) & set(d.lower() for d in m["domains"])
            domain_score = len(overlap)

            # Load score (inverse β€” prefer less loaded)
            load_score = max(0, 100 - m["load"])

            # Priority score (lower number = higher priority, so invert)
            priority_score = max(0, 4 - m["priority"])

            if domain_score > 0 or m["priority"] == 1:
                candidates.append({
                    "id": mid,
                    "model": m,
                    "score": domain_score * 40 + load_score * 0.3 + priority_score * 30,
                })

        if not candidates:
            # Fallback: any healthy model
            for mid, m in self.models.items():
                if m["healthy"] and not m["circuit_broken"]:
                    return mid, m
            return None, None

        # Sort by score descending
        candidates.sort(key=lambda x: x["score"], reverse=True)

        # Check if top candidate is overloaded
        top = candidates[0]
        if top["model"]["load"] > 80 and len(candidates) > 1:
            # Use second best if top is overloaded
            return candidates[1]["id"], candidates[1]["model"]

        return top["id"], top["model"]

    # ═══════ Request Recording ═══════

    def record_request(self, model_id: str, success: bool, response_time: float):
        if model_id not in self.models:
            return
        m = self.models[model_id]
        m["total_requests"] += 1
        m["last_response_time"] = response_time
        if success:
            m["consecutive_failures"] = 0
            # Exponential moving average
            alpha = 0.3
            m["avg_response_time"] = (
                m["avg_response_time"] * (1 - alpha) + response_time * alpha
            )
        else:
            m["total_failures"] += 1
            m["consecutive_failures"] += 1
            # Circuit breaker: 3 consecutive failures
            if m["consecutive_failures"] >= 3:
                m["circuit_broken"] = True
                m["circuit_broken_until"] = time.time() + 30
                m["status"] = "circuit_broken"

    # ═══════ Health Check Loop ═══════

    async def health_check_loop(self):
        """5 mΓ‘sodpercenkΓ©nt ellenΕ‘rzi mind a 3 modellt"""
        while True:
            for mid, m in self.models.items():
                await self._check_one(mid);
            await asyncio.sleep(5)

    async def _check_one(self, model_id: str):
        m = self.models[model_id]
        # Check if circuit breaker should reset
        if m["circuit_broken"] and time.time() >= m["circuit_broken_until"]:
            m["circuit_broken"] = False
            m["consecutive_failures"] = 0
            m["status"] = "recovering"

        try:
            async with httpx.AsyncClient(timeout=5) as client:
                resp = await client.get(f"{m['url']}/health")
                if resp.status_code == 200:
                    if not m["healthy"]:
                        m["uptime_since"] = datetime.utcnow().isoformat()
                    m["healthy"] = True
                    m["status"] = "healthy"
                    m["last_check"] = datetime.utcnow().isoformat()

                    # Get detailed stats if available
                    try:
                        r2 = await client.get(f"{m['url']}/config")
                        if r2.status_code == 200:
                            cfg = r2.json()
                            m["domain_names"] = cfg.get("domain_names", m["domain_names"])
                    except Exception:
                        pass
                else:
                    m["healthy"] = False
                    m["status"] = "unhealthy"
        except Exception:
            m["healthy"] = False
            m["status"] = "unreachable"
            m["last_check"] = datetime.utcnow().isoformat()

        # Calculate load (concurrent / max_concurrent * 100)
        m["load"] = min(100, int(m["concurrent"] / max(1, m["max_concurrent"]) * 100))

    # ═══════ Status Report ═══════

    def get_status(self) -> list[dict]:
        result = []
        for mid, m in self.models.items():
            result.append({
                "id": mid,
                "name": m["name"],
                "url": m["url"],
                "priority": m["priority"],
                "domains": m["domains"],
                "domain_names": m["domain_names"],
                "healthy": m["healthy"],
                "status": m["status"],
                "load_percent": m["load"],
                "concurrent": m["concurrent"],
                "max_concurrent": m["max_concurrent"],
                "total_requests": m["total_requests"],
                "total_failures": m["total_failures"],
                "avg_response_time_ms": round(m["avg_response_time"] * 1000, 1),
                "last_response_time_ms": round(m["last_response_time"] * 1000, 1),
                "last_check": m["last_check"],
                "uptime_since": m["uptime_since"],
                "circuit_broken": m["circuit_broken"],
            })
        return result

    def get_stats(self) -> dict:
        total_req = sum(m["total_requests"] for m in self.models.values())
        total_fail = sum(m["total_failures"] for m in self.models.values())
        healthy_count = sum(1 for m in self.models.values() if m["healthy"])
        return {
            "models_total": len(self.models),
            "models_healthy": healthy_count,
            "total_requests": total_req,
            "total_failures": total_fail,
            "success_rate": round((1 - total_fail / max(1, total_req)) * 100, 1) if total_req else 0,
            "timestamp": datetime.utcnow().isoformat(),
        }


    # ═══════ Chat with Model ═══════

    async def chat_with_model(self, model_id: str, message: str, history: list[dict] = []) -> dict:
        """TovΓ‘bbΓ­tja a chat kΓ©rΓ©st a Space /chat endpointjΓ‘ra"""
        if model_id not in self.models:
            return {"error": "Model not found"}
        m = self.models[model_id]
        t0 = time.time()
        try:
            headers = {}
            if m["hf_token"]:
                headers["Authorization"] = f"Bearer {m['hf_token']}"
            async with httpx.AsyncClient(timeout=120) as client:
                resp = await client.post(
                    f"{m['url']}/chat",
                    json={"message": message, "history": history},
                    headers=headers,
                )
                elapsed = time.time() - t0
                if resp.status_code == 200:
                    self.record_request(model_id, True, elapsed)
                    return resp.json()
                else:
                    self.record_request(model_id, False, elapsed)
                    return {"error": f"Status {resp.status_code}", "raw": resp.text[:200]}
        except Exception as e:
            elapsed = time.time() - t0
            self.record_request(model_id, False, elapsed)
            return {"error": str(e)}

# ═══════════ Global Instance ══════════════════════════════

model_manager = ModelManager()