#!/usr/bin/env python3 """ ACEA Inference Script Runs an OpenAI LLM agent through all three task difficulties. Logs strictly follow: [START], [STEP], [END] """ import os import sys import json import time import logging import random from typing import Dict, Any from groq import Groq from env.environment import ACEAEnvironment from env.models import Action, ActionType, Priority # ─── Logging ─────────────────────────────────────────────────────── logging.basicConfig( level=logging.INFO, format="%(asctime)s %(message)s", handlers=[logging.StreamHandler(sys.stdout)], ) logger = logging.getLogger("ACEA-Inference") # deterministic internal state for reproducible logs and environment sampling random.seed(42) # ─── Groq Client ────────────────────────────────────────────────── client = Groq(api_key=os.environ.get("GROQ_API_KEY")) MODEL = os.environ.get("GROQ_MODEL", "llama-3.1-8b-instant") SYSTEM_PROMPT = """ You are an expert Site Reliability Engineer (SRE) and Incident Commander. You are operating inside an enterprise environment simulation and must respond to alerts, logs, and incidents. Your goal is to resolve incidents as quickly and accurately as possible. Each turn you receive the current environment observation and must return ONE action. Available action types: - restart_service: Restart a failing service or container - scale_system: Add capacity (nodes, replicas) to handle load - debug_issue: Investigate root cause before acting - notify_user: Send comms to affected customers or escalate to stakeholders - ignore: Take no action (use sparingly — only when an alert is clearly a false positive) - isolate_system: Network-isolate a compromised or failing component You MUST respond ONLY with valid JSON in this exact format: { "type": "", "target": "", "priority": <1-4 integer where 4=CRITICAL>, "reasoning": "", "parameters": {} } Think step by step. Consider: 1. What is the highest-severity incident? 2. What action would most directly resolve it? 3. Are there security implications? 4. What is the cascading impact? """ def obs_to_prompt(obs: Dict[str, Any]) -> str: alerts = obs.get("alerts", []) incidents = obs.get("active_incidents", []) health = obs.get("system_health", {}) logs = obs.get("logs", [])[-5:] tickets = obs.get("tickets", []) chaos = obs.get("chaos_events", []) lines = [ f"=== ENVIRONMENT OBSERVATION (Step {obs.get('step_count', 0)}) ===", f"Risk Level: {obs.get('risk_level', 'unknown').upper()}", f"Time Elapsed: {obs.get('time_elapsed', 0)}s", "", "--- ACTIVE INCIDENTS ---", ] for inc in incidents: lines.append(f" [{inc['severity'].upper()}] {inc['id']}: {inc['description']}") lines.append(f" Affected: {', '.join(inc['affected_services'])}") lines.append("\n--- ALERTS ---") for a in alerts[-5:]: lines.append(f" [{a['severity'].upper()}] {a['service']}: {a['message']}") lines.append("\n--- RECENT LOGS ---") for log in logs: lines.append(f" [{log['level']}] {log['service']}: {log['message']}") lines.append("\n--- SYSTEM HEALTH ---") lines.append(f" CPU: {health.get('cpu_usage', 0):.1f}%") lines.append(f" Memory: {health.get('memory_usage', 0):.1f}%") lines.append(f" Latency: {health.get('latency_ms', 0):.0f}ms") lines.append(f" Uptime: {health.get('uptime_pct', 0):.1f}%") lines.append(f" Error Rate: {health.get('error_rate', 0):.1f}%") lines.append(f" Nodes: {health.get('active_nodes', 0)}/{health.get('total_nodes', 0)}") if chaos: lines.append("\n--- CHAOS EVENTS THIS STEP ---") for c in chaos: lines.append(f" [{c['severity'].upper()}] {c['type']}: {c['description']}") if tickets: lines.append("\n--- CUSTOMER TICKETS ---") for t in tickets[:3]: escalated = " [ESCALATED]" if t.get("escalated") else "" lines.append(f" [{t['severity'].upper()}]{escalated} {t['id']}: {t['subject']}") lines.append("\nRespond with the JSON action:") return "\n".join(lines) def call_agent(obs: Dict[str, Any]) -> Action: """Call Groq and parse the action.""" prompt = obs_to_prompt(obs) response = client.chat.completions.create( model=MODEL, messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}, ], temperature=0.0, top_p=1.0, max_tokens=500, response_format={"type": "json_object"}, ) raw = response.choices[0].message.content data = json.loads(raw) # Validate and coerce action_type = ActionType(data["type"]) priority = max(1, min(4, int(data.get("priority", 2)))) return Action( type=action_type, target=data.get("target", "unknown"), priority=priority, reasoning=data.get("reasoning", "No reasoning provided"), parameters=data.get("parameters", {}), ) def run_episode(difficulty: str) -> Dict[str, Any]: """Run one full episode for a given difficulty.""" logger.info("[START] Episode starting — difficulty=%s model=%s", difficulty, MODEL) env = ACEAEnvironment(difficulty=difficulty) obs = env.reset() obs_dict = obs.model_dump() total_reward = 0.0 step = 0 done = False episode_actions = [] while not done: step += 1 logger.info("[STEP] Step %d — calling agent...", step) try: action = call_agent(obs_dict) except Exception as e: logger.error("[STEP] Agent error at step %d: %s — using fallback action", step, str(e)) action = Action( type=ActionType.DEBUG_ISSUE, target="unknown", priority=2, reasoning=f"Fallback action due to agent error: {e}", ) observation, reward, done, info = env.step(action) obs_dict = observation.model_dump() total_reward += reward logger.info( "[STEP] Step=%d | Action=%s → %s | Reward=%.4f | Done=%s", step, action.type.value, action.target, reward, done, ) logger.info( "[STEP] Reasoning: %s", action.reasoning[:120], ) breakdown = info.get("reward_breakdown", {}) logger.info( "[STEP] RewardBreakdown: incident_res=%.2f | priority_acc=%.2f | stability=%.2f | total=%.4f", breakdown.get("incident_resolution", 0), breakdown.get("prioritization_accuracy", 0), breakdown.get("system_stability", 0), breakdown.get("total", 0), ) counterfactual = info.get("counterfactual", {}) if counterfactual.get("suboptimal"): logger.info("[STEP] Counterfactual: %s", counterfactual.get("recommendation", "")) episode_actions.append({ "step": step, "action_type": action.type.value, "target": action.target, "reward": round(reward, 4), "reasoning": action.reasoning[:100], }) time.sleep(0.5) # Rate limiting summary = info.get("episode_summary", env._grader.get_summary()) trajectory_score = summary.get("trajectory_score", 0.0) logger.info( "[END] Episode complete — difficulty=%s | Steps=%d | TotalReward=%.4f | TrajectoryScore=%.4f", difficulty, step, total_reward, trajectory_score, ) return { "difficulty": difficulty, "steps": step, "total_reward": round(total_reward, 4), "trajectory_score": trajectory_score, "actions": episode_actions, "summary": summary, } def main(): difficulties = ["easy", "medium", "hard"] results = [] logger.info("[START] ACEA Inference starting — running all %d tasks", len(difficulties)) logger.info("[START] Model: %s", MODEL) print("=" * 70) for difficulty in difficulties: print(f"\n{'='*70}") print(f" RUNNING TASK: {difficulty.upper()}") print(f"{'='*70}") try: result = run_episode(difficulty) results.append(result) print(f"\n ✅ {difficulty.upper()} complete — Score: {result['trajectory_score']:.4f}") except Exception as e: logger.error("[END] Episode failed for difficulty=%s: %s", difficulty, str(e)) results.append({"difficulty": difficulty, "error": str(e)}) print(f"\n{'='*70}") print(" FINAL RESULTS") print(f"{'='*70}") for r in results: if "error" in r: print(f" {r['difficulty'].upper()}: ERROR — {r['error']}") else: print( f" {r['difficulty'].upper()}: " f"Steps={r['steps']} | " f"TotalReward={r['total_reward']:.4f} | " f"TrajectoryScore={r['trajectory_score']:.4f}" ) logger.info("[END] All tasks complete") return results if __name__ == "__main__": if not os.environ.get("GROQ_API_KEY"): print("ERROR: GROQ_API_KEY environment variable not set.") sys.exit(1) main()