Spaces:
Sleeping
Sleeping
Kalpesh Parashar commited on
Commit ·
d1e5c06
1
Parent(s): 4246a2c
fix: update OpenAI client usage and improve error handling in task execution
Browse files- inference.py +22 -36
- server/app.py +0 -2
inference.py
CHANGED
|
@@ -3,7 +3,7 @@ import json
|
|
| 3 |
import asyncio
|
| 4 |
import re
|
| 5 |
from typing import List, Dict, Any
|
| 6 |
-
from openai import
|
| 7 |
|
| 8 |
from src.env import QuasarEnv
|
| 9 |
from src.models import QuasarAction
|
|
@@ -18,10 +18,8 @@ def log_step(step: int, action: str, reward: float, done: bool, error: str = Non
|
|
| 18 |
def log_end(success: bool, steps: int, score: float, rewards: List[float]):
|
| 19 |
print(f"[END] success={success} steps={steps} score={score} rewards={rewards}", flush=True)
|
| 20 |
|
| 21 |
-
async def run_task(client:
|
| 22 |
env = QuasarEnv(task_name=task_name)
|
| 23 |
-
|
| 24 |
-
history: List[str] = []
|
| 25 |
rewards: List[float] = []
|
| 26 |
steps_taken = 0
|
| 27 |
score = 0.0
|
|
@@ -44,36 +42,33 @@ You MUST return strictly valid JSON matching this schema:
|
|
| 44 |
{
|
| 45 |
"command": "allow_packet" | "flag_packet" | "isolate_ip" | "pass",
|
| 46 |
"target_id": "string or null"
|
| 47 |
-
}
|
| 48 |
-
Do not include markdown blocks or any other text."""
|
| 49 |
|
| 50 |
for step in range(1, max_steps + 1):
|
| 51 |
-
if state.done:
|
| 52 |
-
break
|
| 53 |
|
| 54 |
obs_dict = state.observation.model_dump()
|
| 55 |
user_message = f"Current State: {json.dumps(obs_dict)}\nWhat is your action?"
|
| 56 |
|
| 57 |
try:
|
| 58 |
-
response =
|
| 59 |
model=model_name,
|
| 60 |
messages=[
|
| 61 |
{"role": "system", "content": system_prompt},
|
| 62 |
{"role": "user", "content": user_message}
|
| 63 |
],
|
| 64 |
-
temperature=0.0
|
| 65 |
)
|
| 66 |
-
|
| 67 |
-
raw_action = response.choices[0].message.content
|
| 68 |
json_match = re.search(r'\{.*?\}', raw_action, re.DOTALL)
|
| 69 |
|
| 70 |
if json_match:
|
| 71 |
action_dict = json.loads(json_match.group(0))
|
|
|
|
|
|
|
| 72 |
else:
|
| 73 |
-
raise ValueError("No valid JSON object found
|
| 74 |
-
|
| 75 |
-
action_obj = QuasarAction(**action_dict)
|
| 76 |
-
error = None
|
| 77 |
|
| 78 |
except Exception as e:
|
| 79 |
action_obj = QuasarAction(command="pass", target_id=None)
|
|
@@ -81,44 +76,35 @@ Do not include markdown blocks or any other text."""
|
|
| 81 |
error = f"LLM parsing error: {str(e)}"
|
| 82 |
|
| 83 |
state = await env.step(action_obj)
|
| 84 |
-
|
| 85 |
reward = state.reward.score if state.reward else 0.0
|
| 86 |
done = state.done
|
| 87 |
|
| 88 |
rewards.append(reward)
|
| 89 |
steps_taken = step
|
| 90 |
-
|
| 91 |
log_step(step=step, action=action_dict, reward=reward, done=done, error=error)
|
| 92 |
|
| 93 |
-
if done:
|
| 94 |
-
break
|
| 95 |
|
| 96 |
-
score = rewards[-1] if rewards else 0.0
|
| 97 |
-
success = score >= 0.7
|
| 98 |
|
| 99 |
finally:
|
| 100 |
log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
|
| 101 |
|
| 102 |
|
| 103 |
async def main():
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
print("WARNING: HF_TOKEN or OPENAI_API_KEY environment variable not set. LLM calls will fail.")
|
| 110 |
-
|
| 111 |
-
client = AsyncOpenAI(base_url=api_base, api_key=api_key)
|
| 112 |
|
| 113 |
-
|
| 114 |
-
"task_1_volumetric_flood",
|
| 115 |
-
"task_2_contextual_injection",
|
| 116 |
-
"task_3_stealth_poisoning"
|
| 117 |
-
]
|
| 118 |
|
|
|
|
| 119 |
for task in tasks:
|
| 120 |
print(f"\n--- Running Baseline for {task.upper()} ---")
|
| 121 |
-
await run_task(client, task,
|
| 122 |
|
| 123 |
if __name__ == "__main__":
|
| 124 |
asyncio.run(main())
|
|
|
|
| 3 |
import asyncio
|
| 4 |
import re
|
| 5 |
from typing import List, Dict, Any
|
| 6 |
+
from openai import OpenAI
|
| 7 |
|
| 8 |
from src.env import QuasarEnv
|
| 9 |
from src.models import QuasarAction
|
|
|
|
| 18 |
def log_end(success: bool, steps: int, score: float, rewards: List[float]):
|
| 19 |
print(f"[END] success={success} steps={steps} score={score} rewards={rewards}", flush=True)
|
| 20 |
|
| 21 |
+
async def run_task(client: OpenAI, task_name: str, model_name: str):
|
| 22 |
env = QuasarEnv(task_name=task_name)
|
|
|
|
|
|
|
| 23 |
rewards: List[float] = []
|
| 24 |
steps_taken = 0
|
| 25 |
score = 0.0
|
|
|
|
| 42 |
{
|
| 43 |
"command": "allow_packet" | "flag_packet" | "isolate_ip" | "pass",
|
| 44 |
"target_id": "string or null"
|
| 45 |
+
}"""
|
|
|
|
| 46 |
|
| 47 |
for step in range(1, max_steps + 1):
|
| 48 |
+
if state.done: break
|
|
|
|
| 49 |
|
| 50 |
obs_dict = state.observation.model_dump()
|
| 51 |
user_message = f"Current State: {json.dumps(obs_dict)}\nWhat is your action?"
|
| 52 |
|
| 53 |
try:
|
| 54 |
+
response = client.chat.completions.create(
|
| 55 |
model=model_name,
|
| 56 |
messages=[
|
| 57 |
{"role": "system", "content": system_prompt},
|
| 58 |
{"role": "user", "content": user_message}
|
| 59 |
],
|
| 60 |
+
temperature=0.0
|
| 61 |
)
|
| 62 |
+
|
| 63 |
+
raw_action = response.choices[0].message.content
|
| 64 |
json_match = re.search(r'\{.*?\}', raw_action, re.DOTALL)
|
| 65 |
|
| 66 |
if json_match:
|
| 67 |
action_dict = json.loads(json_match.group(0))
|
| 68 |
+
action_obj = QuasarAction(**action_dict)
|
| 69 |
+
error = None
|
| 70 |
else:
|
| 71 |
+
raise ValueError("No valid JSON object found.")
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
except Exception as e:
|
| 74 |
action_obj = QuasarAction(command="pass", target_id=None)
|
|
|
|
| 76 |
error = f"LLM parsing error: {str(e)}"
|
| 77 |
|
| 78 |
state = await env.step(action_obj)
|
|
|
|
| 79 |
reward = state.reward.score if state.reward else 0.0
|
| 80 |
done = state.done
|
| 81 |
|
| 82 |
rewards.append(reward)
|
| 83 |
steps_taken = step
|
|
|
|
| 84 |
log_step(step=step, action=action_dict, reward=reward, done=done, error=error)
|
| 85 |
|
| 86 |
+
if done: break
|
|
|
|
| 87 |
|
| 88 |
+
score = rewards[-1] if rewards else 0.0
|
| 89 |
+
success = score >= 0.7
|
| 90 |
|
| 91 |
finally:
|
| 92 |
log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
|
| 93 |
|
| 94 |
|
| 95 |
async def main():
|
| 96 |
+
API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
|
| 97 |
+
MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-3.5-turbo")
|
| 98 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 99 |
+
|
| 100 |
+
api_key = HF_TOKEN or os.environ.get("OPENAI_API_KEY")
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
+
client = OpenAI(base_url=API_BASE_URL, api_key=api_key)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
+
tasks = ["task_1_volumetric_flood", "task_2_contextual_injection", "task_3_stealth_poisoning"]
|
| 105 |
for task in tasks:
|
| 106 |
print(f"\n--- Running Baseline for {task.upper()} ---")
|
| 107 |
+
await run_task(client, task, MODEL_NAME)
|
| 108 |
|
| 109 |
if __name__ == "__main__":
|
| 110 |
asyncio.run(main())
|
server/app.py
CHANGED
|
@@ -5,10 +5,8 @@ from openenv.core.env_server import create_app
|
|
| 5 |
from src.env import QuasarEnv
|
| 6 |
from src.models import QuasarAction, QuasarObservation
|
| 7 |
|
| 8 |
-
# Initialize the OpenEnv FastAPI wrapper
|
| 9 |
app = create_app(QuasarEnv, QuasarAction, QuasarObservation)
|
| 10 |
|
| 11 |
-
# Add a root endpoint for human judges and HF health checks
|
| 12 |
@app.get("/", response_class=HTMLResponse)
|
| 13 |
async def root():
|
| 14 |
return """
|
|
|
|
| 5 |
from src.env import QuasarEnv
|
| 6 |
from src.models import QuasarAction, QuasarObservation
|
| 7 |
|
|
|
|
| 8 |
app = create_app(QuasarEnv, QuasarAction, QuasarObservation)
|
| 9 |
|
|
|
|
| 10 |
@app.get("/", response_class=HTMLResponse)
|
| 11 |
async def root():
|
| 12 |
return """
|