import os import sys from fastapi import FastAPI from fastapi.responses import JSONResponse import uvicorn # Add parent directory to path so we can import env sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from env import FraudEnv from models import Action, Observation, Reward from typing import Optional app = FastAPI() # Global environment instance _env: Optional[FraudEnv] = None _task_level: str = "medium" _num_users: int = 5 @app.get("/") async def root(): return { "message": "Ecommerce Fraud RL Agent API", "endpoints": { "POST /reset": "Initialize the environment", "POST /step": "Execute one step in the environment", "GET /state": "Get current environment state", "GET /health": "Health check" } } @app.post("/reset") async def reset(): global _env, _task_level, _num_users _env = FraudEnv(task_level=_task_level, num_users=_num_users) obs = _env.reset() return { "observation": obs.model_dump(), "done": False, "info": {} } @app.post("/step") async def step(action: dict): global _env if _env is None: return JSONResponse( status_code=400, content={"error": "Environment not initialized. Call /reset first."} ) try: action_obj = Action(**action) next_obs, reward, done, info = _env.step(action_obj) return { "observation": next_obs.model_dump(), "reward": reward.value, "done": done, "info": info } except Exception as e: return JSONResponse( status_code=400, content={"error": str(e)} ) @app.get("/state") async def state(): global _env if _env is None: return JSONResponse( status_code=400, content={"error": "Environment not initialized. Call /reset first."} ) state_dict = _env.state() return state_dict @app.get("/health") async def health(): return {"status": "ok"} def main(): port = int(os.getenv("PORT", 7860)) uvicorn.run(app, host="0.0.0.0", port=port) if __name__ == "__main__": main()