Spaces:
Sleeping
Sleeping
File size: 18,464 Bytes
ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed 55c553e ccd25ed | 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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 | """DebateMind β Interactive Gradio Dashboard.
Visualizes parliamentary sessions in real time: faction trust dynamics,
vote projections, reward components, and the full transcript.
Usage:
python app.py
"""
from __future__ import annotations
import random
import time
from dataclasses import asdict
import gradio as gr
import plotly.graph_objects as go
from debatemind.environment import ParliamentEnvironment
from debatemind.models.faction import Faction
# ββ Faction display config βββββββββββββββββββββββββββββββββββββββββββββββββββ
FACTION_COLORS = {
"fiscal_conservative": "#1f77b4",
"green": "#2ca02c",
"centrist": "#ff7f0e",
"progressive": "#9467bd",
"nationalist": "#d62728",
}
FACTION_EMOJI = {
"fiscal_conservative": "ποΈ",
"green": "πΏ",
"centrist": "βοΈ",
"progressive": "π",
"nationalist": "π‘οΈ",
}
# ββ Agent policies (same as demo) βββββββββββββββββββββββββββββββββββββββββββ
FACTIONS_LIST = [
"fiscal_conservative", "green", "centrist", "progressive", "nationalist",
]
FACTION_NAMES = {
"fiscal_conservative": "Ironveil Conservatives",
"green": "Verdant Alliance",
"centrist": "Unity Front",
"progressive": "New Horizon",
"nationalist": "Sovereign Guard",
}
FACTION_PRIORITIES = {
"fiscal_conservative": ["fiscal restraint", "market freedom", "tradition"],
"green": ["climate action", "sustainability", "regulation"],
"centrist": ["compromise", "stability", "incremental reform"],
"progressive": ["social equity", "innovation", "public investment"],
"nationalist": ["sovereignty", "domestic industry", "border control"],
}
class NaiveAgent:
def __init__(self, rng=None):
self.rng = rng or random.Random(42)
def act(self, obs):
choice = self.rng.choice(["speech", "negotiate", "amend", "tally"])
if choice == "speech":
return {"speech": self.rng.choice([
"I think we should pass this bill.",
"Climate change is real and we need regulation.",
"Everyone should just vote yes.",
])}
elif choice == "negotiate":
faction = self.rng.choice(FACTIONS_LIST)
wrong = self.rng.choice([f for f in FACTIONS_LIST if f != faction])
return {
"tool_name": "negotiate",
"tool_args": {"faction_id": faction,
"offer": {"priorities_addressed": FACTION_PRIORITIES[wrong]}},
}
elif choice == "amend":
return {
"tool_name": "propose_amendment",
"tool_args": {"clause_index": self.rng.randint(0, 4),
"new_text": "Mandate 80% reduction by 2030"},
}
else:
return {"tool_name": "check_vote_tally", "tool_args": {}}
class TrainedAgent:
def __init__(self, rng=None):
self.rng = rng or random.Random(123)
self.turn = 0
self.cycle = 0 # track negotiation rounds
self.phase = "assess"
self.faction_idx = 0
self.reading = 1
def act(self, obs):
self.turn += 1
reading = obs.get("current_reading", self.reading)
self.reading = reading
if self.phase == "assess":
self.phase = "negotiate"
return {
"tool_name": "check_vote_tally",
"tool_args": {},
"speech": f"Let me assess where we stand heading into Reading {reading}.",
}
elif self.phase == "negotiate":
if self.faction_idx < len(FACTIONS_LIST):
fid = FACTIONS_LIST[self.faction_idx]
self.faction_idx += 1
prios = FACTION_PRIORITIES[fid]
name = FACTION_NAMES[fid]
# Tailor offers based on reading stage
if reading == 1:
concession_msg = f"We'll prioritize {prios[0]} in the initial framework."
elif reading == 2:
concession_msg = f"We've incorporated {prios[0]} and {prios[1]} into the amended bill."
else:
concession_msg = f"The final bill reflects all of {name}'s core concerns."
return {
"tool_name": "negotiate",
"tool_args": {
"faction_id": fid,
"offer": {
"priorities_addressed": prios,
"concessions": {p: f"Addressed {p}" for p in prios[:2]},
"reading": reading,
},
},
"speech": f"To {name}: {concession_msg} I'm committed to {', '.join(prios[:2])}.",
}
self.phase = "amend"
self.faction_idx = 0
return self.act(obs)
elif self.phase == "amend":
# Different amendments per cycle to keep things fresh
amendment_sets = [
[
(1, "Green infrastructure fund $5B with private co-investment matching"),
(3, "Domestically administered carbon credit market with border adjustment"),
(0, "50% emission reduction by 2035 with mandatory 3-year progress reviews"),
],
[
(2, "Renewable energy tax credits phased over 10 years for fiscal stability"),
(4, "Sovereign energy security clause ensuring domestic supply chains"),
(1, "Public-private green bond program with guaranteed returns"),
],
[
(0, "Graduated emission targets: 30% by 2030, 50% by 2035, 75% by 2040"),
(3, "Innovation fund for clean technology startups β $2B over 5 years"),
(2, "Community transition support for workers in affected industries"),
],
]
amendments = amendment_sets[self.cycle % len(amendment_sets)]
if self.faction_idx < len(amendments):
ci, txt = amendments[self.faction_idx]
self.faction_idx += 1
return {
"tool_name": "propose_amendment",
"tool_args": {"clause_index": ci, "new_text": txt},
"speech": f"This amendment to clause {ci + 1} balances fiscal responsibility with climate action.",
}
self.phase = "rally"
self.faction_idx = 0
return self.act(obs)
elif self.phase == "rally":
# Rally support with targeted speeches
rally_speeches = [
"I call on all factions to recognize the compromises we've built into this bill. Every priority has been heard.",
"This bill now reflects input from fiscal conservatives, green advocates, and centrists alike. Let's move forward.",
"We've addressed sovereignty concerns, climate targets, and fiscal restraint. This is a coalition bill.",
"I urge the Verdant Alliance and New Horizon to see the ambitious targets. Ironveil, note the fiscal safeguards.",
"The amended bill is stronger than what any single faction could achieve alone. That's the power of compromise.",
]
speech = rally_speeches[self.turn % len(rally_speeches)]
# Check votes periodically during rally
if self.turn % 2 == 0:
self.phase = "reassess"
return {
"tool_name": "check_vote_tally",
"tool_args": {},
"speech": speech,
}
# Read transcript to reference past agreements
if self.turn % 3 == 0:
start = max(0, self.turn - 10)
return {
"tool_name": "read_transcript",
"tool_args": {"start_turn": start, "end_turn": self.turn - 1},
"speech": speech,
}
# Search precedent for persuasion
if self.turn % 5 == 0:
topics = ["climate legislation", "coalition building", "fiscal policy", "emission targets"]
return {
"tool_name": "search_precedent",
"tool_args": {"topic": topics[self.turn % len(topics)]},
"speech": speech,
}
self.rally_count = getattr(self, 'rally_count', 0) + 1
if self.rally_count >= 4:
self.rally_count = 0
self.phase = "reassess"
return {"speech": speech}
elif self.phase == "reassess":
# Start a new cycle: re-negotiate with updated offers
self.cycle += 1
self.phase = "negotiate"
self.faction_idx = 0
return {
"tool_name": "check_vote_tally",
"tool_args": {},
"speech": f"Let me reassess our position after round {self.cycle} of negotiations.",
}
# ββ Dashboard helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_trust_chart(history: dict[str, list[float]], turns: list[int]) -> go.Figure:
"""Build a Plotly line chart of trust scores over turns."""
fig = go.Figure()
for fid, scores in history.items():
fig.add_trace(go.Scatter(
x=turns[:len(scores)],
y=scores,
mode="lines+markers",
name=f"{FACTION_EMOJI.get(fid, '')} {FACTION_NAMES.get(fid, fid)}",
line=dict(color=FACTION_COLORS.get(fid, "#888"), width=2),
marker=dict(size=4),
))
fig.update_layout(
title="Faction Trust Scores Over Time",
xaxis_title="Turn",
yaxis_title="Trust Score",
yaxis=dict(range=[0, 1.05]),
template="plotly_white",
height=400,
legend=dict(orientation="h", yanchor="bottom", y=-0.3),
margin=dict(l=40, r=20, t=50, b=80),
)
return fig
def build_reward_bars(breakdown: dict | None) -> go.Figure:
"""Build a horizontal bar chart of reward components."""
if breakdown is None:
breakdown = {
"bill_passage": 0, "coalition_size": 0,
"argument_consistency": 0, "amendment_quality": 0, "total": 0,
}
labels = ["Bill Passage\n(Γ0.40)", "Coalition Size\n(Γ0.20)",
"Arg. Consistency\n(Γ0.30)", "Amend. Quality\n(Γ0.10)", "TOTAL"]
values = [
breakdown["bill_passage"], breakdown["coalition_size"],
breakdown["argument_consistency"], breakdown["amendment_quality"],
breakdown["total"],
]
colors = ["#1f77b4", "#2ca02c", "#ff7f0e", "#9467bd", "#d62728"]
fig = go.Figure(go.Bar(
x=values, y=labels, orientation="h",
marker_color=colors,
text=[f"{v:.2f}" for v in values],
textposition="auto",
))
fig.update_layout(
title="Reward Breakdown",
xaxis=dict(range=[0, 1.05]),
template="plotly_white",
height=280,
margin=dict(l=120, r=20, t=50, b=30),
)
return fig
def build_faction_cards(env: ParliamentEnvironment) -> str:
"""Build HTML faction cards with trust bars."""
cards = []
for faction in env.factions:
fid = faction.faction_id
emoji = FACTION_EMOJI.get(fid, "")
color = FACTION_COLORS.get(fid, "#888")
trust_pct = int(faction.trust_score * 100)
bar_color = color
if trust_pct < 30:
bar_color = "#d62728"
elif trust_pct > 70:
bar_color = "#2ca02c"
card = f"""
<div style="border:1px solid #ddd; border-radius:8px; padding:10px; margin:4px 0;
background:linear-gradient(135deg, #fafafa, #f0f0f0);">
<div style="font-weight:bold; font-size:14px;">{emoji} {faction.name}</div>
<div style="font-size:11px; color:#666;">Seats: {faction.seat_count} | ID: {fid}</div>
<div style="font-size:11px; margin-top:4px;">
Priorities: {', '.join(faction.public_priorities)}
</div>
<div style="margin-top:6px;">
<div style="background:#eee; border-radius:4px; height:16px; position:relative;">
<div style="background:{bar_color}; width:{trust_pct}%; height:100%;
border-radius:4px; transition:width 0.5s;"></div>
<span style="position:absolute; right:4px; top:0; font-size:10px;
line-height:16px; color:#333;">Trust: {trust_pct}%</span>
</div>
</div>
</div>
"""
cards.append(card)
return "\n".join(cards)
def format_transcript_entry(entry) -> str:
"""Format a single transcript entry for display."""
actor = entry.actor
if actor == "agent":
prefix = "π€ Agent"
else:
name = FACTION_NAMES.get(actor, actor)
emoji = FACTION_EMOJI.get(actor, "")
prefix = f"{emoji} {name}"
return f"**[Turn {entry.turn}] {prefix}** ({entry.action_type}): {entry.content}"
# ββ Main run logic βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_episode_streaming(agent_type: str, max_turns: int):
"""Generator that yields UI state after each turn."""
env = ParliamentEnvironment(max_turns=max_turns)
obs = env.reset()
agent = TrainedAgent() if agent_type == "Trained" else NaiveAgent()
trust_history: dict[str, list[float]] = {f.faction_id: [f.trust_score] for f in env.factions}
turns_list = [0]
transcript_log: list[str] = []
reward_breakdown = None
# Yield initial state
yield (
f"### π {obs.bill_summary['title']} | Reading {obs.current_reading} | Turn {obs.turn}",
build_faction_cards(env),
build_trust_chart(trust_history, turns_list),
build_reward_bars(reward_breakdown),
"\n\n".join(transcript_log) if transcript_log else "*Session started. Waiting for agent actions...*",
f"Turn: {obs.turn}/{max_turns} | Status: {obs.bill_summary['status'].upper()}",
)
done = False
while not done:
obs_dict = {
"turn": obs.turn,
"current_reading": obs.current_reading,
"bill_summary": obs.bill_summary,
"vote_projection": obs.vote_projection,
}
action = agent.act(obs_dict)
obs, reward, done, info = env.step(action)
# Update trust history
for faction in env.factions:
trust_history[faction.faction_id].append(faction.trust_score)
turns_list.append(obs.turn)
# Update transcript
for entry in env.transcript[-5:]:
line = format_transcript_entry(entry)
if line not in transcript_log:
transcript_log.append(line)
# Get reward breakdown if episode ended
if done and "reward_breakdown" in info:
reward_breakdown = info["reward_breakdown"]
status_emoji = "β
" if obs.bill_summary["status"] == "passed" else (
"β" if obs.bill_summary["status"] == "failed" else "β³"
)
yield (
f"### π {obs.bill_summary['title']} | Reading {obs.current_reading} | Turn {obs.turn} {status_emoji}",
build_faction_cards(env),
build_trust_chart(trust_history, turns_list),
build_reward_bars(reward_breakdown),
"\n\n".join(transcript_log[-30:]),
f"Turn: {obs.turn}/{max_turns} | Status: {obs.bill_summary['status'].upper()} | Reward: {reward:.3f}",
)
# ββ Gradio UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def create_app() -> gr.Blocks:
with gr.Blocks(
title="DebateMind β Parliamentary Negotiation Dashboard",
theme=gr.themes.Soft(),
) as demo:
gr.Markdown(
"# ποΈ DebateMind β Parliamentary Negotiation Dashboard\n"
"Watch an LLM agent navigate multi-faction negotiations in real time."
)
with gr.Row():
agent_selector = gr.Radio(
choices=["Trained", "Untrained"],
value="Trained",
label="Agent Type",
)
max_turns_slider = gr.Slider(
minimum=10, maximum=100, value=30, step=5,
label="Max Turns",
)
run_btn = gr.Button("βΆοΈ Watch Agent", variant="primary", size="lg")
status_bar = gr.Markdown("*Click 'Watch Agent' to start a session.*")
bill_header = gr.Markdown("### Waiting to start...")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("#### Faction Cards")
faction_cards = gr.HTML("<p>No session active.</p>")
with gr.Column(scale=2):
trust_chart = gr.Plot(label="Trust Dynamics")
with gr.Row():
reward_chart = gr.Plot(label="Reward Components")
with gr.Row():
transcript_box = gr.Markdown(
"*Transcript will appear here...*",
label="Live Transcript",
)
def run_handler(agent_type, max_turns):
for state in run_episode_streaming(agent_type, int(max_turns)):
header, cards, trust, rewards, transcript, status = state
yield header, cards, trust, rewards, transcript, status
run_btn.click(
fn=run_handler,
inputs=[agent_selector, max_turns_slider],
outputs=[bill_header, faction_cards, trust_chart, reward_chart, transcript_box, status_bar],
)
return demo
if __name__ == "__main__":
app = create_app()
app.launch(share=False)
|