astroocra commited on
Commit
417ca84
Β·
1 Parent(s): edd4611
Files changed (1) hide show
  1. server/app.py +47 -120
server/app.py CHANGED
@@ -1,165 +1,92 @@
1
-
2
- """FastAPI app for the Eco-LLM Inference Routing environment."""
3
  from __future__ import annotations
4
 
 
 
 
 
5
  from openenv.core.env_server.http_server import create_app
6
- from fastapi.responses import RedirectResponse
7
 
 
8
  from server.env import EcoLLMInferenceRoutingEnvironment
9
  from server.models import RLAction, RLObservation, Strategy, ModelChoice
10
 
11
- import gradio as gr
12
- from gradio.routes import mount_gradio_app
13
-
14
-
15
- # πŸ”₯ OpenEnv app (DO NOT CHANGE)
16
- app = create_app(
17
- EcoLLMInferenceRoutingEnvironment,
18
- RLAction,
19
- RLObservation,
20
- env_name="eco_llm_inference_routing",
21
- max_concurrent_envs=4,
22
- )
23
-
24
 
25
  # βœ… REQUIRED FOR EVALUATOR
26
  @app.get("/health")
27
  def health():
28
  return {"status": "ok"}
29
 
30
-
31
- # πŸ”₯ FORCE ROOT β†’ YOUR UI (IMPORTANT FIX)
32
- @app.get("/", include_in_schema=False)
33
- def root():
34
- return RedirectResponse(url="/ui")
35
-
36
-
37
  # ─────────────────────────────────────────
38
- # 🎯 YOUR UI
39
  # ─────────────────────────────────────────
40
 
41
  def reset_demo(task_id: str, state: dict) -> tuple:
42
  demo_env = EcoLLMInferenceRoutingEnvironment()
43
  obs = demo_env.reset(task_id=task_id)
44
-
45
- updated_state = {
46
- "env": demo_env,
47
- "obs": obs,
48
- "history": [],
49
- "total_reward": 0.0,
50
- }
51
-
52
- log = f"πŸ”„ Reset β€” Task: {task_id} ({demo_env.current_task.difficulty})\n"
53
- log += f"πŸ“‹ Query: {obs.query}\n"
54
- log += f"🌍 Carbon intensity: {obs.carbon_intensity:.2f}\n"
55
- log += f"πŸ’Ύ Cache: {obs.cache_contents or 'empty'}\n"
56
- log += f"πŸ”Œ KB available: {obs.kb_available}"
57
-
58
  return log, "", 0.0, updated_state
59
 
60
-
61
  def step_demo(strategy: str, model: str, exit_flag: bool, state: dict) -> tuple:
62
  demo_env = state.get("env")
63
-
64
- if demo_env is None or state.get("obs") is None:
65
- return "⚠️ Click Reset first!", "", 0.0, state
66
-
67
- obs = state["obs"]
68
-
69
- if obs.done:
70
- return "βœ… Episode done β€” click Reset to start again.", "", state.get("total_reward", 0.0), state
71
-
72
- action = RLAction(
73
- strategy=Strategy(strategy),
74
- model_choice=ModelChoice(model),
75
- exit_flag=exit_flag,
76
- )
77
-
78
  new_obs = demo_env.step(action)
79
  rd = new_obs.reward_details
80
  total_reward = state.get("total_reward", 0.0) + rd.total_reward
 
 
 
81
 
