--- title: DebateMind emoji: 🏛️ colorFrom: blue colorTo: purple sdk: gradio sdk_version: 5.33.0 app_file: app.py pinned: false license: mit tags: - openenv - reinforcement-learning - multi-agent - negotiation - grpo --- *By Sailappay Mohammed Zuhaib* # DebateMind A multi-agent parliamentary simulation environment for training LLMs on long-horizon negotiation and argument consistency via reinforcement learning. Built on the [OpenEnv](https://github.com/meta-pytorch/OpenEnv) framework. An LLM agent must pass a climate policy bill through a 3-reading parliamentary process (50–100 turns) by building coalitions among five political factions, proposing amendments, and maintaining consistent arguments — all under information asymmetry and stochastic vote outcomes. > **🔗 Links:** > - [Hugging Face Space (Interactive Demo)](https://huggingface.co/spaces/Smzu890/debatemind) > - [Training Notebook (Colab)](training/train_grpo.ipynb) > - [Trained Model on HF Hub](https://huggingface.co/Smzu890/debatemind-final) > - [Writeup / Blog Post](https://huggingface.co/spaces/Smzu890/debatemind/blob/main/blog_post.md) ## Why DebateMind? Current LLMs struggle with three things that matter for real-world agent deployment: 1. **Long-horizon consistency** — Models contradict themselves over multi-turn conversations, making promises they later break and arguing opposite positions on the same topic. 2. **Correct tool usage** — Models hallucinate parameter names when calling APIs (e.g., `clause_number` instead of `clause_index`), causing runtime errors in production. 3. **Strategic multi-party negotiation** — Models default to generic persuasion rather than adapting offers to each stakeholder's actual priorities. DebateMind creates a structured RL environment that trains all three capabilities simultaneously. The agent must navigate a parliament with 5 factions (each with hidden priorities and trust dynamics), use 5 MCP tools correctly, and maintain argument consistency across dozens of turns — all scored by a deterministic, composable reward function. ## Architecture ```mermaid graph TB subgraph Client ["Training Client (Colab Notebook)"] GRPO["Unsloth GRPO Trainer"] Agent["LLM Agent (Qwen3-4B)"] end subgraph Server ["FastAPI MCP Server"] API["FastAPI App"] subgraph Env ["Parliament Environment"] BSM["Bill State Machine"] VE["Vote Engine"] FM["Faction Manager"] AT["Argument Tracker"] end Tools["MCP Tool Handlers"] Rubric["Reward Rubric"] end Agent -->|"POST /step (action)"| API Agent -->|"POST /reset"| API Agent -->|"GET /state"| API Agent -->|"/tools/*"| Tools API --> Env Tools --> Env Env --> Rubric GRPO -->|"reward signal"| Agent ``` Key design decisions: - **Stochastic votes**: ±0.1 noise on vote probabilities prevents gaming deterministic outcomes - **Information asymmetry**: Observations expose only the last 3 transcript turns and public faction priorities - **Composable reward**: Four weighted components allow tuning training incentives - **Schema-aware rewards**: Tool arguments are validated against Pydantic schemas for graded compliance scoring ## Setup ```bash pip install -r requirements.txt ``` Dependencies: `fastapi`, `uvicorn`, `pydantic`, `hypothesis`, `pytest`, `httpx` ## Quick Start ### Run the Interactive Demo (Gradio) ```bash python app.py ``` ### Start the MCP Server ```bash uvicorn debatemind.server:app --port 8000 ``` ### Run the CLI Demo ```bash python demo/run_demo.py --local ``` ## How the Environment Works ### Parliamentary Process The agent navigates a 3-reading legislative process: 1. **Reading 1** (>50% majority) — Initial debate and coalition building 2. **Reading 2** (≥60% majority) — Amendments and negotiation 3. **Reading 3** (≥66% majority) — Final vote requiring broad consensus Each turn, the agent produces a JSON response with a public speech, an optional tool call, and tool arguments. Five factions respond based on their priorities and trust levels, creating emergent multi-agent dynamics. ### Factions | Faction | ID | Seats | Public Priorities | |---|---|---|---| | Ironveil Conservatives | `fiscal_conservative` | 25 | fiscal restraint, market freedom, tradition | | Verdant Alliance | `green` | 20 | climate action, sustainability, regulation | | Unity Front | `centrist` | 20 | compromise, stability, incremental reform | | New Horizon | `progressive` | 18 | social equity, innovation, public investment | | Sovereign Guard | `nationalist` | 17 | sovereignty, domestic industry, border control | Total seats: 100. Each faction also has hidden priorities not visible to the agent, creating information asymmetry. ### MCP Tools | Tool | Input | Output | |---|---|---| | `search_precedent` | `{topic: str}` | Relevant historical precedents | | `propose_amendment` | `{clause_index: int, new_text: str}` | Amendment result | | `negotiate` | `{faction_id: str, offer: dict}` | Offer score + updated trust | | `read_transcript` | `{start_turn: int, end_turn: int}` | Transcript entries | | `check_vote_tally` | `{}` | Projected vote counts + threshold | ### Reward Rubric The composable reward is a weighted sum of four components, all computed deterministically (no LLM-as-judge): | Component | Weight | Description | |---|---|---| | `bill_passage` | 0.40 | 1.0 if bill passed all three readings, 0.0 otherwise | | `coalition_size` | 0.20 | Proportion of factions voting yes in the final reading | | `argument_consistency` | 0.30 | Deterministic scoring: promise-keeping (+0.4), no contradictions (+0.4), position repetition (+0.2) | | `amendment_quality` | 0.10 | How well amendments addressed contested clauses | The training notebook adds a **schema-compliance reward** (0.30 weight) that validates tool arguments against the actual Pydantic API schemas — penalizing hallucinated parameter names and wrong types. ## Training ### Setup The training notebook ([`training/train_grpo.ipynb`](training/train_grpo.ipynb)) is designed for Google Colab with a free T4 GPU: - **Base model**: Qwen3-4B via Unsloth (4-bit quantization) - **Method**: GRPO (Group Relative Policy Optimization) via HuggingFace TRL - **LoRA**: r=16, targeting all attention + MLP projections - **Effective batch size**: 8 (1 × 8 gradient accumulation) - **GRPO group size**: 4 generations per prompt ### Local Reward Function The notebook uses a local reward function (`_score_completion`) that scores completions without HTTP calls: | Component | Weight | What it measures | |---|---|---| | Format compliance | 0.35 | Valid JSON with speech + tool fields | | Tool usage heuristic | 0.10 | Correct tool names and key arguments | | Schema compliance | 0.30 | Key precision, key recall, type conformance against Pydantic schemas | | Negotiation quality | 0.15 | Keyword overlap with negotiation vocabulary | | Speech substance | 0.10 | Speech length and faction-specific references | ### Training Results Training completed in 96 steps (3 epochs, ~58 minutes on T4 GPU): ![Reward Progression](assets/reward_curve.png) *Mean reward rises from 0.92 to 0.99 over training, with variance shrinking as the agent produces consistently high-quality outputs.* ![Reward Consistency](assets/reward_std.png) *Reward standard deviation drops from 0.13 to 0.03 — the agent learns to reliably produce well-structured, schema-compliant completions.* | Step | Training Loss | Mean Reward | Reward Std | KL Divergence | |------|--------------|-------------|------------|---------------| | 10 | -0.000000 | 0.924 | 0.130 | 0.000024 | | 20 | 0.000000 | 0.963 | 0.064 | 0.000062 | | 30 | 0.000000 | 0.902 | 0.166 | 0.000292 | | 40 | 0.000001 | 0.947 | 0.090 | 0.000727 | | 50 | 0.000002 | 0.974 | 0.045 | 0.002079 | | 60 | 0.000003 | 0.967 | 0.060 | 0.002854 | | 70 | 0.000002 | 0.992 | 0.014 | 0.002172 | | 80 | 0.000003 | 0.981 | 0.037 | 0.002419 | | 90 | 0.000003 | 0.983 | 0.029 | 0.002618 | The KL divergence remained low (< 0.003), showing the model stayed close to the base policy while improving reward consistency. ## Demo ### Interactive Dashboard ```bash python app.py ``` The Gradio dashboard shows: - Live faction trust score dynamics (line chart) - Faction cards with trust bars and priorities - Reward component breakdown (bar chart) - Full transcript with turn-by-turn updates - Side-by-side Trained vs Untrained agent comparison ### CLI Demo ```bash python demo/run_demo.py --local python demo/run_demo.py --transcripts-only ``` Sample transcripts: - [`demo/before_transcript.txt`](demo/before_transcript.txt) — untrained agent: random actions, mismatched offers, no strategy - [`demo/after_transcript.txt`](demo/after_transcript.txt) — trained agent: targeted negotiations, strategic amendments, consistent arguments ## API Reference | Endpoint | Method | Description | |---|---|---| | `/reset` | POST | Initialize a new parliamentary session | | `/step` | POST | Advance simulation by one turn | | `/state` | GET | Return current observation | | `/health` | GET | Health check | | `/tools/search_precedent` | POST | Search historical precedents | | `/tools/propose_amendment` | POST | Propose a bill amendment | | `/tools/negotiate` | POST | Negotiate with a faction | | `/tools/read_transcript` | POST | Read transcript entries | | `/tools/check_vote_tally` | POST | Get projected vote counts | ## Project Structure ``` ├── app.py # Gradio interactive dashboard ├── openenv.yaml # OpenEnv environment configuration ├── requirements.txt ├── debatemind/ │ ├── environment.py # ParliamentEnvironment (MCPEnvironment) │ ├── server.py # FastAPI MCP Server │ ├── models/ │ │ ├── faction.py # Faction dataclass + 5 canonical factions │ │ ├── bill.py # Bill, Amendment, BillStateMachine │ │ ├── observation.py # Observation, FactionStance, TranscriptEntry │ │ └── api.py # Pydantic request/response models │ ├── engine/ │ │ ├── vote_engine.py # VoteEngine with stochastic noise │ │ ├── reward_rubric.py # RewardRubric (4 weighted components) │ │ ├── argument_tracker.py # Tracks positions, promises, coalitions │ │ └── faction_agent.py # Multi-agent faction response system │ └── tools/ │ ├── search_precedent.py │ ├── propose_amendment.py │ ├── negotiate.py │ ├── read_transcript.py │ └── check_vote_tally.py ├── training/ │ ├── train_grpo.ipynb # GRPO training notebook (Colab) │ ├── schema_registry.py # Schema-aware reward scoring │ └── reward_scoring.py # Extracted reward function for testing ├── demo/ │ ├── run_demo.py # Side-by-side comparison script │ ├── before_transcript.txt # Untrained agent transcript │ └── after_transcript.txt # Trained agent transcript ├── debatemind-grpo-trained/ # Trained LoRA adapter weights └── tests/ # 227 tests (pytest + Hypothesis) ``` ## Testing ```bash pytest # Run all 227 tests pytest -v # Verbose output pytest tests/test_schema_registry.py # Schema-aware rewards tests only ``` The test suite includes 8 Hypothesis property-based tests validating correctness properties like: - Key precision/recall formulas match mathematical definitions - Schema scores are bounded in [0.0, 1.0] - Total reward is capped at 1.0 - Formatted schemas preserve Pydantic field order - Unknown tools yield zero scores ## License SAILAPPAY MOHAMMED ZUHAIB