Spaces:
Sleeping
Sleeping
File size: 3,872 Bytes
36c8ed0 285e101 36c8ed0 285e101 36c8ed0 285e101 36c8ed0 285e101 36c8ed0 285e101 36c8ed0 285e101 36c8ed0 285e101 36c8ed0 | 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 | """
server.py
---------
FastAPI server exposing the OpenEnv API endpoints:
POST /reset β reset environment with an episode_id
POST /step β take an action and return (obs, reward, done, info)
GET /state β return full internal state
GET / β health check (returns 200)
"""
from __future__ import annotations
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
from env.environment import ISSEnvironment
from env.objects import Action, Observation, Reward
app = FastAPI(title="ISS Safety Operations β OpenEnv API", version="1.0.0")
# Single global environment instance
env = ISSEnvironment()
# ---------------------------------------------------------------------------
# Request / Response models
# ---------------------------------------------------------------------------
class ResetRequest(BaseModel):
episode_id: str = "audit_001"
class ResetResponse(BaseModel):
observation: Observation
class StepRequest(BaseModel):
action_type: str
target_object_id: Optional[str] = None
target_module: Optional[str] = None
reasoning: str = "automated"
class StepResponse(BaseModel):
observation: Observation
reward: Reward
done: bool
info: dict
class StateResponse(BaseModel):
state: dict
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@app.get("/")
def health():
"""Health check β returns 200."""
return {"status": "ok", "environment": "iss-safety-operations", "version": "1.0.0"}
def _do_reset(episode_id: str) -> ResetResponse:
valid_episodes = ["audit_001", "emergency_001", "investigation_001"]
if episode_id not in valid_episodes:
raise HTTPException(
status_code=400,
detail=f"Invalid episode_id '{episode_id}'. Must be one of {valid_episodes}",
)
try:
obs = env.reset(episode_id)
return ResetResponse(observation=obs)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/reset", response_model=ResetResponse)
def reset_post(req: ResetRequest = None):
"""Reset the environment with the given episode_id."""
episode_id = req.episode_id if req else "audit_001"
return _do_reset(episode_id)
@app.get("/reset", response_model=ResetResponse)
def reset_get(episode_id: str = "audit_001"):
"""Reset the environment (GET variant for convenience)."""
return _do_reset(episode_id)
@app.post("/step", response_model=StepResponse)
def step(req: StepRequest):
"""Take one action in the environment."""
try:
action = Action(
action_type=req.action_type,
target_object_id=req.target_object_id,
target_module=req.target_module,
reasoning=req.reasoning,
)
obs, reward, done, info = env.step(action)
return StepResponse(observation=obs, reward=reward, done=done, info=info)
except RuntimeError as e:
raise HTTPException(status_code=400, detail=str(e))
except ValueError as e:
raise HTTPException(status_code=422, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/state", response_model=StateResponse)
def state():
"""Return the full internal environment state."""
try:
return StateResponse(state=env.state())
except RuntimeError as e:
raise HTTPException(status_code=400, detail=str(e))
# ---------------------------------------------------------------------------
# Run with: python server.py
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
|