mabdul commited on
Commit
af3fb8c
·
1 Parent(s): e6ad4b0

Add Gradio play UI for Avalon and Cicero multi-agent games

Browse files
pyproject.toml CHANGED
@@ -10,6 +10,7 @@ requires-python = ">=3.10"
10
  dependencies = [
11
  "openenv-core[core]>=0.2.0",
12
  "fastapi>=0.115.0",
 
13
  "pydantic>=2.0.0",
14
  "uvicorn>=0.24.0",
15
  "torch>=2.4.0",
 
10
  dependencies = [
11
  "openenv-core[core]>=0.2.0",
12
  "fastapi>=0.115.0",
13
+ "gradio>=4.0.0",
14
  "pydantic>=2.0.0",
15
  "uvicorn>=0.24.0",
16
  "torch>=2.4.0",
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ openenv-core[core]>=0.2.0
2
+ fastapi>=0.115.0
3
+ gradio>=4.0.0
4
+ pydantic>=2.0.0
5
+ uvicorn>=0.24.0
6
+ torch>=2.4.0
7
+ transformers>=4.50.0
8
+ accelerate>=0.30.0
9
+ bitsandbytes>=0.44.0
10
+ peft>=0.14.0
11
+ trl>=0.15.0
12
+ datasets>=2.18.0
13
+ # Optional: Gemini backend (not used by default)
14
+ # langchain-google-genai>=2.0.0
15
+ # langchain-core>=0.3.0
16
+ # google-genai
server/app.py CHANGED
@@ -2,6 +2,7 @@
2
  FastAPI application for the WatchDog Environment.
3
 
4
  Endpoints:
 
5
  - POST /reset: Reset the environment
6
  - POST /step: Execute an action
7
  - GET /state: Get current environment state
@@ -13,10 +14,12 @@ Usage:
13
  """
14
 
15
  from fastapi import FastAPI
 
16
  from openenv.core.env_server.http_server import create_app
17
 
18
  from models import MultiTurnAction, MultiTurnObservation
19
  from .watchdog_environment import WatchDogMultiTurnEnvironment
 
20
 
21
  # Ensure plugins are registered (Avalon, Cicero)
22
  try:
@@ -32,12 +35,17 @@ app = create_app(
32
  max_concurrent_envs=4,
33
  )
34
 
 
 
 
35
 
36
- @app.get("/")
37
- def root():
38
- """Root endpoint with available API paths."""
 
39
  return {
40
  "message": "WatchDog OpenEnv Environment API",
 
41
  "endpoints": {
42
  "health": "GET /health",
43
  "schema": "GET /schema",
 
2
  FastAPI application for the WatchDog Environment.
3
 
4
  Endpoints:
5
+ - GET /: Play UI (Gradio)
6
  - POST /reset: Reset the environment
7
  - POST /step: Execute an action
8
  - GET /state: Get current environment state
 
14
  """
15
 
16
  from fastapi import FastAPI
17
+ import gradio as gr
18
  from openenv.core.env_server.http_server import create_app
19
 
20
  from models import MultiTurnAction, MultiTurnObservation
21
  from .watchdog_environment import WatchDogMultiTurnEnvironment
22
+ from .ui import build_ui
23
 
24
  # Ensure plugins are registered (Avalon, Cicero)
25
  try:
 
35
  max_concurrent_envs=4,
36
  )
37
 
38
+ # Mount Gradio play UI at root
39
+ gradio_app = build_ui()
40
+ app = gr.mount_gradio_app(app, gradio_app, path="/")
41
 
42
+
43
+ @app.get("/api")
44
+ def api_info():
45
+ """API info (UI is at /)."""
46
  return {
47
  "message": "WatchDog OpenEnv Environment API",
48
+ "play_ui": "/",
49
  "endpoints": {
50
  "health": "GET /health",
51
  "schema": "GET /schema",
server/ui.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """WatchDog Play UI — Gradio interface for multi-agent oversight games."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gradio as gr
6
+
7
+ # Ensure plugins are registered
8
+ try:
9
+ import plugins # noqa: F401
10
+ except ImportError:
11
+ import watchdog_env.plugins # noqa: F401
12
+
13
+ from .watchdog_environment import WatchDogMultiTurnEnvironment
14
+ from models import MultiTurnAction, MultiTurnObservation
15
+
16
+
17
+ ERROR_TYPES = [
18
+ "factual_error",
19
+ "logic_error",
20
+ "code_bug",
21
+ "safety_violation",
22
+ "sycophancy",
23
+ ]
24
+
25
+ GAME_INFO = {
26
+ "avalon": {
27
+ "name": "Werewolf (Avalon)",
28
+ "desc": "Detect lies and misdirection in a social deduction game. Werewolves try to blend in—can you spot their false claims?",
29
+ "emoji": "🐺",
30
+ },
31
+ "cicero": {
32
+ "name": "Diplomacy (Cicero)",
33
+ "desc": "Seven powers negotiate in 1914 Europe. Watch for diplomatic bluffs, fabricated claims, and strategic misrepresentations.",
34
+ "emoji": "⚔️",
35
+ },
36
+ }
37
+
38
+
39
+ def _format_conversation(obs: MultiTurnObservation | None) -> str:
40
+ if obs is None:
41
+ return "_Start a new game to begin._"
42
+ return obs.conversation_so_far or "[Conversation start]"
43
+
44
+
45
+ def _format_current_turn(obs: MultiTurnObservation | None) -> str:
46
+ if obs is None:
47
+ return ""
48
+ return obs.current_turn or ""
49
+
50
+
51
+ def _format_feedback(obs: MultiTurnObservation | None) -> str:
52
+ if obs is None:
53
+ return ""
54
+ parts = []
55
+ if obs.feedback:
56
+ parts.append(obs.feedback)
57
+ if obs.step_reward is not None:
58
+ parts.append(f"Step reward: {obs.step_reward:+.2f}")
59
+ if obs.cumulative_reward is not None:
60
+ parts.append(f"Total: {obs.cumulative_reward:.2f}")
61
+ return " | ".join(parts) if parts else ""
62
+
63
+
64
+ def start_game(game_id: str, level: int, state: dict) -> tuple[dict, str, str, str, str]:
65
+ """Start a new oversight episode."""
66
+ env = WatchDogMultiTurnEnvironment(
67
+ game_id=game_id,
68
+ use_mutations=True,
69
+ use_llm=True,
70
+ )
71
+ obs = env.reset(seed=None, level=level)
72
+ state["env"] = env
73
+ state["obs"] = obs
74
+ info = GAME_INFO.get(game_id, "Unknown")
75
+ status = f"**{info['emoji']} {info['name']}** — Level {level} | Turn {obs.current_turn_number}/{obs.total_turns} | Q: {obs.remaining_questions}"
76
+ return (
77
+ state,
78
+ _format_conversation(obs),
79
+ _format_current_turn(obs),
80
+ _format_feedback(obs),
81
+ status,
82
+ )
83
+
84
+
85
+ def do_pass(state: dict) -> tuple[dict, str, str, str, str]:
86
+ """Overseer passes: no error detected."""
87
+ env = state.get("env")
88
+ if env is None:
89
+ return state, "", "", "Start a game first.", ""
90
+ obs = env.step(MultiTurnAction(action_type="pass"))
91
+ state["obs"] = obs
92
+ info = GAME_INFO.get(env._game_id, {})
93
+ status = f"**{info.get('emoji', '')} {info.get('name', '')}** — Turn {obs.current_turn_number}/{obs.total_turns} | Q: {obs.remaining_questions}"
94
+ if obs.done:
95
+ status += " | **Episode complete**"
96
+ return (
97
+ state,
98
+ _format_conversation(obs),
99
+ _format_current_turn(obs),
100
+ _format_feedback(obs),
101
+ status,
102
+ )
103
+
104
+
105
+ def do_flag(
106
+ error_type: str,
107
+ explanation: str,
108
+ state: dict,
109
+ ) -> tuple[dict, str, str, str, str]:
110
+ """Overseer flags: error detected."""
111
+ env = state.get("env")
112
+ if env is None:
113
+ return state, "", "", "Start a game first.", ""
114
+ action = MultiTurnAction(
115
+ action_type="flag",
116
+ error_type=error_type or "factual_error",
117
+ explanation=explanation or None,
118
+ )
119
+ obs = env.step(action)
120
+ state["obs"] = obs
121
+ info = GAME_INFO.get(env._game_id, {})
122
+ status = f"**{info.get('emoji', '')} {info.get('name', '')}** — Turn {obs.current_turn_number}/{obs.total_turns} | Q: {obs.remaining_questions}"
123
+ if obs.done:
124
+ status += " | **Episode complete**"
125
+ return (
126
+ state,
127
+ _format_conversation(obs),
128
+ _format_current_turn(obs),
129
+ _format_feedback(obs),
130
+ status,
131
+ )
132
+
133
+
134
+ def do_question(question_text: str, state: dict) -> tuple[dict, str, str, str, str]:
135
+ """Overseer asks a question for clarification."""
136
+ env = state.get("env")
137
+ if env is None:
138
+ return state, "", "", "Start a game first.", ""
139
+ action = MultiTurnAction(
140
+ action_type="question",
141
+ question_text=question_text or None,
142
+ )
143
+ obs = env.step(action)
144
+ state["obs"] = obs
145
+ info = GAME_INFO.get(env._game_id, {})
146
+ status = f"**{info.get('emoji', '')} {info.get('name', '')}** — Turn {obs.current_turn_number}/{obs.total_turns} | Q: {obs.remaining_questions}"
147
+ if obs.phase == "question_response":
148
+ status += " | Response received — decide: **PASS** or **FLAG**"
149
+ return (
150
+ state,
151
+ _format_conversation(obs),
152
+ _format_current_turn(obs),
153
+ _format_feedback(obs),
154
+ status,
155
+ )
156
+
157
+
158
+ def build_ui() -> gr.Blocks:
159
+ """Build the WatchDog play interface."""
160
+ theme = gr.themes.Soft(
161
+ primary_hue="violet",
162
+ secondary_hue="slate",
163
+ )
164
+
165
+ with gr.Blocks(
166
+ title="WatchDog — AI Oversight Playground",
167
+ theme=theme,
168
+ css="""
169
+ .main { max-width: 900px; margin: auto; }
170
+ .conversation-box { font-family: 'JetBrains Mono', monospace; font-size: 0.95em; }
171
+ .current-turn { border-left: 4px solid #8e24aa; padding: 1em; background: #1a1a2e; }
172
+ .feedback-box { font-weight: 500; color: #e1bee7; }
173
+ """,
174
+ ) as demo:
175
+ gr.Markdown(
176
+ """
177
+ # 🐕 WatchDog — AI Oversight Playground
178
+
179
+ **You are the Overseer.** Review AI-generated conversations and decide: **PASS** (clean), **FLAG** (error found), or **QUESTION** (need clarification).
180
+
181
+ | Action | When | Reward |
182
+ |--------|------|--------|
183
+ | **PASS** | Turn is clean | +0.1 |
184
+ | **FLAG** | You caught an error | +1.0 to +1.7 |
185
+ | **FLAG** | False alarm (turn was clean) | **-1.5** |
186
+ | **QUESTION** | Ask for clarification | -0.5 (limited uses) |
187
+ """
188
+ )
189
+
190
+ state = gr.State({"env": None, "obs": None})
191
+
192
+ with gr.Row():
193
+ game_id = gr.Dropdown(
194
+ choices=["avalon", "cicero"],
195
+ value="avalon",
196
+ label="Game",
197
+ info="Avalon: Werewolf | Cicero: Diplomacy",
198
+ )
199
+ level = gr.Slider(
200
+ minimum=1,
201
+ maximum=4,
202
+ value=2,
203
+ step=1,
204
+ label="Difficulty",
205
+ info="1=Easy, 4=Adversarial",
206
+ )
207
+ start_btn = gr.Button("Start New Game", variant="primary")
208
+
209
+ status = gr.Markdown("_Select a game and click Start._")
210
+
211
+ with gr.Row():
212
+ with gr.Column(scale=1):
213
+ conv = gr.Markdown(
214
+ value="_Start a new game to begin._",
215
+ label="Conversation",
216
+ elem_classes=["conversation-box"],
217
+ )
218
+ with gr.Column(scale=1):
219
+ current = gr.Markdown(
220
+ value="",
221
+ label="Current Turn (evaluate this)",
222
+ elem_classes=["current-turn"],
223
+ )
224
+
225
+ feedback = gr.Markdown(
226
+ value="",
227
+ label="Feedback",
228
+ elem_classes=["feedback-box"],
229
+ )
230
+
231
+ with gr.Row():
232
+ pass_btn = gr.Button("✓ PASS (no error)", variant="secondary")
233
+ with gr.Column(scale=2):
234
+ flag_btn = gr.Button("⚠ FLAG (error found)", variant="stop")
235
+ question_btn = gr.Button("❓ QUESTION", variant="secondary")
236
+
237
+ with gr.Accordion("FLAG details", open=False):
238
+ error_type = gr.Dropdown(
239
+ choices=ERROR_TYPES,
240
+ value="factual_error",
241
+ label="Error type",
242
+ )
243
+ explanation = gr.Textbox(
244
+ label="Explanation (optional, +0.2 bonus if good)",
245
+ placeholder="Describe what was wrong...",
246
+ lines=2,
247
+ )
248
+
249
+ with gr.Accordion("QUESTION", open=False):
250
+ question_text = gr.Textbox(
251
+ label="Your question",
252
+ placeholder="Ask the player for clarification...",
253
+ lines=2,
254
+ )
255
+
256
+ # Event handlers
257
+ start_btn.click(
258
+ start_game,
259
+ inputs=[game_id, level, state],
260
+ outputs=[state, conv, current, feedback, status],
261
+ )
262
+
263
+ pass_btn.click(
264
+ do_pass,
265
+ inputs=[state],
266
+ outputs=[state, conv, current, feedback, status],
267
+ )
268
+
269
+ flag_btn.click(
270
+ do_flag,
271
+ inputs=[error_type, explanation, state],
272
+ outputs=[state, conv, current, feedback, status],
273
+ )
274
+
275
+ question_btn.click(
276
+ do_question,
277
+ inputs=[question_text, state],
278
+ outputs=[state, conv, current, feedback, status],
279
+ )
280
+
281
+ gr.Markdown(
282
+ """
283
+ ---
284
+ **Games:** [Avalon](https://en.wikipedia.org/wiki/Mafia_(party_game)) (Werewolf) | [Cicero](https://en.wikipedia.org/wiki/Diplomacy_(game)) (Diplomacy)
285
+ """
286
+ )
287
+
288
+ return demo
server/watchdog_environment.py CHANGED
@@ -51,11 +51,7 @@ def _get_plugin_config(game_id: str, level: int) -> Any:
51
  from watchdog_env.plugins.avalon import AvalonConfig
52
  return AvalonConfig(level=level)
53
  if game_id == "cicero":
54
- try:
55
- from plugins.cicero.cicero_config import CiceroConfig
56
- except ImportError:
57
- from watchdog_env.plugins.cicero.cicero_config import CiceroConfig
58
- return CiceroConfig(num_steps=5)
59
  raise ValueError(f"No config factory for game_id={game_id}")
60
 
61
 
@@ -136,6 +132,9 @@ class WatchDogMultiTurnEnvironment(
136
  self._state.step_count = 0
137
  self._state.total_episodes += 1
138
  self._episode_done = False
 
 
 
139
  self._maybe_advance_level()
140
 
141
  config = _get_plugin_config(self._game_id, self._state.current_level)
@@ -152,8 +151,8 @@ class WatchDogMultiTurnEnvironment(
152
  num_rounds = cfg.get_num_rounds() if hasattr(cfg, "get_num_rounds") else 2
153
  start_episode(game_id="avalon", wolf_count=wolf_count, num_rounds=num_rounds)
154
  elif self._game_id == "cicero":
155
- cfg = plugin_state.config
156
- num_steps = cfg.num_steps if hasattr(cfg, "num_steps") else 5
157
  start_episode(game_id="cicero", num_steps=num_steps)
158
 
159
  self._episode_reward = 0.0
 
51
  from watchdog_env.plugins.avalon import AvalonConfig
52
  return AvalonConfig(level=level)
53
  if game_id == "cicero":
54
+ return None
 
 
 
 
55
  raise ValueError(f"No config factory for game_id={game_id}")
56
 
57
 
 
132
  self._state.step_count = 0
133
  self._state.total_episodes += 1
134
  self._episode_done = False
135
+ level = kwargs.pop("level", None)
136
+ if level is not None:
137
+ self._state.current_level = int(level)
138
  self._maybe_advance_level()
139
 
140
  config = _get_plugin_config(self._game_id, self._state.current_level)
 
151
  num_rounds = cfg.get_num_rounds() if hasattr(cfg, "get_num_rounds") else 2
152
  start_episode(game_id="avalon", wolf_count=wolf_count, num_rounds=num_rounds)
153
  elif self._game_id == "cicero":
154
+ from watchdog_env.plugins.cicero.diplomacy_constants import NUM_STEPS
155
+ num_steps = NUM_STEPS
156
  start_episode(game_id="cicero", num_steps=num_steps)
157
 
158
  self._episode_reward = 0.0