# AgorAI: Democratic AI Through Multi-Agent Aggregation

[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: Research](https://img.shields.io/badge/License-Research-green.svg)](LICENSE)

AgorAI is a Python library for building fair, unbiased AI systems through democratic multi-agent opinion aggregation. It combines social choice theory, welfare economics, and modern LLMs to enable collective decision-making with provable fairness guarantees.

## 🎯 What is AgorAI?

AgorAI addresses a fundamental challenge in AI: **How do we make fair decisions when different perspectives disagree?**

Instead of relying on a single AI model's judgment, AgorAI:
1. Gathers opinions from multiple diverse agents (different models, cultural perspectives, or stakeholders)
2. Aggregates these opinions using mathematically rigorous methods from social choice theory
3. Produces decisions with provable fairness guarantees

**Perfect for:** AI researchers, ML engineers, and social scientists building fair multi-agent systems.

## 📦 Installation

```bash
pip install agorai[all]
```

**API Keys (Optional):**
- For LLM synthesis: `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or configure Ollama locally
- For counterfactual testing: `OPENAI_API_KEY` or `REPLICATE_API_TOKEN`

## 🚀 Quick Start

### Use Case 1: Aggregate Opinions from Multiple Agents

The most common use case - combine utilities/opinions from multiple agents:

```python
from agorai.aggregate import aggregate

# Three agents provide utilities for three candidates
utilities = [
    [0.8, 0.2, 0.5],  # Agent 1's utilities
    [0.3, 0.7, 0.4],  # Agent 2's utilities
    [0.6, 0.5, 0.9],  # Agent 3's utilities
]

# Use "fair" aggregation (Atkinson method)
result = aggregate(utilities, method="fair")
print(f"Winner: Candidate {result['winner']}")
print(f"Scores: {result['scores']}")
```

**Try different methods:**
```python
# Protect minorities
result = aggregate(utilities, method="minority-focused")  # Maximin

# Resist outliers
result = aggregate(utilities, method="robust")  # Robust Median

# Democratic voting
result = aggregate(utilities, method="democratic")  # Majority

# Or use technical names
result = aggregate(utilities, method="schulze_condorcet")
```

**See all options:** [Aggregation Methods Documentation](docs/core/aggregation.md)

---

### Use Case 2: Mitigate Bias Through Multi-Perspective Analysis

Detect and mitigate bias by synthesizing diverse cultural perspectives:

```python
from agorai.bias import mitigate_bias

# Analyze content from multiple cultural perspectives
result = mitigate_bias(
    input_text="Is this job posting discriminatory?",
    input_image=None,  # Optional: for multimodal analysis
    aggregation_method="fair",
    num_perspectives=5  # Generate 5 diverse cultural perspectives
)

print(f"Decision: {result['decision']}")
print(f"Confidence: {result['confidence']:.2%}")
print(f"Fairness metrics: {result['fairness_metrics']}")
```

**See full guide:** [Bias Mitigation Documentation](docs/applications/bias_mitigation.md)

---

## 📚 Documentation

### Core Functionality
- **[Aggregation Methods](docs/core/aggregation.md)** - All 14+ methods with parameters and examples
- **[Mechanism Aliases](docs/core/aliases.md)** - Intuitive names for aggregation methods
- **[Property Analysis](docs/core/properties.md)** - Select mechanisms based on theoretical properties

### Applications
- **[Bias Mitigation](docs/applications/bias_mitigation.md)** - Detect and mitigate AI bias
- **[Council Creation](docs/applications/automatic_council.md)** - Auto-generate diverse perspectives
- **[Counterfactual Testing](docs/applications/counterfactual_testing.md)** - Causal robustness evaluation

### Advanced Topics
- **[Queue Processing](docs/advanced/queue_processing.md)** - Batch operations and benchmarking
- **[Visualization](docs/advanced/visualization.md)** - Plots and explanations
- **[Custom Extensions](docs/advanced/extending.md)** - Add your own methods

### Reference
- **[API Reference](docs/reference/api.md)** - Complete function signatures
- **[Configuration](docs/reference/configuration.md)** - Environment variables and settings
- **[Examples](examples/)** - Code examples and demos

## 🎓 Key Concepts

### Aggregation Methods (14+ Available)

| Category | Methods | Use When |
|----------|---------|----------|
| **Social Choice** | Majority, Borda, Schulze, Approval | Democratic legitimacy, ranked preferences |
| **Welfare Economics** | Maximin, Atkinson | Fairness, inequality aversion, minority protection |
| **Machine Learning** | Robust Median, Consensus | Outlier resistance, ensemble predictions |
| **Game Theory** | Nash Bargaining, Veto Hybrid | Strategic settings, minority veto power |

**Full list:** [Aggregation Methods Documentation](docs/core/aggregation.md#available-methods)

### Why Democratic Aggregation?

**Problem:** Single AI models can be biased, unfair, or make decisions that don't align with diverse human values.

**Solution:** Democratic aggregation provides:
- ✅ **Fairness:** Mechanisms with provable properties (anonymity, Pareto efficiency, minority protection)
- ✅ **Diversity:** Incorporates multiple perspectives systematically
- ✅ **Transparency:** Clear mathematical procedures, not black-box decisions
- ✅ **Robustness:** Resistant to outliers and strategic manipulation

## 🔬 Research & Citations

AgorAI builds on decades of research in social choice theory, welfare economics, and multi-agent AI systems.

**Related Research:**
- Constitutional AI (Anthropic)
- Multi-agent reinforcement learning (MARL)
- Test-time compute scaling (OpenAI o1)
- Collective decision-making in AI

**Citing AgorAI:**
```bibtex
@software{agorai2025,
  author = {Schlenker, Samuel},
  title = {AgorAI: Democratic AI Through Multi-Agent Aggregation},
  year = {2025},
  url = {https://github.com/yourusername/agorai}
}
```

## 🤝 Contributing

Contributions for research and non-commercial purposes are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

**Areas where we'd love help:**
- Additional benchmark datasets
- New aggregation mechanisms
- Documentation improvements
- Bug reports and feature requests

## 📄 License

**Research and Non-Commercial License**

Copyright (c) 2025 Samuel Schlenker

Free for academic research, education, and non-commercial use. Commercial use requires prior written agreement.

See [LICENSE](LICENSE) for full terms.

## 📧 Contact

- **Issues:** [GitHub Issues](https://github.com/yourusername/agorai/issues)
- **Email:** samuel.schlenker@example.com

---

**Built with ❤️ for the democratic AI research community**
