Spaces:
Runtime error
Runtime error
File size: 10,793 Bytes
3f757a4 ee3dd3b 96261ab 3f757a4 342dbfd ee3dd3b 96261ab ee3dd3b e8c9190 ee3dd3b e8c9190 ee3dd3b e8c9190 ee3dd3b e8c9190 ee3dd3b 3f757a4 96261ab ee3dd3b 96261ab 73ccac3 ee3dd3b 035acef | 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 | from __future__ import annotations
import os
from typing import Any
from fastapi import HTTPException
from openenv.core.env_server.http_server import create_app
from pydantic import BaseModel
import uvicorn
from graders import GRADERS, grade_easy
from server.env import EcoLLMInferenceRoutingEnvironment
from server.models import ModelChoice, RLAction, RLObservation, RLState, Strategy
from tasks import TASKS as VALIDATOR_TASKS
from tasks import TASK_REGISTRY
app = create_app(
EcoLLMInferenceRoutingEnvironment,
RLAction,
RLObservation,
env_name="eco_llm_inference_routing",
max_concurrent_envs=4,
)
_TASK_META = [
{
**task,
"grader": task.get("grader_path", "unknown"),
"graders": task.get("grader_paths", []),
}
for task in VALIDATOR_TASKS
]
_ACTION_SPACE = {
"strategy": [strategy.value for strategy in Strategy],
"model_choice": [model.value for model in ModelChoice],
"exit_flag": "boolean",
}
_ENDPOINTS = {
"reset": {"method": "POST", "path": "/reset"},
"step": {"method": "POST", "path": "/step"},
"state": {"method": "GET", "path": "/state"},
"tasks": {"method": "GET", "path": "/tasks"},
"tasks_meta": {"method": "GET", "path": "/tasks/meta"},
"metadata": {"method": "GET", "path": "/metadata"},
"schema": {"method": "GET", "path": "/schema"},
"grader": {"method": "POST", "path": "/grader"},
"grade": {"method": "POST", "path": "/grade"},
"grader_replay": {"method": "POST", "path": "/grader/replay"},
"docs": {"method": "GET", "path": "/docs"},
}
class ResetRequest(BaseModel):
task_id: str | None = None
seed: int | None = None
episode_id: str | None = None
class GradeRequest(BaseModel):
task_id: str
episode_id: str = ""
rewards: list[float] = []
steps: int = 0
success: bool = False
state: dict[str, Any] = {}
class ReplayAction(BaseModel):
strategy: str
model_choice: str
exit_flag: bool = False
class ReplayRequest(BaseModel):
task_id: str
actions: list[ReplayAction]
@app.get("/")
def root() -> dict[str, Any]:
return {
"status": "ok",
"service": "eco_llm_inference_routing",
"docs": "/docs",
"metadata": "/metadata",
"tasks": "/tasks",
}
@app.get("/health")
def health() -> dict[str, str]:
return {"status": "healthy"}
@app.get("/metadata")
def metadata() -> dict[str, Any]:
return {
"name": "eco_llm_inference_routing",
"description": "Carbon-aware RL environment for multi-objective LLM query routing",
"version": "1.0.0",
"domain": "llm systems optimization",
"deterministic": True,
"observation_highlights": [
"query text",
"carbon intensity",
"cache contents",
"knowledge-base availability",
"structured reward breakdown",
],
"action_space": _ACTION_SPACE,
"endpoints": _ENDPOINTS,
"tasks": _TASK_META,
"reward_range": [0.0, 1.0],
}
@app.get("/schema")
def schema() -> dict[str, Any]:
return {
"action_schema": RLAction.model_json_schema(),
"observation_schema": RLObservation.model_json_schema(),
"state_schema": RLState.model_json_schema(),
}
@app.get("/tasks")
def list_tasks() -> list[dict[str, Any]]:
return _TASK_META
@app.get("/task_ids")
def list_task_ids() -> list[str]:
return list(TASK_REGISTRY.keys())
@app.get("/tasks/meta")
def list_tasks_meta() -> dict[str, Any]:
return {
"tasks": _TASK_META,
"count": len(_TASK_META),
"available_task_ids": [task["id"] for task in _TASK_META],
}
@app.get("/tasks/{task_id}")
def get_task(task_id: str) -> dict[str, Any]:
for task in _TASK_META:
if task["id"] == task_id:
return task
raise HTTPException(status_code=404, detail=f"Unknown task '{task_id}'")
def _grade_payload(request: GradeRequest) -> dict[str, Any]:
fn = GRADERS.get(request.task_id)
if fn is None:
raise HTTPException(
status_code=400,
detail=f"Invalid task_id '{request.task_id}'. Valid: {sorted(GRADERS)}",
)
total_reward = sum(request.rewards)
score = float(fn(request.state, total_reward))
return {
"score": round(score, 4),
"task_id": request.task_id,
"success": score >= 0.5,
"total_reward": round(total_reward, 4),
"steps": request.steps,
"reward": round(score, 4),
"normalized_reward": round(score, 4),
}
@app.post("/grader")
def grader_endpoint(request: GradeRequest) -> dict[str, Any]:
return _grade_payload(request)
@app.post("/grade")
def grade_endpoint(request: GradeRequest) -> dict[str, Any]:
return _grade_payload(request)
@app.post("/grader/replay")
def grader_replay(request: ReplayRequest) -> dict[str, Any]:
if request.task_id not in TASK_REGISTRY:
raise HTTPException(status_code=400, detail=f"Invalid task_id: {request.task_id}")
env = EcoLLMInferenceRoutingEnvironment()
obs = env.reset(task_id=request.task_id)
rewards: list[float] = []
for action in request.actions:
if obs.done:
break
try:
obs = env.step(
RLAction(
strategy=Strategy(action.strategy),
model_choice=ModelChoice(action.model_choice),
exit_flag=action.exit_flag,
)
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=f"Invalid replay action: {exc}") from exc
rewards.append(float(obs.reward))
total_reward = sum(rewards)
fn = GRADERS.get(request.task_id, grade_task_1)
score = float(fn({}, total_reward))
return {
"score": round(score, 4),
"task_id": request.task_id,
"success": score >= 0.5,
"total_reward": round(total_reward, 4),
"steps": len(rewards),
}
def main() -> None:
port = int(os.getenv("PORT", "7860"))
uvicorn.run("server.app:app", host="0.0.0.0", port=port)
if __name__ == "__main__":
main()
# ββ Gradio UI (mounted at /ui β does NOT override any API routes) βββββββββββββ
try:
import gradio as gr
from gradio.routes import mount_gradio_app
from server.env import EcoLLMInferenceRoutingEnvironment
from server.models import RLAction, Strategy, ModelChoice
_env_store: dict = {}
def ui_reset(task_id: str) -> str:
env = EcoLLMInferenceRoutingEnvironment()
obs = env.reset(task_id=task_id)
_env_store["env"] = env
_env_store["rewards"] = []
_env_store["task_id"] = task_id
return (
f"β
Reset β {task_id} ({env.current_task.difficulty})\n"
f"Query : {obs.query}\n"
f"Carbon : {obs.carbon_intensity:.2f}\n"
f"Cache : {obs.cache_contents or 'empty'}\n"
f"KB avail : {obs.kb_available}\n"
f"Done : {obs.done}"
)
def ui_step(strategy: str, model: str, exit_flag: bool) -> str:
env = _env_store.get("env")
if env is None:
return "β οΈ Click Reset first."
if env._episode_complete:
rewards = _env_store.get("rewards", [])
total = sum(rewards)
return f"π Episode complete.\nTotal reward: {total:.3f}\nRewards: {rewards}"
try:
obs = env.step(RLAction(
strategy=Strategy(strategy),
model_choice=ModelChoice(model),
exit_flag=exit_flag,
))
except Exception as exc:
return f"β Error: {exc}"
_env_store.setdefault("rewards", []).append(obs.reward_details.total_reward)
rd = obs.reward_details
out = (
f"step reward : {rd.total_reward:+.3f} ({'β correct' if rd.correct else 'β wrong'})\n"
f" score : {rd.score}\n"
f" carbon pen: {rd.carbon_penalty:.3f}\n"
f" lat pen : {rd.latency_penalty:.3f}\n"
f" bonuses : {rd.bonuses:.3f}\n"
f" trace : {rd.strategy_trace}\n\n"
)
if obs.done:
total = sum(_env_store["rewards"])
out += f"π Done! Total reward: {total:.3f}"
else:
out += (
f"Next query : {obs.query}\n"
f"Carbon : {obs.carbon_intensity:.2f}\n"
f"Cache : {obs.cache_contents or 'empty'}\n"
f"KB avail : {obs.kb_available}"
)
return out
with gr.Blocks(title="π± Eco-LLM Routing") as _demo:
gr.Markdown(
"# π± Eco-LLM Inference Routing\n"
"Carbon-aware LLM query routing β balance **accuracy**, **energy**, **latency** & **carbon**.\n\n"
"**API endpoints:** `POST /reset` Β· `POST /step` Β· `GET /tasks` Β· `POST /grade`"
)
with gr.Row():
task_dd = gr.Dropdown(
choices=["task_1", "task_2", "task_3"],
value="task_1",
label="Task",
)
reset_btn = gr.Button("π Reset", variant="primary")
state_box = gr.Textbox(label="Environment State", lines=8, interactive=False)
gr.Markdown("### Take a Step")
with gr.Row():
strat_dd = gr.Dropdown(
choices=["NONE", "USE_CACHE", "DO_CASCADE", "EARLY_EXIT", "WAIT", "CALL_KB"],
value="NONE",
label="Strategy",
)
model_dd = gr.Dropdown(
choices=["SMALL", "MEDIUM", "LARGE"],
value="SMALL",
label="Model",
)
exit_cb = gr.Checkbox(label="exit_flag", value=False)
step_btn = gr.Button("βΆοΈ Step", variant="secondary")
result_box = gr.Textbox(label="Step Result", lines=10, interactive=False)
gr.Markdown(
"### Reward Formula\n"
"`reward = score β (carbon Γ energy) β (0.1 Γ latency) + bonuses`\n\n"
"| Model | Energy | Latency | | Strategy | Bonus |\n"
"|-------|--------|---------|--|----------|-------|\n"
"| SMALL | 0.1 | 1.0 | | USE_CACHE | +0.5 |\n"
"| MEDIUM | 0.3 | 2.0 | | EARLY_EXIT | +0.1 |\n"
"| LARGE | 0.6 | 5.0 | | CALL_KB | low cost |"
)
reset_btn.click(fn=ui_reset, inputs=[task_dd], outputs=[state_box])
step_btn.click(fn=ui_step, inputs=[strat_dd, model_dd, exit_cb], outputs=[result_box])
app = mount_gradio_app(app, _demo, path="/ui")
except ImportError:
pass # Gradio optional β API works without it |