anvisinghh commited on
Commit
00fce2f
·
verified ·
1 Parent(s): 0010678

Update inference.py

Browse files
Files changed (1) hide show
  1. inference.py +70 -72
inference.py CHANGED
@@ -1,73 +1,71 @@
1
- import asyncio
2
- import os
3
- import textwrap
4
- from typing import List, Optional
5
- from openai import OpenAI
6
- from my_env_v4 import MyEnvV4Action, MyEnvV4Env
7
-
8
- # Environment Configuration
9
- API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
10
- API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
11
- MODEL_NAME = os.getenv("MODEL_NAME") or "Qwen/Qwen2.5-72B-Instruct"
12
- TASK_NAME = "email-triage"
13
- BENCHMARK = "mit-manipal-v4"
14
- MAX_STEPS = 3
15
- SUCCESS_THRESHOLD = 0.5
16
-
17
- SYSTEM_PROMPT = """
18
- You are an Email Security Agent. Triage the following email based on sender, headers, and body content.
19
- Digital Seduction Rules:
20
- - 'INBOX': Official domains (.edu, .gov) and passed security headers.
21
- - 'SPAM': Marketing, gambling, or generic lottery win claims.
22
- - 'QUARANTINE': Phishing, high-urgency threats, suspicious links (.net, .co), or failed headers (SPF/DMARC Fail).
23
-
24
- REPLY WITH EXACTLY ONE WORD: 'INBOX', 'SPAM', or 'QUARANTINE'.
25
- """
26
-
27
- def log_start():
28
- print(f"[START] task={TASK_NAME} env={BENCHMARK} model={MODEL_NAME}", flush=True)
29
-
30
- def log_step(step, action, reward, done):
31
- print(f"[STEP] step={step} action={action} reward={reward:.2f} done={str(done).lower()} error=null", flush=True)
32
-
33
- def log_end(success, steps, score, rewards):
34
- r_str = ",".join(f"{r:.2f}" for r in rewards)
35
- print(f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={r_str}", flush=True)
36
-
37
- async def main():
38
- client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
39
- env = MyEnvV4Env() # Local instance for testing, can use from_docker_image if needed
40
-
41
- rewards = []
42
- log_start()
43
-
44
- try:
45
- result = await env.reset()
46
- for step in range(1, MAX_STEPS + 1):
47
- if result.done: break
48
-
49
- obs = result.observation
50
- prompt = f"Sender: {obs.sender}\nSubject: {obs.subject}\nBody: {obs.body}\nHeaders: {obs.headers}"
51
-
52
- # OpenAI Call
53
- response = client.chat.completions.create(
54
- model=MODEL_NAME,
55
- messages=[{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}],
56
- max_tokens=10,
57
- temperature=0.0 # Deterministic for testing
58
- )
59
- action_text = response.choices[0].message.content.strip().upper()
60
-
61
- result = await env.step(MyEnvV4Action(message=action_text))
62
- rewards.append(result.reward)
63
-
64
- log_step(step, action_text, result.reward, result.done)
65
- if result.done: break
66
-
67
- total_score = sum(rewards) / MAX_STEPS
68
- log_end(total_score >= SUCCESS_THRESHOLD, len(rewards), total_score, rewards)
69
- finally:
70
- await env.close()
71
-
72
- if __name__ == "__main__":
73
  asyncio.run(main())
 
1
+ import asyncio
2
+ import os
3
+ from typing import List
4
+ from openai import OpenAI
5
+ from env import MyEnvV4Env
6
+ from models import MyEnvV4Action
7
+
8
+ # Environment Configuration
9
+ API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
10
+ API_KEY = os.getenv("HF_TOKEN") or ""
11
+ MODEL_NAME = os.getenv("MODEL_NAME") or "gemini-2.5-flash-preview-09-2025"
12
+ TASK_NAME = "security-mail-triage"
13
+
14
+ SYSTEM_PROMPT = """
15
+ You are an Advanced Email Security Agent. Analyze the metadata (headers, SPF/DKIM), URLs, and content.
16
+ Categories:
17
+ - INBOX: Trusted academic/official domains, passed auth, clean history.
18
+ - SPAM: Mass marketing, generic lottery/sales, usually safe but unwanted.
19
+ - QUARANTINE: Phishing, spear-phishing, credential theft, high-urgency threats, typo-squatted domains.
20
+
21
+ Rules:
22
+ 1. Examine 'raw_headers' and 'auth_results'.
23
+ 2. Inspect 'urls' for low reputation or high age.
24
+ 3. Provide reasoning first, then your decision.
25
+
26
+ Respond in JSON format:
27
+ {
28
+ "reasoning": "Explain your logic here...",
29
+ "message": "INBOX|SPAM|QUARANTINE"
30
+ }
31
+ """
32
+
33
+ async def main():
34
+ client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
35
+ env = MyEnvV4Env()
36
+
37
+ rewards = []
38
+ print(f"[START] Testing Security Triage Environment...")
39
+
40
+ result = await env.reset()
41
+ step_idx = 1
42
+
43
+ while not result.done:
44
+ obs = result.observation
45
+ prompt = f"Sender: {obs.sender}\nSubject: {obs.subject}\nBody: {obs.body}\nHeaders: {obs.raw_headers}\nURLs: {obs.urls}"
46
+
47
+ try:
48
+ response = client.chat.completions.create(
49
+ model=MODEL_NAME,
50
+ messages=[{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}],
51
+ response_format={"type": "json_object"},
52
+ temperature=0.0
53
+ )
54
+ import json
55
+ data = json.loads(response.choices[0].message.content)
56
+
57
+ action = MyEnvV4Action(message=data["message"], reasoning=data["reasoning"])
58
+ result = await env.step(action)
59
+ rewards.append(result.reward)
60
+
61
+ print(f"[STEP {step_idx}] Action: {action.message} | Reward: {result.reward:.2f}")
62
+ step_idx += 1
63
+ except Exception as e:
64
+ print(f"[ERROR] Step {step_idx}: {e}")
65
+ break
66
+
67
+ score = sum(rewards) / len(rewards) if rewards else 0
68
+ print(f"[END] Final Score: {score:.3f}")
69
+
70
+ if __name__ == "__main__":
 
 
71
  asyncio.run(main())