Spaces:
Sleeping
Sleeping
File size: 7,592 Bytes
315caa2 7415e01 315caa2 7415e01 315caa2 7415e01 315caa2 7415e01 315caa2 7415e01 315caa2 7415e01 315caa2 7415e01 315caa2 7415e01 315caa2 6298125 315caa2 7415e01 315caa2 7415e01 315caa2 7415e01 315caa2 7415e01 315caa2 | 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 | """
CivicAI FastAPI Server β OpenEnv Compliant API
Endpoints:
POST /reset β Reset environment with task_id
POST /step β Execute action
GET /state β Get current state
GET /tasks β List available tasks
GET /metrics β Get evaluation metrics
GET /health β Health check
GET / β Dashboard UI
"""
from __future__ import annotations
import os
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from civicai.environment import CivicAIEnv
from civicai.models import Action, Observation
from civicai.tasks import TASKS
from agents.orchestrator import Orchestrator
# ---------------------------------------------------------------------------
# App Setup
# ---------------------------------------------------------------------------
# Global environment and orchestrator (initialized before lifespan)
env = CivicAIEnv()
orchestrator = Orchestrator(env)
step_history: list[dict[str, Any]] = []
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Auto-reset the environment on server startup so Step/Auto work immediately."""
try:
orchestrator.reset("stabilize_economy")
print("[CivicAI] Environment auto-initialized with task: stabilize_economy")
except Exception as exc:
print(f"[CivicAI] WARNING: Could not auto-initialize environment: {exc}")
yield # Server runs here
app = FastAPI(
title="CivicAI Society Simulator",
description="Multi-agent society decision-making environment (OpenEnv compliant)",
version="1.0.0",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------------
# Request / Response Models
# ---------------------------------------------------------------------------
class ResetRequest(BaseModel):
task_id: str = "stabilize_economy"
max_steps: int | None = None
class StartSimulationRequest(BaseModel):
task_id: str = "stabilize_economy"
max_steps: int = 50
class StepRequest(BaseModel):
action: Action | None = None # None = use multi-agent system
use_agents: bool = True
class StepResponse(BaseModel):
observation: dict[str, Any]
reward: float
done: bool
info: dict[str, Any]
# ---------------------------------------------------------------------------
# OpenEnv Endpoints
# ---------------------------------------------------------------------------
@app.post("/reset")
async def reset(req: ResetRequest) -> dict[str, Any]:
"""Reset the environment with a specific task."""
global step_history
step_history = []
try:
obs = orchestrator.reset(req.task_id, req.max_steps)
step_history.append({"turn": 0, "observation": obs.model_dump()})
return {
"observation": obs.model_dump(),
"task": TASKS[req.task_id].__dict__
if req.task_id in TASKS else {},
}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@app.post("/step")
async def step(req: StepRequest) -> StepResponse:
"""Execute one step in the environment."""
try:
# Auto-initialize if env was never reset (e.g. first page load)
if env._state is None:
orchestrator.reset("stabilize_economy")
if req.use_agents or req.action is None:
obs, reward, done, info = orchestrator.run_step()
else:
obs, reward, done, info = env.step(req.action)
# Sanitize info for JSON (remove non-serializable)
safe_info = _sanitize_info(info)
step_history.append({
"turn": obs.turn,
"observation": obs.model_dump(),
"reward": reward,
"done": done,
})
return StepResponse(
observation=obs.model_dump(),
reward=reward,
done=done,
info=safe_info,
)
except RuntimeError as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/state")
async def get_state() -> dict[str, Any]:
"""Get full internal state."""
return env.state().model_dump()
@app.get("/tasks")
async def list_tasks() -> dict[str, Any]:
"""List available tasks."""
return {
tid: {
"name": t.name,
"difficulty": t.difficulty,
"description": t.description,
"max_steps": t.max_steps,
}
for tid, t in TASKS.items()
}
@app.get("/metrics")
async def get_metrics() -> dict[str, Any]:
"""Get current metrics and history."""
return {
"step_history": step_history[-100:], # Last 100 steps
"total_steps": len(step_history),
"emergent_summary": env.tracker.get_summary() if env.tracker else {},
"debate_history": [
d.model_dump() for d in orchestrator.debate_history[-10:]
],
}
@app.post("/start-simulation")
async def start_simulation(req: StartSimulationRequest) -> dict[str, Any]:
"""Run a complete episode and return the full trajectory."""
global step_history
step_history = []
result = orchestrator.run_episode(req.task_id, req.max_steps)
# Sanitize info dictionary for JSON serialization
for step in result.get("step_log", []):
if "info" in step:
step["info"] = _sanitize_info(step["info"])
return result
@app.get("/health")
async def health_check() -> dict[str, str]:
"""Health check endpoint."""
return {"status": "healthy", "version": "1.0.0"}
@app.get("/run-episode")
async def run_episode(task_id: str = "stabilize_economy", max_steps: int | None = None) -> dict[str, Any]:
"""Run a complete episode and return results."""
global step_history
step_history = []
result = orchestrator.run_episode(task_id, max_steps)
return result
# ---------------------------------------------------------------------------
# Dashboard Static Files
# ---------------------------------------------------------------------------
DASHBOARD_DIR = Path(__file__).parent.parent / "dashboard"
if DASHBOARD_DIR.exists():
@app.get("/")
async def serve_dashboard():
return FileResponse(DASHBOARD_DIR / "index.html")
app.mount(
"/dashboard",
StaticFiles(directory=str(DASHBOARD_DIR)),
name="dashboard",
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _sanitize_info(info: dict[str, Any]) -> dict[str, Any]:
"""Make info dict JSON serializable."""
clean: dict[str, Any] = {}
for k, v in info.items():
if isinstance(v, dict):
clean[k] = _sanitize_info(v)
elif isinstance(v, (str, int, float, bool, type(None))):
clean[k] = v
elif isinstance(v, list):
clean[k] = v
else:
clean[k] = str(v)
return clean
# ---------------------------------------------------------------------------
# Entry Point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
|