82
- history = list(state.get("history", []))
83
-
84
- history.append(
85
- f"Step {len(history)+1}: {strategy}+{model} β†’ reward={rd.total_reward:+.3f} "
86
- f"({'βœ…' if rd.correct else '❌'})"
87
- )
88
-
89
- log = "\n".join(history) + "\n\n"
90
-
91
- if not new_obs.done:
92
- log += f"πŸ“‹ Next query: {new_obs.query}\n"
93
- log += f"🌍 Carbon intensity: {new_obs.carbon_intensity:.2f}\n"
94
- log += f"πŸ’Ύ Cache: {new_obs.cache_contents or 'empty'}\n"
95
- log += f"πŸ”Œ KB available: {new_obs.kb_available}"
96
- else:
97
- log += "βœ… Episode complete!"
98
-
99
- breakdown = (
100
- f"score={rd.score:.1f} "
101
- f"energy_cost={rd.energy_cost:.2f} "
102
- f"carbon_penalty={rd.carbon_penalty:.3f} "
103
- f"latency_penalty={rd.latency_penalty:.3f} "
104
- f"bonuses={rd.bonuses:.2f} "
105
- f"β†’ total={rd.total_reward:+.3f}"
106
- )
107
-
108
- updated_state = {
109
- "env": demo_env,
110
- "obs": new_obs,
111
- "history": history,
112
- "total_reward": total_reward,
113
- }
114
-
115
- return log, breakdown, round(total_reward, 3), updated_state
116
-
117
-
118
- # πŸ”₯ UI
119
  with gr.Blocks(title="Eco-LLM Routing") as demo:
120
  demo_state = gr.State({"env": None, "obs": None, "history": [], "total_reward": 0.0})
121
-
122
- gr.Markdown("# 🌱 Eco-LLM Inference Routing Environment")
123
-
124
  with gr.Row():
125
- task_selector = gr.Dropdown(
126
- choices=["task_1", "task_2", "task_3"],
127
- value="task_1",
128
- label="Task"
129
- )
130
  reset_btn = gr.Button("πŸ”„ Reset", variant="primary")
131
-
132
- obs_box = gr.Textbox(label="State", lines=6, interactive=False)
133
-
134
  with gr.Row():
135
- strategy_dd = gr.Dropdown(
136
- choices=["NONE", "USE_CACHE", "DO_CASCADE", "EARLY_EXIT", "WAIT", "CALL_KB"],
137
- value="NONE",
138
- label="Strategy"
139
- )
140
- model_dd = gr.Dropdown(
141
- choices=["SMALL", "MEDIUM", "LARGE"],
142
- value="SMALL",
143
- label="Model"
144
- )
145
  exit_cb = gr.Checkbox(label="Exit Flag", value=False)
146
-
147
  step_btn = gr.Button("▢️ Step")
148
- reward_box = gr.Textbox(label="Reward", interactive=False)
149
- total_num = gr.Number(label="Total", interactive=False)
150
 
151
  reset_btn.click(reset_demo, [task_selector, demo_state], [obs_box, reward_box, total_num, demo_state])
152
  step_btn.click(step_demo, [strategy_dd, model_dd, exit_cb, demo_state], [obs_box, reward_box, total_num, demo_state])
153
 
 
 
 
 
 
 
 
154
 
155
- # πŸ”₯ Mount UI safely
156
- app = mount_gradio_app(app, demo, path="/ui")
 
 
 
 
 
 
 
 
157
 
158
 
159
  def main(host: str = "0.0.0.0", port: int = 7860) -> None:
160
- import uvicorn
161
  uvicorn.run(app, host=host, port=port)
162
 
163
-
164
  if __name__ == "__main__":
165
- main()
 
1
+ """Full FastAPI app for the Eco-LLM Inference Routing environment."""
 
2
  from __future__ import annotations
3
 
4
+ import uvicorn
5
+ import gradio as gr
6
+ from fastapi import FastAPI
7
+ from gradio.routes import mount_gradio_app
8
  from openenv.core.env_server.http_server import create_app
 
9
 
10
+ # Your local logic imports
11
  from server.env import EcoLLMInferenceRoutingEnvironment
12
  from server.models import RLAction, RLObservation, Strategy, ModelChoice
13
 
14
+ # 1. Create the Master App FIRST
15
+ app = FastAPI()
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  # βœ… REQUIRED FOR EVALUATOR
18
  @app.get("/health")
19
  def health():
20
  return {"status": "ok"}
21
 
 
 
 
 
 
 
 
22
  # ─────────────────────────────────────────
23
+ # 🎯 GRADIO UI DEFINITION
24
  # ─────────────────────────────────────────
25
 
26
  def reset_demo(task_id: str, state: dict) -> tuple:
27
  demo_env = EcoLLMInferenceRoutingEnvironment()
