Spaces:
Sleeping
Sleeping
Download app.py from Smzu890/DebateMind: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/spaces/Smzu890/DebateMind/resolve/main/app.py
- Command line
-
hf download hf://spaces/Smzu890/DebateMind/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Smzu890/DebateMind/resolve/main/app.py
18.5 kB
| """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) | |