spidey121 commited on
Commit
03a69bc
·
1 Parent(s): cd1ee98

fix phase2 timeout

Browse files
Files changed (1) hide show
  1. inference.py +80 -88
inference.py CHANGED
@@ -1,132 +1,124 @@
 
1
  import threading
2
  import time
3
- import os
4
  import random
5
  import traceback
6
  from openai import OpenAI
7
 
8
  random.seed(42)
9
 
10
- # Start server
11
- try:
12
- from env.fake_server import run_server
13
- threading.Thread(target=run_server, daemon=True).start()
14
- time.sleep(3)
15
- except Exception:
16
- pass
17
-
18
  from env.env import DeceptionEnv
19
  from env.attacker import simulate_attack
20
 
21
- API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
22
- MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-7B-Instruct")
23
- HF_TOKEN = os.getenv("HF_TOKEN")
24
 
25
- try:
 
26
 
27
- client = OpenAI(
28
- base_url=API_BASE_URL,
29
- api_key=HF_TOKEN
30
- )
31
 
32
- env = DeceptionEnv()
33
 
34
- # reset API must work
 
 
 
 
 
35
  try:
36
- state = env.reset()
37
- except Exception:
38
- state = {}
39
 
40
- print(
41
- "[START] task=ai-deception env=cyber-security model=AI-agent",
42
- flush=True
43
- )
 
 
 
 
 
 
44
 
45
- rewards = []
46
- history = []
 
 
47
 
48
- # EXACTLY 3 STEPS
49
- for step in range(1, 4):
50
 
51
- try:
52
- simulate_attack()
53
- except Exception:
54
- pass
55
 
56
- # state API must work
57
- try:
58
- state = env.state()
59
- except Exception:
60
- pass
61
 
62
- summary = {
63
- "failed_logins": state.get("failed_logins", 0),
64
- "port_scans": state.get("port_scans", 0),
65
- "suspicious_ips": len(state.get("suspicious_ips", []))
66
- }
67
 
68
- prompt = f"""
69
- You are a cybersecurity decision system.
 
 
 
70
 
71
- Previous actions:
72
- {history}
73
 
74
- Current summary:
75
- {summary}
76
 
77
- Return ONLY one word:
78
  detect_attack
79
  deploy_honeypot
80
  block_ip
81
  """
82
 
83
- try:
84
- response = client.chat.completions.create(
85
- model=MODEL_NAME,
86
- messages=[{"role": "user", "content": prompt}],
87
- temperature=0.2,
88
- max_tokens=20,
89
- timeout=15
90
- )
 
 
91
 
92
- action = response.choices[0].message.content.strip()
93
 
94
- except Exception:
95
- # fallback logic
96
- if not history:
97
- action = "detect_attack"
98
- elif history[-1] == "detect_attack":
99
- action = "deploy_honeypot"
100
- else:
101
- action = "block_ip"
102
 
103
- history.append(action)
104
 
105
- try:
106
  state, reward, done, _ = env.step(action)
107
- except Exception:
108
- reward = 0.0
109
- done = False
110
 
111
- rewards.append(reward)
 
 
 
 
 
 
112
 
113
  print(
114
- f"[STEP] step={step} action={action} reward={reward:.2f} "
115
- f"done={str(done).lower()} error=null",
116
  flush=True
117
  )
118
 
119
- score = min(sum(rewards), 1.0)
120
 
121
- print(
122
- f"[END] success=true steps={len(rewards)} "
123
- f"score={score:.2f} rewards={','.join(f'{r:.2f}' for r in rewards)}",
124
- flush=True
125
- )
126
 
127
- except Exception:
128
- traceback.print_exc()
129
- print(
130
- "[END] success=false steps=0 score=0.00 rewards=",
131
- flush=True
132
- )
 
1
+ import os
2
  import threading
3
  import time
 
4
  import random
5
  import traceback
6
  from openai import OpenAI
7
 
8
  random.seed(42)
9
 
10
+ from env.fake_server import run_server
 
 
 
 
 
 
 
11
  from env.env import DeceptionEnv
12
  from env.attacker import simulate_attack
13
 
 
 
 
14
 
15
+ # If running inside HuggingFace Space → start server only
16
+ if os.getenv("SPACE_ID"):
17
 
18
+ run_server()
 
 
 
19
 
 
20
 
21
+ else:
22
+
23
+ API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
24
+ MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-7B-Instruct")
25
+ HF_TOKEN = os.getenv("HF_TOKEN")
26
+
27
  try:
 
 
 
28
 
29
+ threading.Thread(target=run_server, daemon=True).start()
30
+ time.sleep(3)
31
+
32
+ client = OpenAI(
33
+ base_url=API_BASE_URL,
34
+ api_key=HF_TOKEN
35
+ )
36
+
37
+ env = DeceptionEnv()
38
+ state = env.reset()
39
 
40
+ print(
41
+ "[START] task=ai-deception env=cyber-security model=AI-agent",
42
+ flush=True
43
+ )
44
 
45
+ rewards = []
46
+ history = []
47
 
48
+ for step in range(1, 4):
 
 
 
49
 
50
+ try:
51
+ simulate_attack()
52
+ except:
53
+ pass
 
54
 
55
+ try:
56
+ state = env.state()
57
+ except:
58
+ pass
 
59
 
60
+ summary = {
61
+ "failed_logins": state.get("failed_logins", 0),
62
+ "port_scans": state.get("port_scans", 0),
63
+ "suspicious_ips": len(state.get("suspicious_ips", []))
64
+ }
65
 
66
+ prompt = f"""
67
+ You are cybersecurity system.
68
 
69
+ Previous: {history}
70
+ Current: {summary}
71
 
72
+ Return one:
73
  detect_attack
74
  deploy_honeypot
75
  block_ip
76
  """
77
 
78
+ try:
79
+ response = client.chat.completions.create(
80
+ model=MODEL_NAME,
81
+ messages=[{"role": "user", "content": prompt}],
82
+ temperature=0.2,
83
+ max_tokens=20,
84
+ timeout=15
85
+ )
86
+
87
+ action = response.choices[0].message.content.strip()
88
 
89
+ except:
90
 
91
+ if not history:
92
+ action = "detect_attack"
93
+ elif history[-1] == "detect_attack":
94
+ action = "deploy_honeypot"
95
+ else:
96
+ action = "block_ip"
 
 
97
 
98
+ history.append(action)
99
 
 
100
  state, reward, done, _ = env.step(action)
101
+ rewards.append(reward)
 
 
102
 
103
+ print(
104
+ f"[STEP] step={step} action={action} reward={reward:.2f} "
105
+ f"done={str(done).lower()} error=null",
106
+ flush=True
107
+ )
108
+
109
+ score = min(sum(rewards), 1.0)
110
 
111
  print(
112
+ f"[END] success=true steps={len(rewards)} "
113
+ f"score={score:.2f} rewards={','.join(f'{r:.2f}' for r in rewards)}",
114
  flush=True
115
  )
116
 
117
+ except Exception:
118
 
119
+ traceback.print_exc()
 
 
 
 
120
 
121
+ print(
122
+ "[END] success=false steps=0 score=0.00 rewards=",
123
+ flush=True
124
+ )