Skip to content

Conversation

@IlumCI
Copy link
Contributor

@IlumCI IlumCI commented Sep 26, 2025

Description

This PR introduces ElectionSwarm, a sophisticated multi-agent orchestrator selection system that implements democratic decision-making protocols for leadership selection in multi-agent workflows. The system enables agent voters to elect the best orchestrator candidate through various coordination algorithms, providing a structured approach to leadership selection.

Key Features Added:

  1. ElectionSwarm Core System (swarms/structs/election_swarm.py):

    • Democratic election workflow with voter registration and candidate presentation
    • Multiple election algorithms: Leader Election, Consensus Building, Director-CEO Matching
    • AGENTSNET-inspired message passing protocols for voter coordination
    • Structured voting with detailed reasoning, confidence scores, and candidate rankings
    • Vote counting system with dedicated vote counter role
    • Comprehensive election result tracking and presentation
  2. Vote Counter Integration:

    • New VoteCounterProfile dataclass for dedicated vote counting agents
    • VoteCountingResult dataclass for detailed vote analysis
    • Enhanced ElectionResult to include vote counting information
    • Automated vote counting and result presentation
  3. Real-World Example (examples/multi_agent/election_swarm/real_world_election.py):

    • Complete CEO election simulation with board of directors
    • Multiple candidate profiles with different leadership styles
    • Vote counter integration for transparent results
    • Elected CEO task execution with renewable energy market expansion
    • Silent operation with no print statements
  4. Documentation (docs/swarms/structs/election_swarm.md):

    • Comprehensive documentation with architecture diagrams
    • Usage examples and API reference
    • Quick start guide with import instructions
  5. Package Integration:

    • Added ElectionSwarm to swarms/structs/__init__.py exports
    • Proper module structure for public API access

Architecture:

graph TD
    A[User Task] --> B[ElectionSwarm]
    B --> C[Voter Registration]
    B --> D[Candidate Registration]
    C --> E[Agent Voters]
    D --> F[Orchestrator Candidates]
    E --> G[Message Passing Protocol]
    F --> G
    G --> H[AGENTSNET Communication]
    H --> I[Voting Process]
    I --> J[Election Algorithms]
    J --> K[Consensus Building]
    J --> L[Leader Election]
    J --> M[Matching Algorithm]
    J --> N[Coloring Algorithm]
    J --> O[Vertex Cover]
    K --> P[Election Result]
    L --> P
    M --> P
    N --> P
    O --> P
    P --> Q[Selected Orchestrator]
Loading

Technical Implementation:

  • Robust JSON Parsing: Handles LLM agent responses with multiple fallback strategies
  • Error Handling: Comprehensive exception handling for election processes
  • Type Safety: Full type annotations with Pydantic validation
  • Modular Design: Clean separation of concerns with dedicated roles
  • Extensible Architecture: Easy to add new election algorithms and voting methods

Issue

#957

Dependencies

  • No new external dependencies required
  • Uses existing Swarms framework components
  • Compatible with current Swarms architecture

Tag Maintainer

@kyegomez

Twitter Handle

x.com/IlumTheProtogen

Testing

The implementation includes:

  • Comprehensive error handling and validation
  • Real-world example demonstrating full workflow
  • Silent operation for production use
  • Type safety with Pydantic validation

Files Changed

  • swarms/structs/election_swarm.py - Core ElectionSwarm implementation
  • examples/multi_agent/election_swarm/real_world_election.py - Real-world CEO election example
  • docs/swarms/structs/election_swarm.md - Comprehensive documentation
  • swarms/structs/__init__.py - Added ElectionSwarm to exports
  • examples/multi_agent/election_swarm/basic_usage.py - Basic Usage example
  • examples/multi_agent/election_swarm/specialized_session.py - advanced(more complex) example
  • docs/mkdocs.yml - added election_swarm under advanced workflows

Usage Example

from swarms.structs import ElectionSwarm

# Create election swarm with voters and candidates
election = ElectionSwarm(
    voters=[voter1, voter2, voter3],
    candidates=[candidate1, candidate2],
    vote_counter=vote_counter
)

# Run election
result = election.run(
    task="Elect the best CEO for our company",
    election_type=ElectionAlgorithm.LEADER_ELECTION,
    max_rounds=3
)

# Get elected leader
winner = result.election_result.winner

This PR significantly enhances the Swarms framework with democratic decision-making capabilities, enabling more sophisticated multi-agent coordination and leadership selection.


📚 Documentation preview 📚: https://swarms--1095.org.readthedocs.build/en/1095/

@github-actions github-actions bot added documentation Improvements or additions to documentation structs labels Sep 26, 2025
from enum import Enum
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, Field

Check failure

Code scanning / Pyre

Undefined import Error

Undefined import [21]: Could not find a module corresponding to import pydantic.
DEFAULT_BATCH_SIZE = 25


class ElectionConfigModel(BaseModel):

Check failure

Code scanning / Pyre

Undefined or invalid type Error

Undefined or invalid type [11]: Annotation BaseModel is not defined as a type.
try:
import yaml

with open(self.config_file_path, "r", encoding="utf-8") as f:

Check failure

Code scanning / Pyre

Incompatible parameter type Error

Incompatible parameter type [6]: In call open, for 1st positional argument, expected Union[PathLike[bytes], PathLike[str], bytes, int, str] but got Optional[str].
try:
import yaml

config_dict = self.config.model_dump()

Check failure

Code scanning / Pyre

Undefined attribute Error

Undefined attribute [16]: ElectionConfigModel has no attribute model_dump.
def validate_config(self) -> List[str]:
errors = []
try:
self.config.model_validate(self.config.model_dump())

Check failure

Code scanning / Pyre

Undefined attribute Error

Undefined attribute [16]: ElectionConfigModel has no attribute model_validate.
- Verification Protocols: {vote_counter.verification_protocols}
"""

vote_counter.agent.system_prompt += context

Check failure

Code scanning / Pyre

Undefined attribute Error

Undefined attribute [16]: Optional has no attribute __iadd__.
election_logger.error(f"Failed to count votes with vote counter: {str(e)}")
# Fallback to basic counting
return VoteCountingResult(
counter_id=self.vote_counter.counter_id,

Check failure

Code scanning / Pyre

Undefined attribute Error

Undefined attribute [16]: Optional has no attribute counter_id.
# Fallback to basic counting
return VoteCountingResult(
counter_id=self.vote_counter.counter_id,
counter_name=self.vote_counter.name,

Check failure

Code scanning / Pyre

Undefined attribute Error

Undefined attribute [16]: Optional has no attribute name.

# Create counting result
counting_result = VoteCountingResult(
counter_id=self.vote_counter.counter_id,

Check failure

Code scanning / Pyre

Undefined attribute Error

Undefined attribute [16]: Optional has no attribute counter_id.
# Create counting result
counting_result = VoteCountingResult(
counter_id=self.vote_counter.counter_id,
counter_name=self.vote_counter.name,

Check failure

Code scanning / Pyre

Undefined attribute Error

Undefined attribute [16]: Optional has no attribute name.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation structs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant