Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- inference.py +95 -52
inference.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
"""
|
| 3 |
AgentOps Gym — Baseline inference script.
|
| 4 |
|
| 5 |
-
Runs an LLM agent against all
|
| 6 |
and reports per-task scores in the mandatory OpenEnv stdout format.
|
| 7 |
|
| 8 |
Environment variables (MANDATORY):
|
|
@@ -21,12 +21,26 @@ import asyncio
|
|
| 21 |
import json
|
| 22 |
import os
|
| 23 |
import sys
|
|
|
|
| 24 |
from typing import Any, Dict, List, Optional
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
from agentops_gym.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
# ---------------------------------------------------------------------------
|
| 32 |
# Configuration
|
|
@@ -42,6 +56,7 @@ MAX_STEPS = 10
|
|
| 42 |
TEMPERATURE = 0.0
|
| 43 |
MAX_TOKENS = 600
|
| 44 |
|
|
|
|
| 45 |
ALL_TASKS = ["task_1", "task_2", "task_3", "task_4"]
|
| 46 |
|
| 47 |
# ---------------------------------------------------------------------------
|
|
@@ -103,7 +118,7 @@ def build_prompt(obs_data: Dict[str, Any]) -> str:
|
|
| 103 |
parts = [f"TASK: {obs_data.get('task_description', '')}"]
|
| 104 |
parts.append(f"\nVisible files: {obs_data.get('visible_files', [])}")
|
| 105 |
if obs_data.get("last_tool_result"):
|
| 106 |
-
parts.append(f"\nLast tool result:\n{obs_data['last_tool_result']}")
|
| 107 |
history = obs_data.get("action_history", [])
|
| 108 |
if history:
|
| 109 |
parts.append(f"\nHistory ({len(history)} calls): {history[-3:]}") # last 3
|
|
@@ -172,17 +187,21 @@ async def run_episode(
|
|
| 172 |
break
|
| 173 |
|
| 174 |
prompt = build_prompt(obs_data)
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
tool_call = extract_tool_call(raw)
|
| 187 |
|
| 188 |
if tool_call is None:
|
|
@@ -216,6 +235,7 @@ async def run_episode(
|
|
| 216 |
|
| 217 |
except Exception as exc:
|
| 218 |
print(f"[DEBUG] Episode error for {task_id}: {exc}", flush=True)
|
|
|
|
| 219 |
|
| 220 |
finally:
|
| 221 |
log_end(success=success, steps=steps_taken, rewards=rewards)
|
|
@@ -233,45 +253,68 @@ async def run_episode(
|
|
| 233 |
# ---------------------------------------------------------------------------
|
| 234 |
|
| 235 |
async def async_main() -> None:
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
"HF_TOKEN (or API_KEY)
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
print(f"
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
|
| 273 |
def main() -> None:
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
|
| 276 |
|
| 277 |
if __name__ == "__main__":
|
|
|
|
| 2 |
"""
|
| 3 |
AgentOps Gym — Baseline inference script.
|
| 4 |
|
| 5 |
+
Runs an LLM agent against all AgentOps Gym tasks (tool-use efficiency)
|
| 6 |
and reports per-task scores in the mandatory OpenEnv stdout format.
|
| 7 |
|
| 8 |
Environment variables (MANDATORY):
|
|
|
|
| 21 |
import json
|
| 22 |
import os
|
| 23 |
import sys
|
| 24 |
+
import traceback
|
| 25 |
from typing import Any, Dict, List, Optional
|
| 26 |
|
| 27 |
+
try:
|
| 28 |
+
from openai import OpenAI
|
| 29 |
+
except ImportError:
|
| 30 |
+
print("ERROR: 'openai' package not found. Install with: pip install openai", file=sys.stderr)
|
| 31 |
+
sys.exit(1)
|
| 32 |
|
| 33 |
+
try:
|
| 34 |
+
from agentops_gym.client import AgentOpsEnv
|
| 35 |
+
from agentops_gym.models import ToolCall
|
| 36 |
+
except (ModuleNotFoundError, ImportError):
|
| 37 |
+
try:
|
| 38 |
+
from client import AgentOpsEnv
|
| 39 |
+
from models import ToolCall
|
| 40 |
+
except ImportError:
|
| 41 |
+
print("ERROR: Could not import AgentOpsEnv or ToolCall. "
|
| 42 |
+
"Ensure you are running from the project root or 'agentops_gym' directory.", file=sys.stderr)
|
| 43 |
+
sys.exit(1)
|
| 44 |
|
| 45 |
# ---------------------------------------------------------------------------
|
| 46 |
# Configuration
|
|
|
|
| 56 |
TEMPERATURE = 0.0
|
| 57 |
MAX_TOKENS = 600
|
| 58 |
|
| 59 |
+
# Tasks are fetched from the environment if possible, or use defaults
|
| 60 |
ALL_TASKS = ["task_1", "task_2", "task_3", "task_4"]
|
| 61 |
|
| 62 |
# ---------------------------------------------------------------------------
|
|
|
|
| 118 |
parts = [f"TASK: {obs_data.get('task_description', '')}"]
|
| 119 |
parts.append(f"\nVisible files: {obs_data.get('visible_files', [])}")
|
| 120 |
if obs_data.get("last_tool_result"):
|
| 121 |
+
parts.append(f"\nLast tool result:\\n{obs_data['last_tool_result']}")
|
| 122 |
history = obs_data.get("action_history", [])
|
| 123 |
if history:
|
| 124 |
parts.append(f"\nHistory ({len(history)} calls): {history[-3:]}") # last 3
|
|
|
|
| 187 |
break
|
| 188 |
|
| 189 |
prompt = build_prompt(obs_data)
|
| 190 |
+
try:
|
| 191 |
+
completion = client.chat.completions.create(
|
| 192 |
+
model=MODEL_NAME,
|
| 193 |
+
messages=[
|
| 194 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 195 |
+
{"role": "user", "content": prompt},
|
| 196 |
+
],
|
| 197 |
+
max_tokens=MAX_TOKENS,
|
| 198 |
+
temperature=TEMPERATURE,
|
| 199 |
+
)
|
| 200 |
+
raw = (completion.choices[0].message.content or "").strip()
|
| 201 |
+
except Exception as e:
|
| 202 |
+
print(f"[DEBUG] LLM Error: {e}", flush=True)
|
| 203 |
+
raw = "{}"
|
| 204 |
+
|
| 205 |
tool_call = extract_tool_call(raw)
|
| 206 |
|
| 207 |
if tool_call is None:
|
|
|
|
| 235 |
|
| 236 |
except Exception as exc:
|
| 237 |
print(f"[DEBUG] Episode error for {task_id}: {exc}", flush=True)
|
| 238 |
+
traceback.print_exc()
|
| 239 |
|
| 240 |
finally:
|
| 241 |
log_end(success=success, steps=steps_taken, rewards=rewards)
|
|
|
|
| 253 |
# ---------------------------------------------------------------------------
|
| 254 |
|
| 255 |
async def async_main() -> None:
|
| 256 |
+
try:
|
| 257 |
+
if not API_KEY:
|
| 258 |
+
print("WARNING: HF_TOKEN (or API_KEY) not set. Inference may fail.", file=sys.stderr)
|
| 259 |
+
# We don't exit here, as some validators might mock the API or just check for startup
|
| 260 |
+
|
| 261 |
+
if not IMAGE_NAME:
|
| 262 |
+
print("WARNING: IMAGE_NAME not set. Defaulting to 'agentops-gym'.", file=sys.stderr)
|
| 263 |
+
image = "agentops-gym"
|
| 264 |
+
else:
|
| 265 |
+
image = IMAGE_NAME
|
| 266 |
+
|
| 267 |
+
client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY or "dummy-key")
|
| 268 |
+
|
| 269 |
+
# Create environment
|
| 270 |
+
print(f"Connecting to environment image: {image}...", flush=True)
|
| 271 |
+
try:
|
| 272 |
+
# Setting a longer timeout for container operations to prevent TimeoutExpired
|
| 273 |
+
env = await AgentOpsEnv.from_docker_image(image, stop_timeout=30)
|
| 274 |
+
except Exception as e:
|
| 275 |
+
print(f"ERROR: Failed to start environment from image '{image}': {e}", file=sys.stderr)
|
| 276 |
+
traceback.print_exc()
|
| 277 |
+
return
|
| 278 |
+
|
| 279 |
+
async with env:
|
| 280 |
+
results = []
|
| 281 |
+
for task_id in ALL_TASKS:
|
| 282 |
+
result = await run_episode(env, client, task_id)
|
| 283 |
+
results.append(result)
|
| 284 |
+
|
| 285 |
+
# Summary
|
| 286 |
+
print(f"\n{'='*60}", flush=True)
|
| 287 |
+
print("SUMMARY", flush=True)
|
| 288 |
+
print(f"{'='*60}", flush=True)
|
| 289 |
+
|
| 290 |
+
total = sum(r["score"] for r in results)
|
| 291 |
+
resolved = sum(1 for r in results if r["success"])
|
| 292 |
+
avg = total / len(results) if results else 0.0
|
| 293 |
+
|
| 294 |
+
for r in results:
|
| 295 |
+
status = "SOLVED" if r["success"] else "FAILED"
|
| 296 |
+
print(f" {r['task_id']:>8}: score={r['score']:.3f} steps={r['steps']} {status}", flush=True)
|
| 297 |
+
|
| 298 |
+
print(f"\n Total: {total:.3f} / {len(results)}", flush=True)
|
| 299 |
+
print(f" Average: {avg:.3f}", flush=True)
|
| 300 |
+
print(f" Solved: {resolved} / {len(results)}", flush=True)
|
| 301 |
+
|
| 302 |
+
except Exception as e:
|
| 303 |
+
print(f"FATAL ERROR in async_main: {e}", file=sys.stderr)
|
| 304 |
+
traceback.print_exc()
|
| 305 |
+
raise
|
| 306 |
|
| 307 |
|
| 308 |
def main() -> None:
|
| 309 |
+
try:
|
| 310 |
+
asyncio.run(async_main())
|
| 311 |
+
except KeyboardInterrupt:
|
| 312 |
+
pass
|
| 313 |
+
except SystemExit:
|
| 314 |
+
raise
|
| 315 |
+
except Exception:
|
| 316 |
+
# Already logged in async_main, but just in case
|
| 317 |
+
sys.exit(1)
|
| 318 |
|
| 319 |
|
| 320 |
if __name__ == "__main__":
|