28
  obs = demo_env.reset(task_id=task_id)
29
+ updated_state = {"env": demo_env, "obs": obs, "history": [], "total_reward": 0.0}
30
+
31
+ log = f"πŸ”„ Reset β€” Task: {task_id}\nπŸ“‹ Query: {obs.query}\n🌍 Carbon: {obs.carbon_intensity:.2f}"
 
 
 
 
 
 
 
 
 
 
 
32
  return log, "", 0.0, updated_state
33
 
 
34
  def step_demo(strategy: str, model: str, exit_flag: bool, state: dict) -> tuple:
35
  demo_env = state.get("env")
36
+ if not demo_env: return "⚠️ Reset first!", "", 0.0, state
37
+
38
+ action = RLAction(strategy=Strategy(strategy), model_choice=ModelChoice(model), exit_flag=exit_flag)
 
 
 
 
 
 
 
 
 
 
 
 
39
  new_obs = demo_env.step(action)
40
  rd = new_obs.reward_details
41
  total_reward = state.get("total_reward", 0.0) + rd.total_reward
42
+
43
+ log = f"Step Result: {'βœ…' if rd.correct else '❌'}\nReward: {rd.total_reward:+.3f}"
44
+ return log, str(rd), round(total_reward, 3), {**state, "obs": new_obs, "total_reward": total_reward}
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  with gr.Blocks(title="Eco-LLM Routing") as demo:
47
  demo_state = gr.State({"env": None, "obs": None, "history": [], "total_reward": 0.0})
48
+ gr.Markdown("# 🌱 Eco-LLM Inference Routing")
49
+
 
50
  with gr.Row():
51
+ task_selector = gr.Dropdown(choices=["task_1", "task_2", "task_3"], value="task_1", label="Task")
 
 
 
 
52
  reset_btn = gr.Button("πŸ”„ Reset", variant="primary")
53
+
54
+ obs_box = gr.Textbox(label="State", lines=4, interactive=False)
55
+
56
  with gr.Row():
57
+ strategy_dd = gr.Dropdown(choices=["NONE", "USE_CACHE", "DO_CASCADE", "EARLY_EXIT", "WAIT", "CALL_KB"], value="NONE", label="Strategy")
58
+ model_dd = gr.Dropdown(choices=["SMALL", "MEDIUM", "LARGE"], value="SMALL", label="Model")
 
 
 
 
 
 
 
 
59
  exit_cb = gr.Checkbox(label="Exit Flag", value=False)
60
+
61
  step_btn = gr.Button("▢️ Step")
62
+ reward_box = gr.Textbox(label="Step Detail", interactive=False)
63
+ total_num = gr.Number(label="Total Reward", interactive=False)
64
 
65
  reset_btn.click(reset_demo, [task_selector, demo_state], [obs_box, reward_box, total_num, demo_state])
66
  step_btn.click(step_demo, [strategy_dd, model_dd, exit_cb, demo_state], [obs_box, reward_box, total_num, demo_state])
67
 
68
+ # ─────────────────────────────────────────
69
+ # πŸš€ ROUTING SETUP
70
+ # ─────────────────────────────────────────
71
+
72
+ # 2. MOUNT GRADIO TO THE ROOT ("/")
73
+ # This ensures Gradio's internal JS/CSS assets load without path issues.
74
+ app = mount_gradio_app(app, demo, path="/")
75
 
76
+ # 3. Create and mount OpenEnv to "/api"
77
+ # This keeps the environment logic accessible but gets its UI out of the way.
78
+ openenv_logic = create_app(
79
+ EcoLLMInferenceRoutingEnvironment,
80
+ RLAction,
81
+ RLObservation,
82
+ env_name="eco_llm_inference_routing",
83
+ max_concurrent_envs=4,
84
+ )
85
+ app.mount("/api", openenv_logic)
86
 
87
 
88
  def main(host: str = "0.0.0.0", port: int = 7860) -> None:
 
89
  uvicorn.run(app, host=host, port=port)
90
 
 
91
  if __name__ == "__main__":
92
+ main()