Spaces:
Sleeping
Sleeping
Update inference.py
Browse files- inference.py +63 -64
inference.py
CHANGED
|
@@ -1,59 +1,66 @@
|
|
| 1 |
"""
|
| 2 |
inference.py — OpenEnv-compliant inference script for xsecure.
|
| 3 |
|
| 4 |
-
Required env vars
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
STDOUT FORMAT (strictly required):
|
| 10 |
-
[START] task=<task_name> env=<benchmark> model=<model_name>
|
| 11 |
-
[STEP] step=<n> action=<action_str> reward=<0.00> done=<true|false> error=<msg|null>
|
| 12 |
-
[END] success=<true|false> steps=<n> score=<0.000> rewards=<r1,r2,...>
|
| 13 |
"""
|
| 14 |
|
| 15 |
from __future__ import annotations
|
| 16 |
|
|
|
|
| 17 |
import json
|
| 18 |
import os
|
| 19 |
import re
|
| 20 |
import sys
|
| 21 |
-
from typing import Dict, List, Optional
|
| 22 |
|
|
|
|
| 23 |
from openai import OpenAI
|
| 24 |
|
| 25 |
-
from client import IncidentResponseEnv
|
| 26 |
from models import IncidentAction, IncidentObservation
|
| 27 |
|
|
|
|
|
|
|
|
|
|
| 28 |
# ---------------------------------------------------------------------------
|
| 29 |
# Configuration
|
| 30 |
-
# NOTE: Do NOT call load_dotenv() — it overrides the env vars injected by
|
| 31 |
-
# the validator's LiteLLM proxy and breaks the LLM Criteria Check.
|
| 32 |
# ---------------------------------------------------------------------------
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
|
| 38 |
ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
BENCHMARK = "xsecure"
|
| 40 |
MAX_STEPS = 20
|
| 41 |
|
| 42 |
if not API_KEY:
|
| 43 |
-
print("ERROR:
|
| 44 |
sys.exit(1)
|
| 45 |
|
| 46 |
-
#
|
| 47 |
llm = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
|
| 48 |
|
| 49 |
# ---------------------------------------------------------------------------
|
| 50 |
-
# Mandatory stdout loggers
|
| 51 |
# ---------------------------------------------------------------------------
|
| 52 |
|
| 53 |
def log_start(task: str, env: str, model: str) -> None:
|
| 54 |
print(f"[START] task={task} env={env} model={model}", flush=True)
|
| 55 |
|
| 56 |
def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
|
|
|
|
| 57 |
print(
|
| 58 |
f"[STEP] step={step} action={action} reward={reward:.2f} "
|
| 59 |
f"done={str(done).lower()} error={error or 'null'}",
|
|
@@ -61,10 +68,9 @@ def log_step(step: int, action: str, reward: float, done: bool, error: Optional[
|
|
| 61 |
)
|
| 62 |
|
| 63 |
def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
|
| 64 |
-
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
|
| 65 |
print(
|
| 66 |
-
f"[END] success={str(success).lower()} steps={steps} "
|
| 67 |
-
f"
|
| 68 |
flush=True,
|
| 69 |
)
|
| 70 |
|
|
@@ -84,7 +90,7 @@ Your goal is to investigate logs and alerts, identify the threat, and mitigate i
|
|
| 84 |
- restart_service(service)
|
| 85 |
- ignore
|
| 86 |
|
| 87 |
-
## Response Format (STRICT JSON
|
| 88 |
{"action_type": "analyze_log", "target": "L001"}
|
| 89 |
"""
|
| 90 |
|
|
@@ -93,15 +99,11 @@ Your goal is to investigate logs and alerts, identify the threat, and mitigate i
|
|
| 93 |
# ---------------------------------------------------------------------------
|
| 94 |
|
| 95 |
def _format_observation(obs: IncidentObservation) -> str:
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
)
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
)
|
| 102 |
-
services_txt = "\n".join(
|
| 103 |
-
f" {s['name']}: {s['status']}" for s in obs.services
|
| 104 |
-
)
|
| 105 |
return (
|
| 106 |
f"=== Incident Dashboard (Step {obs.step_count}) ===\n\n"
|
| 107 |
f"LOGS:\n{logs_txt}\n\n"
|
|
@@ -112,50 +114,46 @@ def _format_observation(obs: IncidentObservation) -> str:
|
|
| 112 |
)
|
| 113 |
|
| 114 |
def _parse_action(text: str) -> IncidentAction:
|
| 115 |
-
"""Extract JSON action
|
| 116 |
try:
|
|
|
|
| 117 |
pattern = re.search(r"(\{.*?\})", text.strip().replace("\n", " "), re.DOTALL)
|
| 118 |
if pattern:
|
| 119 |
data = json.loads(pattern.group(1))
|
| 120 |
-
|
|
|
|
|
|
|
| 121 |
return IncidentAction(**filtered)
|
| 122 |
except Exception:
|
| 123 |
pass
|
| 124 |
return IncidentAction(action_type="ignore", target="")
|
| 125 |
|
| 126 |
def _get_action(conversation: List[Dict], obs: IncidentObservation) -> IncidentAction:
|
| 127 |
-
"""Call LLM synchronously and return parsed action."""
|
| 128 |
conversation.append({"role": "user", "content": _format_observation(obs)})
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
print(f"[WARN] LLM call failed: {e}", file=sys.stderr)
|
| 139 |
-
text = ""
|
| 140 |
conversation.append({"role": "assistant", "content": text})
|
| 141 |
return _parse_action(text)
|
| 142 |
|
| 143 |
# ---------------------------------------------------------------------------
|
| 144 |
-
# Episode runner
|
| 145 |
# ---------------------------------------------------------------------------
|
| 146 |
|
| 147 |
-
TASK_NAMES = {
|
| 148 |
-
1: "brute-force-easy",
|
| 149 |
-
2: "suspicious-login-medium",
|
| 150 |
-
3: "multi-stage-apt-hard",
|
| 151 |
-
}
|
| 152 |
|
| 153 |
def run_episode(task_id: int) -> None:
|
| 154 |
-
task_name
|
| 155 |
-
rewards:
|
| 156 |
steps_taken = 0
|
| 157 |
-
success
|
| 158 |
-
score
|
| 159 |
conversation: List[Dict] = []
|
| 160 |
|
| 161 |
log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)
|
|
@@ -165,6 +163,7 @@ def run_episode(task_id: int) -> None:
|
|
| 165 |
obs = env.reset(task_id=task_id)
|
| 166 |
|
| 167 |
for step in range(1, MAX_STEPS + 1):
|
|
|
|
| 168 |
action = _get_action(conversation, obs)
|
| 169 |
result = env.step(action)
|
| 170 |
|
|
@@ -181,12 +180,12 @@ def run_episode(task_id: int) -> None:
|
|
| 181 |
)
|
| 182 |
|
| 183 |
if result.done:
|
| 184 |
-
info
|
| 185 |
-
|
| 186 |
-
|
|
|
|
| 187 |
success = bool(info.get("success", False))
|
| 188 |
break
|
| 189 |
-
|
| 190 |
except Exception as e:
|
| 191 |
print(f"ERROR: Episode failed: {e}", file=sys.stderr)
|
| 192 |
finally:
|
|
@@ -196,11 +195,11 @@ def run_episode(task_id: int) -> None:
|
|
| 196 |
# Main
|
| 197 |
# ---------------------------------------------------------------------------
|
| 198 |
|
| 199 |
-
def main()
|
| 200 |
task_ids_str = os.getenv("TASK_IDS", "1,2,3")
|
| 201 |
task_ids = [int(t.strip()) for t in task_ids_str.split(",") if t.strip()]
|
| 202 |
for task_id in task_ids:
|
| 203 |
run_episode(task_id)
|
| 204 |
|
| 205 |
if __name__ == "__main__":
|
| 206 |
-
main()
|
|
|
|
| 1 |
"""
|
| 2 |
inference.py — OpenEnv-compliant inference script for xsecure.
|
| 3 |
|
| 4 |
+
Required env vars:
|
| 5 |
+
HF_TOKEN Hugging Face / API key
|
| 6 |
+
API_BASE_URL LLM endpoint
|
| 7 |
+
MODEL_NAME Model identifier
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
|
| 10 |
from __future__ import annotations
|
| 11 |
|
| 12 |
+
import asyncio
|
| 13 |
import json
|
| 14 |
import os
|
| 15 |
import re
|
| 16 |
import sys
|
| 17 |
+
from typing import Dict, List, Optional, Any
|
| 18 |
|
| 19 |
+
from dotenv import load_dotenv
|
| 20 |
from openai import OpenAI
|
| 21 |
|
| 22 |
+
from client import IncidentResponseEnv, StepResult
|
| 23 |
from models import IncidentAction, IncidentObservation
|
| 24 |
|
| 25 |
+
# Load .env for local dev
|
| 26 |
+
#load_dotenv()
|
| 27 |
+
|
| 28 |
# ---------------------------------------------------------------------------
|
| 29 |
# Configuration
|
|
|
|
|
|
|
| 30 |
# ---------------------------------------------------------------------------
|
| 31 |
+
"""
|
| 32 |
+
API_KEY = os.getenv("API_KEY", "")
|
| 33 |
+
API_BASE_URL = os.getenv("API_BASE_URL")
|
| 34 |
+
MODEL_NAME = os.getenv("MODEL_NAME")
|
|
|
|
| 35 |
ENV_URL = os.getenv("ENV_URL", "http://localhost:7860")
|
| 36 |
+
BENCHMARK = "xsecure"
|
| 37 |
+
MAX_STEPS = 20
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
|
| 41 |
+
MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
|
| 42 |
+
API_KEY = os.environ.get("API_KEY", "")
|
| 43 |
+
ENV_URL = os.environ.get("ENV_URL", "http://localhost:7860")
|
| 44 |
+
|
| 45 |
BENCHMARK = "xsecure"
|
| 46 |
MAX_STEPS = 20
|
| 47 |
|
| 48 |
if not API_KEY:
|
| 49 |
+
print("ERROR: HF_TOKEN is not set.", file=sys.stderr)
|
| 50 |
sys.exit(1)
|
| 51 |
|
| 52 |
+
# Use AsyncOpenAI to prevent blocking the event loop
|
| 53 |
llm = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
|
| 54 |
|
| 55 |
# ---------------------------------------------------------------------------
|
| 56 |
+
# Mandatory stdout loggers (Fixed spacing to match spec)
|
| 57 |
# ---------------------------------------------------------------------------
|
| 58 |
|
| 59 |
def log_start(task: str, env: str, model: str) -> None:
|
| 60 |
print(f"[START] task={task} env={env} model={model}", flush=True)
|
| 61 |
|
| 62 |
def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
|
| 63 |
+
# Spec requires double space after [STEP] for some parsers
|
| 64 |
print(
|
| 65 |
f"[STEP] step={step} action={action} reward={reward:.2f} "
|
| 66 |
f"done={str(done).lower()} error={error or 'null'}",
|
|
|
|
| 68 |
)
|
| 69 |
|
| 70 |
def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
|
|
|
|
| 71 |
print(
|
| 72 |
+
f"[END] success={str(success).lower()} steps={steps} score={score:.3f} "
|
| 73 |
+
f"rewards={','.join(f'{r:.2f}' for r in rewards)}",
|
| 74 |
flush=True,
|
| 75 |
)
|
| 76 |
|
|
|
|
| 90 |
- restart_service(service)
|
| 91 |
- ignore
|
| 92 |
|
| 93 |
+
## Response Format (STRICT JSON):
|
| 94 |
{"action_type": "analyze_log", "target": "L001"}
|
| 95 |
"""
|
| 96 |
|
|
|
|
| 99 |
# ---------------------------------------------------------------------------
|
| 100 |
|
| 101 |
def _format_observation(obs: IncidentObservation) -> str:
|
| 102 |
+
# Use dot notation as expected by the environment models
|
| 103 |
+
logs_txt = "\n".join(f" [{l.log_id}] {l.timestamp} — {l.message}" for l in obs.logs)
|
| 104 |
+
alerts_txt = "\n".join(f" [{a.severity.upper()}] {a.message}" for a in obs.alerts)
|
| 105 |
+
services_txt = "\n".join(f" {s.name}: {s.status}" for s in obs.services)
|
| 106 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
return (
|
| 108 |
f"=== Incident Dashboard (Step {obs.step_count}) ===\n\n"
|
| 109 |
f"LOGS:\n{logs_txt}\n\n"
|
|
|
|
| 114 |
)
|
| 115 |
|
| 116 |
def _parse_action(text: str) -> IncidentAction:
|
| 117 |
+
"""Extract JSON action with filtering for extra fields to avoid Pydantic errors."""
|
| 118 |
try:
|
| 119 |
+
# 1. Try direct or markdown-wrapped JSON
|
| 120 |
pattern = re.search(r"(\{.*?\})", text.strip().replace("\n", " "), re.DOTALL)
|
| 121 |
if pattern:
|
| 122 |
data = json.loads(pattern.group(1))
|
| 123 |
+
# Only pass fields known to IncidentAction
|
| 124 |
+
valid_keys = {"action_type", "target"}
|
| 125 |
+
filtered = {k: v for k, v in data.items() if k in valid_keys}
|
| 126 |
return IncidentAction(**filtered)
|
| 127 |
except Exception:
|
| 128 |
pass
|
| 129 |
return IncidentAction(action_type="ignore", target="")
|
| 130 |
|
| 131 |
def _get_action(conversation: List[Dict], obs: IncidentObservation) -> IncidentAction:
|
|
|
|
| 132 |
conversation.append({"role": "user", "content": _format_observation(obs)})
|
| 133 |
+
|
| 134 |
+
response = llm.chat.completions.create(
|
| 135 |
+
model=MODEL_NAME,
|
| 136 |
+
messages=[{"role": "system", "content": SYSTEM_PROMPT}] + conversation,
|
| 137 |
+
max_tokens=256,
|
| 138 |
+
temperature=0.0,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
text = response.choices[0].message.content or ""
|
|
|
|
|
|
|
| 142 |
conversation.append({"role": "assistant", "content": text})
|
| 143 |
return _parse_action(text)
|
| 144 |
|
| 145 |
# ---------------------------------------------------------------------------
|
| 146 |
+
# Episode runner
|
| 147 |
# ---------------------------------------------------------------------------
|
| 148 |
|
| 149 |
+
TASK_NAMES = {1: "brute-force-easy", 2: "suspicious-login-medium", 3: "multi-stage-apt-hard"}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
def run_episode(task_id: int) -> None:
|
| 152 |
+
task_name = TASK_NAMES.get(task_id, f"task-{task_id}")
|
| 153 |
+
rewards: List[float] = []
|
| 154 |
steps_taken = 0
|
| 155 |
+
success = False
|
| 156 |
+
score = 0.0
|
| 157 |
conversation: List[Dict] = []
|
| 158 |
|
| 159 |
log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)
|
|
|
|
| 163 |
obs = env.reset(task_id=task_id)
|
| 164 |
|
| 165 |
for step in range(1, MAX_STEPS + 1):
|
| 166 |
+
# Now awaited correctly
|
| 167 |
action = _get_action(conversation, obs)
|
| 168 |
result = env.step(action)
|
| 169 |
|
|
|
|
| 180 |
)
|
| 181 |
|
| 182 |
if result.done:
|
| 183 |
+
info = result.info or {}
|
| 184 |
+
# Robust score parsing
|
| 185 |
+
raw_score = info.get("final_score", 0.0)
|
| 186 |
+
score = min(max(float(raw_score or 0.0), 0.0), 1.0)
|
| 187 |
success = bool(info.get("success", False))
|
| 188 |
break
|
|
|
|
| 189 |
except Exception as e:
|
| 190 |
print(f"ERROR: Episode failed: {e}", file=sys.stderr)
|
| 191 |
finally:
|
|
|
|
| 195 |
# Main
|
| 196 |
# ---------------------------------------------------------------------------
|
| 197 |
|
| 198 |
+
def main():
|
| 199 |
task_ids_str = os.getenv("TASK_IDS", "1,2,3")
|
| 200 |
task_ids = [int(t.strip()) for t in task_ids_str.split(",") if t.strip()]
|
| 201 |
for task_id in task_ids:
|
| 202 |
run_episode(task_id)
|
| 203 |
|
| 204 |
if __name__ == "__main__":
|
| 205 |
+
main()
|