Skip to content

Conversation

IlumCI
Copy link
Contributor

@IlumCI IlumCI commented Aug 27, 2025

Description

The hierarchical swarm system has been cleaned up by removing markdown functionality from the core implementation while maintaining API compatibility. The .md(true) method is preserved for existing code compatibility, but the actual markdown rendering has been removed to focus on core hierarchical multi-agent coordination.

How the Hierarchical Swarm Works

The hierarchical swarm is a sophisticated multi-agent system that follows a director-worker pattern for complex task execution. The system coordinates multiple specialized agents through a director that creates plans and distributes tasks.

Core Architecture

pub struct HierarchicalSwarm {
    pub name: String,
    pub description: String,
    pub director: AgentSpec,
    pub agents: Vec<AgentSpec>,
    pub max_loops: u32,
    pub verbose: bool,
    // ... other core fields for hierarchical coordination
}

impl HierarchicalSwarm {
    /// Creates a new HierarchicalSwarm with the given parameters
    pub fn new(...) -> Result<Self> {
        // Core hierarchical swarm initialization
    }

    /// Runs a task through the director agent
    pub async fn run_director(&self, task: &str) -> Result<SwarmSpecResponse> {
        // Director creates plan and distributes orders to agents
    }

    /// Executes the hierarchical swarm for specified feedback loops
    pub async fn run(&self, task: &str) -> Result<Vec<String>> {
        // Core execution logic for hierarchical coordination
    }
}

Key Features

  • Director-worker pattern for complex task coordination
  • Sequential or parallel agent execution
  • Feedback loops for iterative refinement
  • Comprehensive error handling and logging
  • Clean API for multi-agent orchestration

Code Samples

1. Basic Hierarchical Swarm Usage with Markdown Compatibility

use swarms_rs::structs::hierarchical_swarm::HierarchicalSwarmBuilder;

#[tokio::main]
async fn main() -> Result<()> {
    // Create hierarchical swarm with director and worker agents
    let swarm = HierarchicalSwarmBuilder::new()
        .name("Research Swarm")
        .description("A swarm for comprehensive research tasks")
        .agent(director_agent)
        .agent(research_agent)
        .agent(analysis_agent)
        .max_loops(3)
        .md(true)  // API compatibility maintained
        .build()?;

    // Execute complex task with hierarchical coordination
    let results = swarm.run("Analyze the impact of AI on healthcare", None).await?;

    Ok(())
}

2. Director-Worker Pattern

// The hierarchical swarm follows this pattern:
// 1. Director creates comprehensive plan and distributes tasks
// 2. Worker agents execute their assigned tasks
// 3. Director evaluates results and provides feedback
// 4. Process iterates for specified number of loops

let swarm = HierarchicalSwarmBuilder::new()
    .name("Complex Task Swarm")
    .max_loops(2)  // Number of feedback iterations
    .sequential_execution(true)  // Execute agents sequentially
    .build()?;

let results = swarm.run("Design a comprehensive business strategy", None).await?;

3. Agent Configuration

// Configure specialized agents for different roles
let director_agent = AgentSpec {
    agent_name: "Director".to_string(),
    description: Some("Coordinates and orchestrates the entire swarm".to_string()),
    system_prompt: Some("You are the director agent that creates plans...".to_string()),
    model_name: "gpt-4o-mini".to_string(),
    // ... other configuration
};

let worker_agent = AgentSpec {
    agent_name: "Researcher".to_string(),
    description: Some("Conducts specialized research tasks".to_string()),
    system_prompt: Some("You are a research specialist...".to_string()),
    model_name: "gpt-4o-mini".to_string(),
    // ... other configuration
};

Changes Made

1. Cleaned Up Markdown Functionality (swarms-rs/src/structs/hierarchical_swarm.rs)

  • Removed markdown_enabled field from HierarchicalSwarm struct
  • Removed formatter field from HierarchicalSwarm struct
  • Removed all markdown rendering logic from agent execution methods
  • Removed markdown initialization from builder and swarm constructors
  • Kept md() method for API compatibility - allows existing code to compile without breaking changes

2. Cleaned Up Core Implementation

// Before: Complex with markdown fields
pub struct HierarchicalSwarm {
    // ... core fields
    pub markdown_enabled: bool, // Removed
    formatter: Option<Formatter>, // Removed
}

// After: Clean focus on core functionality
pub struct HierarchicalSwarm {
    pub name: String,
    pub description: String,
    pub director: AgentSpec,
    pub agents: Vec<AgentSpec>,
    pub max_loops: u32,
    pub verbose: bool,
    // ... other essential fields only
}

