Merge pull request #1003 from IlumCI/frames

[FEAT][Hierarchical Structured Communication Framework]
pull/938/head
Kye Gomez 2 weeks ago committed by GitHub
commit 6525e99c39
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -290,6 +290,7 @@ nav:
- Hiearchical Architectures:
- Overview: "swarms/structs/multi_swarm_orchestration.md"
- HierarchicalSwarm: "swarms/structs/hierarchical_swarm.md"
- Hierarchical Structured Communication Framework: "swarms/structs/hierarchical_structured_communication_framework.md"
- Auto Agent Builder: "swarms/structs/auto_agent_builder.md"
- Hybrid Hierarchical-Cluster Swarm: "swarms/structs/hhcs.md"
- Auto Swarm Builder: "swarms/structs/auto_swarm_builder.md"

@ -2,7 +2,7 @@
The Board of Directors is a sophisticated multi-agent architecture that implements collective decision-making through democratic processes, voting mechanisms, and role-based leadership. This architecture provides an alternative to single-director patterns by enabling collaborative intelligence through structured governance.
## 🏛️ Overview
## Overview
The Board of Directors architecture follows a democratic workflow pattern:
@ -14,7 +14,7 @@ The Board of Directors architecture follows a democratic workflow pattern:
6. **Feedback Loop**: Board evaluates results and issues new orders if needed (up to `max_loops`)
7. **Context Preservation**: All conversation history and context is maintained throughout the process
## 🏗️ Architecture Components
## Architecture Components
### Core Components
@ -73,7 +73,7 @@ sequenceDiagram
Chairman->>User: Deliver Results
```
## 👥 Board Member Roles
## Board Member Roles
The Board of Directors supports various roles with different responsibilities and voting weights:
@ -138,7 +138,7 @@ class BoardRoleHierarchy:
}
```
## 🚀 Quick Start
## Quick Start
### Basic Setup
@ -206,7 +206,7 @@ result = board_swarm.run(task="Analyze the market potential for Tesla (TSLA) sto
print(result)
```
## 📋 Comprehensive Examples
## Comprehensive Examples
### 1. Strategic Investment Analysis
@ -448,7 +448,7 @@ print("Crisis Management Results:")
print(json.dumps(result, indent=2))
```
## ⚙️ Configuration and Parameters
## Configuration and Parameters
### BoardOfDirectorsSwarm Parameters
@ -551,7 +551,7 @@ quality_config = {
}
```
## 📊 Performance Monitoring and Analytics
## Performance Monitoring and Analytics
### Board Performance Metrics
@ -656,7 +656,7 @@ print("Performance Report:")
print(json.dumps(report, indent=2))
```
## 🔧 Advanced Features and Customization
## Advanced Features and Customization
### Custom Board Templates
@ -729,7 +729,7 @@ board_swarm = BoardOfDirectorsSwarm(
)
```
## 🛠️ Troubleshooting and Debugging
## Troubleshooting and Debugging
### Common Issues and Solutions
@ -821,7 +821,7 @@ logging_swarm = BoardOfDirectorsSwarm(
)
```
## 📋 Use Cases
## Use Cases
### Corporate Governance
- **Strategic Planning**: Long-term business strategy development
@ -853,20 +853,20 @@ logging_swarm = BoardOfDirectorsSwarm(
- **Recovery Planning**: Developing recovery and prevention strategies
- **Legal Compliance**: Ensuring compliance during crisis situations
## 🎯 Success Criteria
## Success Criteria
A successful Board of Directors implementation should demonstrate:
- **Democratic Decision Making**: All board members contribute to decisions
- **Consensus Achievement**: Decisions reached through collaborative processes
- **Role Effectiveness**: Each board member fulfills their responsibilities
- **Agent Coordination**: Worker agents execute tasks efficiently
- **Quality Output**: High-quality results through collective intelligence
- **Process Transparency**: Clear visibility into decision-making processes
- **Performance Optimization**: Efficient resource utilization and execution
- **Continuous Improvement**: Learning from each execution cycle
- **Democratic Decision Making**: All board members contribute to decisions
- **Consensus Achievement**: Decisions reached through collaborative processes
- **Role Effectiveness**: Each board member fulfills their responsibilities
- **Agent Coordination**: Worker agents execute tasks efficiently
- **Quality Output**: High-quality results through collective intelligence
- **Process Transparency**: Clear visibility into decision-making processes
- **Performance Optimization**: Efficient resource utilization and execution
- **Continuous Improvement**: Learning from each execution cycle
## 📚 Best Practices
## Best Practices
### 1. Role Definition
- Clearly define responsibilities for each board member
@ -900,4 +900,4 @@ A successful Board of Directors implementation should demonstrate:
---
The Board of Directors architecture represents a sophisticated approach to multi-agent collaboration, enabling organizations to leverage collective intelligence through structured governance and democratic decision-making processes. This comprehensive implementation provides the tools and frameworks needed to build effective, scalable, and intelligent decision-making systems.
The Board of Directors architecture represents a sophisticated approach to multi-agent collaboration, enabling organizations to leverage collective intelligence through structured governance and democratic decision-making processes. This comprehensive implementation provides the tools and frameworks needed to build effective, scalable, and intelligent decision-making systems.

@ -0,0 +1,177 @@
# Hierarchical Structured Communication Framework
The Hierarchical Structured Communication Framework implements the "Talk Structurally, Act Hierarchically" approach for LLM multi-agent systems, based on the research paper arXiv:2502.11098.
## Overview
This framework provides:
- **Structured Communication Protocol** with Message (M_ij), Background (B_ij), and Intermediate Output (I_ij)
- **Hierarchical Evaluation System** with supervisor coordination
- **Specialized Agent Classes** for different roles
- **Main Swarm Orchestrator** for workflow management
## Key Components
### Agent Classes
- `HierarchicalStructuredCommunicationGenerator` - Creates initial content
- `HierarchicalStructuredCommunicationEvaluator` - Evaluates content quality
- `HierarchicalStructuredCommunicationRefiner` - Improves content based on feedback
- `HierarchicalStructuredCommunicationSupervisor` - Coordinates workflow
### Main Framework
- `HierarchicalStructuredCommunicationFramework` - Main orchestrator class
- `HierarchicalStructuredCommunicationSwarm` - Convenience alias
## Quick Start
```python
from swarms.structs.hierarchical_structured_communication_framework import (
HierarchicalStructuredCommunicationFramework,
HierarchicalStructuredCommunicationGenerator,
HierarchicalStructuredCommunicationEvaluator,
HierarchicalStructuredCommunicationRefiner,
HierarchicalStructuredCommunicationSupervisor
)
# Create specialized agents
generator = HierarchicalStructuredCommunicationGenerator(
agent_name="ContentGenerator"
)
evaluator = HierarchicalStructuredCommunicationEvaluator(
agent_name="QualityEvaluator"
)
refiner = HierarchicalStructuredCommunicationRefiner(
agent_name="ContentRefiner"
)
supervisor = HierarchicalStructuredCommunicationSupervisor(
agent_name="WorkflowSupervisor"
)
# Create the framework
framework = HierarchicalStructuredCommunicationFramework(
name="MyFramework",
supervisor=supervisor,
generators=[generator],
evaluators=[evaluator],
refiners=[refiner],
max_loops=3
)
# Run the workflow
result = framework.run("Create a comprehensive analysis of AI trends in 2024")
```
## Basic Usage
```python
from swarms.structs.hierarchical_structured_communication_framework import (
HierarchicalStructuredCommunicationFramework,
HierarchicalStructuredCommunicationGenerator,
HierarchicalStructuredCommunicationEvaluator,
HierarchicalStructuredCommunicationRefiner
)
# Create agents with custom names
generator = HierarchicalStructuredCommunicationGenerator(agent_name="ContentGenerator")
evaluator = HierarchicalStructuredCommunicationEvaluator(agent_name="QualityEvaluator")
refiner = HierarchicalStructuredCommunicationRefiner(agent_name="ContentRefiner")
# Create framework with default supervisor
framework = HierarchicalStructuredCommunicationFramework(
generators=[generator],
evaluators=[evaluator],
refiners=[refiner],
max_loops=3,
verbose=True
)
# Execute task
result = framework.run("Write a detailed report on renewable energy technologies")
print(result["final_result"])
```
## Advanced Configuration
```python
from swarms.structs.hierarchical_structured_communication_framework import (
HierarchicalStructuredCommunicationFramework
)
# Create framework with custom configuration
framework = HierarchicalStructuredCommunicationFramework(
name="AdvancedFramework",
max_loops=5,
enable_structured_communication=True,
enable_hierarchical_evaluation=True,
shared_memory=True,
model_name="gpt-4o-mini",
verbose=True
)
# Run with custom parameters
result = framework.run(
"Analyze the impact of climate change on global agriculture",
max_loops=3
)
```
## Integration with Other Swarms
```python
from swarms.structs.hierarchical_structured_communication_framework import (
HierarchicalStructuredCommunicationFramework
)
from swarms.structs import AutoSwarmBuilder
# Use HierarchicalStructuredCommunicationFramework for content generation
framework = HierarchicalStructuredCommunicationFramework(
max_loops=2,
verbose=True
)
# Integrate with AutoSwarmBuilder
builder = AutoSwarmBuilder()
swarm = builder.create_swarm(
swarm_type="HierarchicalStructuredCommunicationFramework",
task="Generate a comprehensive business plan"
)
```
## API Reference
### HierarchicalStructuredCommunicationFramework
The main orchestrator class that implements the complete framework.
#### Parameters
- `name` (str): Name of the framework
- `supervisor`: Main supervisor agent
- `generators` (List): List of generator agents
- `evaluators` (List): List of evaluator agents
- `refiners` (List): List of refiner agents
- `max_loops` (int): Maximum refinement loops
- `enable_structured_communication` (bool): Enable structured protocol
- `enable_hierarchical_evaluation` (bool): Enable hierarchical evaluation
- `verbose` (bool): Enable verbose logging
#### Methods
- `run(task)`: Execute complete workflow
- `step(task)`: Execute single workflow step
- `send_structured_message()`: Send structured communication
- `run_hierarchical_evaluation()`: Run evaluation system
## Contributing
Contributions to improve the Hierarchical Structured Communication Framework are welcome! Please:
1. Follow the existing code style and patterns
2. Add comprehensive tests for new features
3. Update documentation for any API changes
4. Ensure all imports use the correct module paths
## License
This framework is part of the Swarms project and follows the same licensing terms.

@ -0,0 +1,310 @@
"""
Single-File Hierarchical Structured Communication Framework Example
This example demonstrates how to use the consolidated single-file implementation
of the Talk Structurally, Act Hierarchically framework.
All components are now in one file: hierarchical_structured_communication_framework.py
"""
import os
import sys
from typing import Dict, Any
# Add the project root to the Python path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.insert(0, project_root)
from dotenv import load_dotenv
# Import everything from the single file
from swarms.structs.hierarchical_structured_communication_framework import (
HierarchicalStructuredCommunicationFramework,
HierarchicalStructuredCommunicationGenerator,
HierarchicalStructuredCommunicationEvaluator,
HierarchicalStructuredCommunicationRefiner,
HierarchicalStructuredCommunicationSupervisor,
# Convenience aliases
TalkHierarchicalGenerator,
TalkHierarchicalEvaluator,
TalkHierarchicalRefiner,
TalkHierarchicalSupervisor,
)
# Load environment variables
load_dotenv()
def example_basic_usage():
"""
Basic usage example with default agents
"""
print("=" * 80)
print("BASIC USAGE EXAMPLE")
print("=" * 80)
# Create framework with default configuration
framework = HierarchicalStructuredCommunicationFramework(
name="BasicFramework",
max_loops=2,
verbose=True
)
# Run a simple task
task = "Explain the benefits of structured communication in multi-agent systems"
print(f"Task: {task}")
print("Running framework...")
result = framework.run(task)
print("\n" + "=" * 50)
print("FINAL RESULT")
print("=" * 50)
print(result["final_result"])
print(f"\nTotal loops: {result['total_loops']}")
print(f"Conversation history entries: {len(result['conversation_history'])}")
print(f"Evaluation results: {len(result['evaluation_results'])}")
def example_custom_agents():
"""
Example using custom specialized agents
"""
print("\n" + "=" * 80)
print("CUSTOM AGENTS EXAMPLE")
print("=" * 80)
# Create custom agents using the convenience aliases
generator = TalkHierarchicalGenerator(
agent_name="ContentCreator",
model_name="gpt-4o-mini",
verbose=True
)
evaluator1 = TalkHierarchicalEvaluator(
agent_name="AccuracyChecker",
evaluation_criteria=["accuracy", "technical_correctness"],
model_name="gpt-4o-mini",
verbose=True
)
evaluator2 = TalkHierarchicalEvaluator(
agent_name="ClarityChecker",
evaluation_criteria=["clarity", "readability", "coherence"],
model_name="gpt-4o-mini",
verbose=True
)
refiner = TalkHierarchicalRefiner(
agent_name="ContentImprover",
model_name="gpt-4o-mini",
verbose=True
)
supervisor = TalkHierarchicalSupervisor(
agent_name="WorkflowManager",
model_name="gpt-4o-mini",
verbose=True
)
# Create framework with custom agents
framework = HierarchicalStructuredCommunicationFramework(
name="CustomFramework",
supervisor=supervisor,
generators=[generator],
evaluators=[evaluator1, evaluator2],
refiners=[refiner],
max_loops=3,
verbose=True
)
# Run a complex task
task = "Design a comprehensive machine learning pipeline for sentiment analysis"
print(f"Task: {task}")
print("Running framework with custom agents...")
result = framework.run(task)
print("\n" + "=" * 50)
print("FINAL RESULT")
print("=" * 50)
print(result["final_result"])
print(f"\nTotal loops: {result['total_loops']}")
print(f"Conversation history entries: {len(result['conversation_history'])}")
print(f"Evaluation results: {len(result['evaluation_results'])}")
def example_ollama_integration():
"""
Example using Ollama for local inference
"""
print("\n" + "=" * 80)
print("OLLAMA INTEGRATION EXAMPLE")
print("=" * 80)
# Create framework with Ollama configuration
framework = HierarchicalStructuredCommunicationFramework(
name="OllamaFramework",
max_loops=2,
verbose=True,
model_name="llama3:latest",
use_ollama=True,
ollama_base_url="http://localhost:11434/v1",
ollama_api_key="ollama"
)
# Run a task with local model
task = "Explain the concept of structured communication protocols"
print(f"Task: {task}")
print("Running framework with Ollama...")
try:
result = framework.run(task)
print("\n" + "=" * 50)
print("FINAL RESULT")
print("=" * 50)
print(result["final_result"])
print(f"\nTotal loops: {result['total_loops']}")
print(f"Conversation history entries: {len(result['conversation_history'])}")
print(f"Evaluation results: {len(result['evaluation_results'])}")
except Exception as e:
print(f"Error with Ollama: {e}")
print("Make sure Ollama is running: ollama serve")
def example_structured_communication():
"""
Example demonstrating structured communication protocol
"""
print("\n" + "=" * 80)
print("STRUCTURED COMMUNICATION EXAMPLE")
print("=" * 80)
# Create framework
framework = HierarchicalStructuredCommunicationFramework(
name="CommunicationDemo",
verbose=True
)
# Demonstrate structured message sending
print("Sending structured message...")
structured_msg = framework.send_structured_message(
sender="Supervisor",
recipient="Generator",
message="Create a technical documentation outline",
background="For a Python library focused on data processing",
intermediate_output="Previous research on similar libraries"
)
print(f"Message sent: {structured_msg.message}")
print(f"Background: {structured_msg.background}")
print(f"Intermediate output: {structured_msg.intermediate_output}")
print(f"From: {structured_msg.sender} -> To: {structured_msg.recipient}")
def example_agent_interaction():
"""
Example showing direct agent interaction
"""
print("\n" + "=" * 80)
print("AGENT INTERACTION EXAMPLE")
print("=" * 80)
# Create agents
generator = TalkHierarchicalGenerator(
agent_name="ContentGenerator",
verbose=True
)
evaluator = TalkHierarchicalEvaluator(
agent_name="QualityEvaluator",
evaluation_criteria=["accuracy", "clarity"],
verbose=True
)
refiner = TalkHierarchicalRefiner(
agent_name="ContentRefiner",
verbose=True
)
# Generate content
print("1. Generating content...")
gen_result = generator.generate_with_structure(
message="Create a brief explanation of machine learning",
background="For beginners with no technical background",
intermediate_output=""
)
print(f"Generated content: {gen_result.content[:200]}...")
# Evaluate content
print("\n2. Evaluating content...")
eval_result = evaluator.evaluate_with_criterion(
content=gen_result.content,
criterion="clarity"
)
print(f"Evaluation score: {eval_result.score}/10")
print(f"Feedback: {eval_result.feedback[:200]}...")
# Refine content
print("\n3. Refining content...")
refine_result = refiner.refine_with_feedback(
original_content=gen_result.content,
evaluation_results=[eval_result]
)
print(f"Refined content: {refine_result.refined_content[:200]}...")
print(f"Changes made: {refine_result.changes_made}")
def main():
"""
Main function to run all examples
"""
print("SINGLE-FILE HIERARCHICAL STRUCTURED COMMUNICATION FRAMEWORK")
print("=" * 80)
print("This demonstrates the consolidated single-file implementation")
print("based on the research paper: arXiv:2502.11098")
print("=" * 80)
try:
# Run examples
example_basic_usage()
example_custom_agents()
example_ollama_integration()
example_structured_communication()
example_agent_interaction()
print("\n" + "=" * 80)
print("ALL EXAMPLES COMPLETED SUCCESSFULLY!")
print("=" * 80)
print("Framework Features Demonstrated:")
print("✓ Single-file implementation")
print("✓ Structured Communication Protocol (M_ij, B_ij, I_ij)")
print("✓ Hierarchical Evaluation System")
print("✓ Iterative Refinement Process")
print("✓ Flexible Model Configuration (OpenAI/Ollama)")
print("✓ Custom Agent Specialization")
print("✓ Direct Agent Interaction")
print("✓ Convenience Aliases")
except KeyboardInterrupt:
print("\nInterrupted by user")
except Exception as e:
print(f"Error during execution: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()

@ -27,4 +27,5 @@ aiohttp
mcp
numpy
openai
schedule
schedule
colorama

@ -11,30 +11,8 @@ from swarms.agents.reasoning_agents import (
agent_types,
)
from swarms.agents.reasoning_duo import ReasoningDuo
from swarms.structs.stopping_conditions import (
check_cancelled,
check_complete,
check_done,
check_end,
check_error,
check_exit,
check_failure,
check_finished,
check_stopped,
check_success,
)
__all__ = [
"check_done",
"check_finished",
"check_complete",
"check_success",
"check_failure",
"check_error",
"check_stopped",
"check_cancelled",
"check_exit",
"check_end",
"create_agents_from_yaml",
"IterativeReflectiveExpansion",
"SelfConsistencyAgent",

@ -1,6 +1,5 @@
from swarms.structs.agent import Agent
from swarms.structs.agent_builder import AgentsBuilder
from swarms.structs.agent_rearrange import AgentRearrange, rearrange
from swarms.structs.auto_swarm_builder import AutoSwarmBuilder
from swarms.structs.base_structure import BaseStructure
from swarms.structs.base_swarm import BaseSwarm
@ -25,8 +24,8 @@ from swarms.structs.groupchat import (
expertise_based,
)
from swarms.structs.heavy_swarm import HeavySwarm
from swarms.structs.hiearchical_swarm import HierarchicalSwarm
from swarms.structs.hybrid_hiearchical_peer_swarm import (
from swarms.structs.hierarchical_swarm import HierarchicalSwarm
from swarms.structs.hybrid_hierarchical_peer_swarm import (
HybridHierarchicalClusterSwarm,
)
from swarms.structs.interactive_groupchat import (
@ -67,10 +66,23 @@ from swarms.structs.multi_agent_exec import (
run_single_agent,
)
from swarms.structs.multi_agent_router import MultiAgentRouter
from swarms.structs.rearrange import AgentRearrange, rearrange
from swarms.structs.round_robin import RoundRobinSwarm
from swarms.structs.sequential_workflow import SequentialWorkflow
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
from swarms.structs.swarm_rearrange import SwarmRearrange
from swarms.structs.stopping_conditions import (
check_cancelled,
check_complete,
check_done,
check_end,
check_error,
check_exit,
check_failure,
check_finished,
check_stopped,
check_success,
)
from swarms.structs.swarm_arange import SwarmRearrange
from swarms.structs.swarm_router import (
SwarmRouter,
SwarmType,
@ -95,6 +107,26 @@ from swarms.structs.swarming_architectures import (
staircase_swarm,
star_swarm,
)
from swarms.structs.hierarchical_structured_communication_framework import (
HierarchicalStructuredCommunicationFramework,
HierarchicalStructuredCommunicationGenerator,
HierarchicalStructuredCommunicationEvaluator,
HierarchicalStructuredCommunicationRefiner,
HierarchicalStructuredCommunicationSupervisor,
StructuredMessage,
HierarchicalOrder,
EvaluationResult,
StructuredMessageSchema,
EvaluationResultSchema,
GeneratorResponseSchema,
EvaluatorResponseSchema,
RefinerResponseSchema,
CommunicationType,
AgentRole,
)
# Convenience alias(fixes old code if any was left out in the wild)
HierarchicalStructuredCommunicationSwarm = HierarchicalStructuredCommunicationFramework
__all__ = [
"Agent",
@ -174,4 +206,30 @@ __all__ = [
"HierarchicalSwarm",
"HeavySwarm",
"CronJob",
"HierarchicalStructuredCommunicationSwarm",
"HierarchicalStructuredCommunicationGenerator",
"HierarchicalStructuredCommunicationEvaluator",
"HierarchicalStructuredCommunicationRefiner",
"HierarchicalStructuredCommunicationSupervisor",
"StructuredMessage",
"HierarchicalOrder",
"EvaluationResult",
"StructuredMessageSchema",
"EvaluationResultSchema",
"GeneratorResponseSchema",
"EvaluatorResponseSchema",
"RefinerResponseSchema",
"CommunicationType",
"AgentRole",
# Stopping conditions
"check_done",
"check_finished",
"check_complete",
"check_success",
"check_failure",
"check_error",
"check_stopped",
"check_cancelled",
"check_exit",
"check_end",
]

Loading…
Cancel
Save