File size: 13,468 Bytes
ef737d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | # main.py β OpenEnv-Compliant FastAPI Server
# Autonomy Calibration Environment v1.0
# OpenEnv India Hackathon 2026 β by Rhythm
from __future__ import annotations
import os
from collections import Counter
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import subprocess
import sys
from pydantic import BaseModel
from models import Action, Observation, Reward, StepResult, ResetRequest
from environment.scenarios import SCENARIOS
def _build_registry():
from tasks.email_triage import EmailTriageTask
from tasks.devops_incident import DevOpsIncidentTask
from tasks.financial_request import FinancialRequestTask
return {
"email_triage": EmailTriageTask,
"devops_incident": DevOpsIncidentTask,
"financial_request": FinancialRequestTask,
}
TASK_REGISTRY = _build_registry()
# βββ App βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
app = FastAPI(
title="Autonomy Calibration Environment",
description=(
"OpenEnv-compliant RL environment training agents to calibrate autonomy "
"across Email Triage, DevOps Incident Response, and Financial Request Handling."
),
version="2.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# βββ Session State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Single-session in-memory state. Sufficient for hackathon + HF Spaces.
_session: dict = {
"task_name": None,
"task": None,
"step": 0,
"history": [],
"done": True,
"seed": None,
"episode_id": None,
}
# Global episode log for /api/history
_episode_log: list[dict] = []
# βββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _get_task(name: str):
if name not in TASK_REGISTRY:
raise HTTPException(
status_code=400,
detail=f"Unknown task '{name}'. Valid: {list(TASK_REGISTRY.keys())}"
)
return TASK_REGISTRY[name]()
# βββ API: Reset βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/reset")
@app.post("/api/reset", response_model=Observation)
def reset(body: ResetRequest = ResetRequest()):
try:
task = _get_task(body.task)
obs = task.reset(seed=body.seed)
# Store seed in session and observation
obs.seed = body.seed
_session["task_name"] = body.task
_session["task"] = task
_session["step"] = 0
_session["history"] = []
_session["done"] = False
_session["seed"] = body.seed
# Create DB episode and store ID
import database as db
_session["episode_id"] = db.create_episode(body.task, body.seed)
return obs
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# βββ API: Step βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/step")
@app.post("/api/step", response_model=StepResult)
async def step_env(action: Action):
task = _session.get("task")
if task is None or _session.get("done"):
raise HTTPException(status_code=400, detail="No active episode. Call /api/reset first.")
try:
obs, reward, done, info = task.step(action)
step_idx = _session["step"]
_session["step"] += 1
_session["done"] = done
step_entry = {
"step": step_idx,
"action": action.type,
"reward": reward.value,
"done": done,
}
_session["history"].append(step_entry)
# Persist step to SQLite
import database as db
db.log_step(
episode_id=_session["episode_id"],
step_index=step_idx,
decision=action.type,
reward=reward.value,
done=done,
)
if done:
episode_score = info.get("episode_score")
db.close_episode(_session["episode_id"], episode_score or 0.0)
_episode_log.append({
"episode_id": _session["episode_id"],
"task": _session["task_name"],
"seed": _session["seed"],
"episode_score": episode_score,
"steps": _session["step"],
"history": list(_session["history"]),
})
return StepResult(observation=obs, reward=reward, done=done, info=info)
except RuntimeError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# βββ API: State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/api/state")
def state():
task = _session.get("task")
if task is None:
return {"status": "not_started"}
return {
"status": "done" if _session["done"] else "active",
"task": _session["task_name"],
"step": _session["step"],
**task.state(),
}
# βββ API: Training ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_training():
"""Runs the training script in a separate process and pipes output to logs."""
try:
print("π GRPO TRAINING CORE: Initializing...")
# Redirect stdout and stderr to the main process ones so they appear in HF Logs
process = subprocess.Popen(
[sys.executable, "train_rl.py"],
stdout=sys.stdout,
stderr=sys.stderr,
bufsize=1, # Line buffered
universal_newlines=True
)
print(f"β
Background process PID {process.pid} spawned.")
except Exception as e:
print(f"β Error during background training: {e}")
@app.post("/api/train")
def start_training(background_tasks: BackgroundTasks):
# Basic check for GPU presence (useful for logs)
try:
import torch
has_gpu = torch.cuda.is_available()
device_name = torch.cuda.get_device_name(0) if has_gpu else "CPU"
except ImportError:
has_gpu = False
device_name = "CPU"
background_tasks.add_task(run_training)
return {
"status": "started",
"message": "GRPO Training started in background.",
"using_gpu": has_gpu,
"device": device_name
}
@app.post("/api/upload")
def upload_to_hub(repo_id: str = "JOY0021/autonomy-agent-v2"):
"""Pushes the trained folder to the HF Hub model repo, creating it if needed."""
try:
import os
from huggingface_hub import HfApi, create_repo
token = os.getenv("HF_TOKEN")
api = HfApi(token=token)
# 1. Create repo if it doesn't exist
print(f"π¦ Ensuring repo {repo_id} exists...")
create_repo(repo_id=repo_id, repo_type="model", exist_ok=True, token=token)
# 2. Upload the folder
print(f"π‘ Uploading autonomy-agent-v2 to {repo_id}...")
api.upload_folder(
folder_path="autonomy-agent-v2",
repo_id=repo_id,
repo_type="model",
)
return {"status": "success", "message": f"Model live at https://huggingface.co/{repo_id}"}
except Exception as e:
print(f"β Upload Error: {e}")
return {"status": "error", "message": str(e)}
# βββ API: Health βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/api/health")
def health():
difficulty_dist = Counter(s["difficulty"] for s in SCENARIOS)
decision_dist = Counter(s["best_decision"] for s in SCENARIOS)
return {
"status": "ok",
"environment": "autonomy-calibration-env",
"version": "2.0.0",
"tasks": list(TASK_REGISTRY.keys()),
"autonomy_action_space": ["ACT", "ASK", "STOP", "RECOVER"],
"autonomy_scenarios": len(SCENARIOS),
"autonomy_difficulty_distribution": dict(difficulty_dist),
"autonomy_decision_distribution": dict(decision_dist),
"reward_range": [0.01, 0.99],
}
# βββ API: History βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/api/history")
def history():
total = len(_episode_log)
scores = [e["episode_score"] for e in _episode_log if e.get("episode_score") is not None]
return {
"total_episodes": total,
"avg_score": round(sum(scores) / len(scores), 4) if scores else 0.0,
"episodes": _episode_log,
}
@app.delete("/api/history")
def clear_history():
_episode_log.clear()
return {"status": "cleared"}
# βββ API: Observability (Step 4) βββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/api/episodes")
def episodes(limit: int = 20):
"""List recent episodes from SQLite with metadata."""
import database as db
try:
rows = db.list_episodes(limit=limit)
return {"episodes": rows, "count": len(rows)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/replay/{episode_id}")
def replay(episode_id: int):
"""
Return the full step history for a past episode.
Can be used to reproduce the episode by feeding steps back into reset + step.
"""
import database as db
try:
data = db.get_episode(episode_id)
return {
"episode_id": episode_id,
"episode": data["episode"],
"steps": data["steps"],
"total_steps": len(data["steps"]),
}
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/grade")
def grade_current():
"""Run deterministic grader on the current session's episode history."""
task = _session.get("task")
if task is None:
raise HTTPException(status_code=400, detail="No active episode.")
score = task.grade_episode(_session["history"])
return {
"task": _session["task_name"],
"seed": _session["seed"],
"episode_id": _session["episode_id"],
"score": score,
"steps_completed": _session["step"],
"done": _session["done"],
}
@app.get("/api/grade/{episode_id}")
def grade_episode(episode_id: int):
"""Run deterministic grader on a completed historical episode."""
import database as db
try:
data = db.get_episode(episode_id)
ep = data["episode"]
steps = data["steps"]
# Reconstruct history format expected by grade_episode()
history = [
{"step": s["step_index"], "action": s["decision"],
"reward": {"value": s["reward"]}}
for s in steps
]
total_reward = sum(s["reward"] for s in steps)
from utils import clamp
score = clamp(total_reward)
return {
"episode_id": episode_id,
"task": ep["task"],
"seed": ep["seed"],
"score": score,
"total_steps": len(steps),
"started_at": ep["started_at"],
"ended_at": ep["ended_at"],
"steps": steps,
}
except ValueError as e:
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# βββ Static UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if os.path.exists("static"):
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
def serve_ui():
return FileResponse("static/index.html")
else:
@app.get("/")
def serve_fallback():
return {
"message": "Autonomy Calibration Environment API v1.0",
"docs": "/docs",
"tasks": list(TASK_REGISTRY.keys()),
}
def main():
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
if __name__ == "__main__":
main()
|