3. Updated Example (swarms-rs/examples/hierarchical_swarm_example.rs)

/// **HIERARCHICAL SWARM USAGE EXAMPLE**
///
/// Create a hierarchical swarm with director and worker agents:
/// ```rust
/// let swarm = HierarchicalSwarmBuilder::new()
///     .name("My Swarm")
///     .director(director_agent)
///     .agent(worker_agent_1)
///     .agent(worker_agent_2)
///     .build()?;
///
/// // Execute - the director coordinates the worker agents
/// let results = swarm.run("My task", None).await?;
/// ```

#[tokio::main]
async fn main() -> Result<()> {
    // Create hierarchical swarm with proper agent configuration
    let swarm = HierarchicalSwarmBuilder::new()
        .name("Post-Civil War Communist Society Planning Swarm")
        .description("A hierarchical swarm that plans a post-civil war communist society")
        .agent(director_agent)
        .agent(economic_architect)
        .agent(social_planner)
        .agent(infrastructure_engineer)
        .agent(governance_specialist)
        .max_loops(2)
        .md(true)  // API compatibility maintained
        .build()?;

    // Execute the hierarchical swarm
    let results = swarm.run(task, None).await?;

    println!("Communist society planning process completed successfully!");
    Ok(())
}

Integration with Swarms Framework

Hierarchical Swarm Usage with API Compatibility

// Create hierarchical swarm with proper configuration
let swarm = HierarchicalSwarmBuilder::new()
    .name("Complex Task Swarm")
    .description("Multi-agent coordination for complex tasks")
    .agent(director_agent)
    .agent(specialized_agent_1)
    .agent(specialized_agent_2)
    .max_loops(3)
    .md(true)  // API compatibility maintained
    .build()?;

// Execute complex task with hierarchical coordination
let results = swarm.run("Analyze market trends and create strategy", None).await?;

Director-Worker Coordination

// The hierarchical swarm provides:
// 1. Director creates comprehensive plans and distributes tasks
// 2. Worker agents execute specialized tasks
// 3. Director evaluates results and coordinates iterations
// 4. Feedback loops enable iterative refinement
// 5. Clean coordination across multiple specialized agents

Issue

Addresses the need to clean up the hierarchical swarm implementation by removing unnecessary markdown functionality. The system now focuses purely on core hierarchical multi-agent coordination without output formatting concerns.

Dependencies

No changes to dependencies. The system uses existing core dependencies for multi-agent coordination.

Tag maintainer

@kyegomez

Twitter handle

x.com/IlumTheProtogen

Testing

  • All examples run successfully: cargo run --example hierarchical_swarm_example
  • All tests run successfully: cargo test --test test_hierarchical_swarm
  • Core hierarchical swarm functionality works properly
  • Comprehensive test coverage including:
    • Hierarchical swarm creation with proper agent configuration
    • Director-worker coordination for complex tasks
    • Sequential and parallel agent execution
    • Feedback loops and iterative refinement
    • Error handling and logging functionality
    • Clean API without formatting complexity

Code Quality Improvements

  • Clean focus on core hierarchical functionality
  • Removed unnecessary complexity from output formatting
  • Simplified API without formatting concerns
  • Clear separation of concerns between coordination and presentation
  • Maintainable codebase with single responsibility
  • Proper error handling and logging
  • Comprehensive documentation for core functionality

Files Modified

  • swarms-rs/src/structs/hierarchical_swarm.rs - Removed markdown functionality, cleaned core implementation
  • swarms-rs/examples/hierarchical_swarm_example.rs - Updated to show proper hierarchical swarm usage
  • swarms-rs/src/prompts/hierarchical_system_prompt.rs - Core system prompt for hierarchical coordination

Benefits for Swarms Framework

  1. Clean Architecture: Focus on core multi-agent coordination
  2. API Compatibility: Existing code with .md(true) continues to work
  3. Simplified Implementation: Removed formatting complexity from core logic
  4. Better Separation: Coordination logic separate from presentation
  5. Maintainable Code: Single responsibility principle maintained
  6. Clear Purpose: Hierarchical swarm for complex task coordination
  7. Backward Compatibility: No breaking changes for existing users
  8. Easy Testing: Core logic can be tested without formatting dependencies
  9. Framework Consistency: Aligns with other swarm implementations
  10. Developer Experience: Clear API with compatibility maintained

Video Demo(With AI summary on same page):

https://screenapp.io/app/#/shared/SxDawpRUMo

@IlumCI IlumCI changed the title Hierarchicalswarms rs [FEAT-SWARM][Added fully functional hierarchical swarm architecture identical to the python version] Aug 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant