Spaces:
Sleeping
Sleeping
Commit ·
9425538
1
Parent(s): a97b13a
fix: make inference.py robust against unhandled exceptions - Replace sys.exit(1) with graceful returns and error messages - Use .get() with defaults for all dict access in build_user_prompt - Add top-level try/except to catch ALL exceptions incl SystemExit - Add import guards for third-party packages (openai, requests) - Sanitize NaN/Inf values before json.dumps - Add env health check before starting tasks - Wrap every risky operation in try/except
Browse files- inference.py +170 -62
inference.py
CHANGED
|
@@ -10,13 +10,23 @@ Optional: ENV_URL (default: http://localhost:7860)
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
import json
|
|
|
|
| 13 |
import os
|
| 14 |
import sys
|
| 15 |
import time
|
| 16 |
import traceback
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# ═══════════════════════════════════════════════════════════════════════
|
| 22 |
# CONFIGURATION
|
|
@@ -85,63 +95,111 @@ Srv-001 is xlarge but only needs small capacity. Resizing to cut cost.
|
|
| 85 |
# LOGGING & HELPERS
|
| 86 |
# ═══════════════════════════════════════════════════════════════════════
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
def log_start(task: str, env: str, model: str):
|
| 89 |
-
print(f"[START] {
|
| 90 |
|
| 91 |
def log_step(step: int, action: str, reward: float, done: bool, error: str = None):
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
def log_end(success: bool, steps: int, score: float, rewards: list):
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
|
| 98 |
def build_user_prompt(obs: dict) -> str:
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
if
|
| 115 |
-
|
| 116 |
-
if
|
| 117 |
-
|
| 118 |
-
lines.append(
|
| 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 |
def parse_action(text: str) -> dict:
|
|
@@ -182,6 +240,9 @@ def call_env(method: str, endpoint: str, body: dict = None, params: dict = None)
|
|
| 182 |
except requests.RequestException as e:
|
| 183 |
print(f" ENV ERROR: {e}")
|
| 184 |
return {}
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
|
| 187 |
def call_llm(client: OpenAI, messages: list) -> str:
|
|
@@ -206,11 +267,22 @@ def call_llm(client: OpenAI, messages: list) -> str:
|
|
| 206 |
|
| 207 |
|
| 208 |
def run_task(client: OpenAI, task_id: str) -> float:
|
| 209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
if not reset_data:
|
|
|
|
| 211 |
return 0.0
|
| 212 |
|
| 213 |
session_id = reset_data.get("session_id")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
obs = reset_data
|
| 215 |
max_steps = obs.get("max_steps", 5)
|
| 216 |
final_score = 0.0
|
|
@@ -231,7 +303,9 @@ def run_task(client: OpenAI, task_id: str) -> float:
|
|
| 231 |
if action_log:
|
| 232 |
user_prompt += f"\n\n## Action History\nYou have taken {len(action_log)} actions so far:\n"
|
| 233 |
for past_step, (past_a, past_m) in enumerate(action_log):
|
| 234 |
-
|
|
|
|
|
|
|
| 235 |
messages.append({"role": "user", "content": user_prompt})
|
| 236 |
|
| 237 |
# Keep conversation manageable
|
|
@@ -242,8 +316,13 @@ def run_task(client: OpenAI, task_id: str) -> float:
|
|
| 242 |
messages.append({"role": "assistant", "content": raw_response})
|
| 243 |
|
| 244 |
action = parse_action(raw_response)
|
| 245 |
-
|
| 246 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
error = None
|
| 248 |
done = False
|
| 249 |
reward_val = 0.0
|
|
@@ -254,9 +333,10 @@ def run_task(client: OpenAI, task_id: str) -> float:
|
|
| 254 |
obs = step_result.get("observation", obs)
|
| 255 |
reward_dict = step_result.get("reward", {})
|
| 256 |
done = step_result.get("done", False)
|
| 257 |
-
final_score = reward_dict.get("score", 0.0)
|
| 258 |
reward_val = final_score
|
| 259 |
-
|
|
|
|
| 260 |
action_log.append((action, info_msg))
|
| 261 |
|
| 262 |
rewards.append(reward_val)
|
|
@@ -271,14 +351,31 @@ def run_task(client: OpenAI, task_id: str) -> float:
|
|
| 271 |
|
| 272 |
|
| 273 |
def main():
|
|
|
|
| 274 |
if not API_BASE_URL:
|
| 275 |
-
|
|
|
|
| 276 |
if not MODEL_NAME:
|
| 277 |
-
|
|
|
|
| 278 |
if not HF_TOKEN:
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
scores = {}
|
| 284 |
|
|
@@ -286,9 +383,20 @@ def main():
|
|
| 286 |
try:
|
| 287 |
score = run_task(client, task_id)
|
| 288 |
except Exception as e:
|
|
|
|
|
|
|
| 289 |
score = 0.0
|
| 290 |
scores[task_id] = score
|
| 291 |
|
|
|
|
|
|
|
| 292 |
|
| 293 |
if __name__ == "__main__":
|
| 294 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
import json
|
| 13 |
+
import math
|
| 14 |
import os
|
| 15 |
import sys
|
| 16 |
import time
|
| 17 |
import traceback
|
| 18 |
|
| 19 |
+
try:
|
| 20 |
+
import requests
|
| 21 |
+
except ImportError:
|
| 22 |
+
print("[FATAL] 'requests' package not installed. pip install requests")
|
| 23 |
+
sys.exit(0)
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
from openai import OpenAI
|
| 27 |
+
except ImportError:
|
| 28 |
+
print("[FATAL] 'openai' package not installed. pip install openai")
|
| 29 |
+
sys.exit(0)
|
| 30 |
|
| 31 |
# ═══════════════════════════════════════════════════════════════════════
|
| 32 |
# CONFIGURATION
|
|
|
|
| 95 |
# LOGGING & HELPERS
|
| 96 |
# ═══════════════════════════════════════════════════════════════════════
|
| 97 |
|
| 98 |
+
def _safe_json_dumps(obj):
|
| 99 |
+
"""json.dumps that handles NaN/Inf gracefully."""
|
| 100 |
+
try:
|
| 101 |
+
return json.dumps(obj, default=str)
|
| 102 |
+
except (ValueError, TypeError):
|
| 103 |
+
return str(obj)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
def log_start(task: str, env: str, model: str):
|
| 107 |
+
print(f"[START] {_safe_json_dumps({'task': task, 'env': env, 'model': model})}", flush=True)
|
| 108 |
|
| 109 |
def log_step(step: int, action: str, reward: float, done: bool, error: str = None):
|
| 110 |
+
try:
|
| 111 |
+
# Sanitise reward (json.dumps rejects NaN/Inf)
|
| 112 |
+
if isinstance(reward, float) and (math.isnan(reward) or math.isinf(reward)):
|
| 113 |
+
reward = 0.0
|
| 114 |
+
print(f"[STEP] {_safe_json_dumps({'step': step, 'action': action, 'reward': reward, 'done': done, 'error': error})}", flush=True)
|
| 115 |
+
except Exception as e:
|
| 116 |
+
print(f"[STEP] step={step} reward={reward} done={done} error={error} (log_step err: {e})", flush=True)
|
| 117 |
|
| 118 |
def log_end(success: bool, steps: int, score: float, rewards: list):
|
| 119 |
+
try:
|
| 120 |
+
if isinstance(score, float) and (math.isnan(score) or math.isinf(score)):
|
| 121 |
+
score = 0.0
|
| 122 |
+
clean_rewards = []
|
| 123 |
+
for r in rewards:
|
| 124 |
+
if isinstance(r, float) and (math.isnan(r) or math.isinf(r)):
|
| 125 |
+
clean_rewards.append(0.0)
|
| 126 |
+
else:
|
| 127 |
+
clean_rewards.append(r)
|
| 128 |
+
print(f"[END] {_safe_json_dumps({'success': success, 'steps': steps, 'score': score, 'rewards': clean_rewards})}", flush=True)
|
| 129 |
+
except Exception as e:
|
| 130 |
+
print(f"[END] success={success} steps={steps} score={score} (log_end err: {e})", flush=True)
|
| 131 |
|
| 132 |
|
| 133 |
def build_user_prompt(obs: dict) -> str:
|
| 134 |
+
"""Build a user prompt from the observation dict. Fully defensive with .get()."""
|
| 135 |
+
try:
|
| 136 |
+
lines = []
|
| 137 |
+
step_num = obs.get('step_number', '?')
|
| 138 |
+
max_steps = obs.get('max_steps', '?')
|
| 139 |
+
cost = obs.get('total_cost_per_hour', 0.0)
|
| 140 |
+
budget = obs.get('budget_per_hour', 0.0)
|
| 141 |
+
sla_v = obs.get('sla_violations', 0)
|
| 142 |
+
unassigned = obs.get('unassigned_workloads', 0)
|
| 143 |
+
|
| 144 |
+
lines.append(f"Step {step_num}/{max_steps} | "
|
| 145 |
+
f"Cost: ${cost:.2f}/hr | "
|
| 146 |
+
f"Budget: ${budget:.2f}/hr | "
|
| 147 |
+
f"SLA violations: {sla_v} | "
|
| 148 |
+
f"Unassigned: {unassigned}")
|
| 149 |
+
if obs.get("spot_eviction_occurred"):
|
| 150 |
+
lines.append("⚠️ SPOT EVICTION occurred this step!")
|
| 151 |
+
if obs.get("traffic_multiplier_active"):
|
| 152 |
+
lines.append("📈 Traffic spikes active (demand fluctuates each step)")
|
| 153 |
+
lines.append(f"Message: {obs.get('message', 'N/A')}")
|
| 154 |
+
|
| 155 |
+
lines.append("\n## Servers")
|
| 156 |
+
for s in obs.get("servers", []):
|
| 157 |
+
badges = ""
|
| 158 |
+
if s.get("is_spot"):
|
| 159 |
+
badges += " [SPOT]"
|
| 160 |
+
if s.get("is_overloaded"):
|
| 161 |
+
badges += " [OVERLOADED]"
|
| 162 |
+
cpu_util = s.get('cpu_utilization', 0.0)
|
| 163 |
+
ram_util = s.get('ram_utilization', 0.0)
|
| 164 |
+
disk_util = s.get('disk_utilization', 0.0)
|
| 165 |
+
net_util = s.get('network_utilization', 0.0)
|
| 166 |
+
lines.append(
|
| 167 |
+
f" {s.get('server_id', '?')} ({s.get('instance_type', '?')}) "
|
| 168 |
+
f"CPU:{s.get('cpu_cores', 0)}c@{cpu_util:.0%} "
|
| 169 |
+
f"RAM:{s.get('ram_gb', 0)}GB@{ram_util:.0%} "
|
| 170 |
+
f"Disk:{s.get('disk_iops', 0)}iops@{disk_util:.0%} "
|
| 171 |
+
f"Net:{s.get('network_gbps', 0)}Gbps@{net_util:.0%} "
|
| 172 |
+
f"${s.get('cost_per_hour', 0)}/hr "
|
| 173 |
+
f"wl: {s.get('assigned_workloads', [])}{badges}"
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
lines.append("\n## Workloads")
|
| 177 |
+
for w in obs.get("workloads", []):
|
| 178 |
+
assigned = w.get("assigned_server")
|
| 179 |
+
cur_lat = w.get("current_latency_ms", 0.0)
|
| 180 |
+
sla_lat = w.get("sla_latency_ms", 1.0)
|
| 181 |
+
if assigned is None:
|
| 182 |
+
status = "DOWN"
|
| 183 |
+
elif cur_lat > sla_lat:
|
| 184 |
+
status = "BREACH"
|
| 185 |
+
else:
|
| 186 |
+
status = "OK"
|
| 187 |
+
crit = " [CRITICAL]" if w.get("is_critical") else ""
|
| 188 |
+
deps = f" depends→{w.get('dependencies', [])}" if w.get("dependencies") else ""
|
| 189 |
+
lines.append(
|
| 190 |
+
f" {w.get('workload_id', '?')} \"{w.get('name', '?')}\"{crit} "
|
| 191 |
+
f"needs {w.get('required_cpu', 0)}cpu/{w.get('required_ram', 0)}GB/"
|
| 192 |
+
f"{w.get('required_disk_iops', 0)}iops/{w.get('required_net_gbps', 0)}Gbps "
|
| 193 |
+
f"latency:{cur_lat:.0f}ms/sla:{sla_lat:.0f}ms "
|
| 194 |
+
f"-> {status} on:{assigned or 'NONE'}{deps}"
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
lines.append("\nRespond with a single JSON action:")
|
| 198 |
+
return "\n".join(lines)
|
| 199 |
+
except Exception as e:
|
| 200 |
+
# Fallback: return a minimal prompt so the agent can still act
|
| 201 |
+
print(f" WARNING: build_user_prompt failed: {e}", flush=True)
|
| 202 |
+
return f"Observation (raw): {str(obs)[:2000]}\n\nRespond with a single JSON action:"
|
| 203 |
|
| 204 |
|
| 205 |
def parse_action(text: str) -> dict:
|
|
|
|
| 240 |
except requests.RequestException as e:
|
| 241 |
print(f" ENV ERROR: {e}")
|
| 242 |
return {}
|
| 243 |
+
except Exception as e:
|
| 244 |
+
print(f" ENV UNEXPECTED ERROR: {e}")
|
| 245 |
+
return {}
|
| 246 |
|
| 247 |
|
| 248 |
def call_llm(client: OpenAI, messages: list) -> str:
|
|
|
|
| 267 |
|
| 268 |
|
| 269 |
def run_task(client: OpenAI, task_id: str) -> float:
|
| 270 |
+
"""Run a single task episode. Returns the final score (0.0 on failure)."""
|
| 271 |
+
try:
|
| 272 |
+
reset_data = call_env("POST", "/reset", {"task_id": task_id})
|
| 273 |
+
except Exception as e:
|
| 274 |
+
print(f" RESET EXCEPTION for task {task_id}: {e}")
|
| 275 |
+
return 0.0
|
| 276 |
+
|
| 277 |
if not reset_data:
|
| 278 |
+
print(f" RESET returned empty for task {task_id}")
|
| 279 |
return 0.0
|
| 280 |
|
| 281 |
session_id = reset_data.get("session_id")
|
| 282 |
+
if not session_id:
|
| 283 |
+
print(f" RESET did not return session_id for task {task_id}")
|
| 284 |
+
return 0.0
|
| 285 |
+
|
| 286 |
obs = reset_data
|
| 287 |
max_steps = obs.get("max_steps", 5)
|
| 288 |
final_score = 0.0
|
|
|
|
| 303 |
if action_log:
|
| 304 |
user_prompt += f"\n\n## Action History\nYou have taken {len(action_log)} actions so far:\n"
|
| 305 |
for past_step, (past_a, past_m) in enumerate(action_log):
|
| 306 |
+
past_action_type = past_a.get('action_type', '?') if isinstance(past_a, dict) else '?'
|
| 307 |
+
past_msg = str(past_m)[:70] if past_m else ''
|
| 308 |
+
user_prompt += f" Step {past_step+1}: {past_action_type} -> {past_msg}\n"
|
| 309 |
messages.append({"role": "user", "content": user_prompt})
|
| 310 |
|
| 311 |
# Keep conversation manageable
|
|
|
|
| 316 |
messages.append({"role": "assistant", "content": raw_response})
|
| 317 |
|
| 318 |
action = parse_action(raw_response)
|
| 319 |
+
|
| 320 |
+
try:
|
| 321 |
+
step_result = call_env("POST", "/step", action, {"session_id": session_id})
|
| 322 |
+
except Exception as e:
|
| 323 |
+
print(f" STEP EXCEPTION: {e}")
|
| 324 |
+
step_result = {}
|
| 325 |
+
|
| 326 |
error = None
|
| 327 |
done = False
|
| 328 |
reward_val = 0.0
|
|
|
|
| 333 |
obs = step_result.get("observation", obs)
|
| 334 |
reward_dict = step_result.get("reward", {})
|
| 335 |
done = step_result.get("done", False)
|
| 336 |
+
final_score = reward_dict.get("score", 0.0) if isinstance(reward_dict, dict) else 0.0
|
| 337 |
reward_val = final_score
|
| 338 |
+
info = step_result.get("info", {})
|
| 339 |
+
info_msg = info.get("action_result", "") if isinstance(info, dict) else str(info)
|
| 340 |
action_log.append((action, info_msg))
|
| 341 |
|
| 342 |
rewards.append(reward_val)
|
|
|
|
| 351 |
|
| 352 |
|
| 353 |
def main():
|
| 354 |
+
"""Main entry point with comprehensive error handling."""
|
| 355 |
if not API_BASE_URL:
|
| 356 |
+
print("[ERROR] API_BASE_URL environment variable is not set.", flush=True)
|
| 357 |
+
return
|
| 358 |
if not MODEL_NAME:
|
| 359 |
+
print("[ERROR] MODEL_NAME environment variable is not set.", flush=True)
|
| 360 |
+
return
|
| 361 |
if not HF_TOKEN:
|
| 362 |
+
print("[ERROR] HF_TOKEN environment variable is not set.", flush=True)
|
| 363 |
+
return
|
| 364 |
+
|
| 365 |
+
print(f"[CONFIG] ENV_URL={ENV_URL}, MODEL={MODEL_NAME}, API_BASE={API_BASE_URL[:50]}...", flush=True)
|
| 366 |
|
| 367 |
+
# Verify env container is reachable before starting
|
| 368 |
+
try:
|
| 369 |
+
health = requests.get(f"{ENV_URL}/", timeout=15)
|
| 370 |
+
print(f"[CONFIG] Env health check: {health.status_code}", flush=True)
|
| 371 |
+
except Exception as e:
|
| 372 |
+
print(f"[WARN] Env health check failed: {e}. Proceeding anyway...", flush=True)
|
| 373 |
+
|
| 374 |
+
try:
|
| 375 |
+
client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)
|
| 376 |
+
except Exception as e:
|
| 377 |
+
print(f"[ERROR] Failed to create OpenAI client: {e}", flush=True)
|
| 378 |
+
return
|
| 379 |
|
| 380 |
scores = {}
|
| 381 |
|
|
|
|
| 383 |
try:
|
| 384 |
score = run_task(client, task_id)
|
| 385 |
except Exception as e:
|
| 386 |
+
print(f"[ERROR] Task '{task_id}' crashed: {e}", flush=True)
|
| 387 |
+
traceback.print_exc()
|
| 388 |
score = 0.0
|
| 389 |
scores[task_id] = score
|
| 390 |
|
| 391 |
+
print(f"[RESULTS] {_safe_json_dumps(scores)}", flush=True)
|
| 392 |
+
|
| 393 |
|
| 394 |
if __name__ == "__main__":
|
| 395 |
+
try:
|
| 396 |
+
main()
|
| 397 |
+
except SystemExit:
|
| 398 |
+
pass # Don't let sys.exit propagate as unhandled
|
| 399 |
+
except Exception as e:
|
| 400 |
+
print(f"[FATAL] Unhandled exception in main: {e}", flush=True)
|
| 401 |
+
traceback.print_exc()
|
| 402 |
+
# Exit with 0 so the validator doesn't see a non-zero exit code
|