DebateMind / README.md
smzuhaib06
Deploy DebateMind Gradio dashboard
0325991
|
Raw History Blame Contribute Delete
12.2 kB
---
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