Update board_of_directors_example.py

pull/987/head
CI-DEV 1 month ago committed by GitHub
parent 4e6eced828
commit def507cf5c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -5,19 +5,25 @@ This example demonstrates how to use the Board of Directors swarm feature
in the Swarms Framework. It shows how to create a board, configure it, in the Swarms Framework. It shows how to create a board, configure it,
and use it to orchestrate tasks across multiple agents. and use it to orchestrate tasks across multiple agents.
The example includes: To run this example:
1. Basic Board of Directors setup and usage 1. Make sure you're in the root directory of the swarms project
2. Custom board member configuration 2. Run: python examples/multi_agent/board_of_directors/board_of_directors_example.py
3. Task execution and feedback
4. Configuration management
""" """
import os import os
import sys import sys
from typing import List, Optional from typing import List
# Add the parent directory to the path to import swarms # Add the root directory to the Python path if running from examples directory
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))) current_dir = os.path.dirname(os.path.abspath(__file__))
if 'examples' in current_dir:
root_dir = current_dir
while os.path.basename(root_dir) != 'examples' and root_dir != os.path.dirname(root_dir):
root_dir = os.path.dirname(root_dir)
if os.path.basename(root_dir) == 'examples':
root_dir = os.path.dirname(root_dir)
if root_dir not in sys.path:
sys.path.insert(0, root_dir)
from swarms.structs.board_of_directors_swarm import ( from swarms.structs.board_of_directors_swarm import (
BoardOfDirectorsSwarm, BoardOfDirectorsSwarm,
@ -25,413 +31,167 @@ from swarms.structs.board_of_directors_swarm import (
BoardMemberRole, BoardMemberRole,
) )
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.config.board_config import (
enable_board_feature,
disable_board_feature,
is_board_feature_enabled,
create_default_config_file,
set_board_size,
set_decision_threshold,
set_board_model,
enable_verbose_logging,
disable_verbose_logging,
)
def enable_board_directors_feature() -> None:
"""
Enable the Board of Directors feature.
This function demonstrates how to enable the Board of Directors feature
globally and create a default configuration file.
"""
print("🔧 Enabling Board of Directors feature...")
try:
# Create a default configuration file
create_default_config_file("swarms_board_config.yaml")
# Enable the feature
enable_board_feature("swarms_board_config.yaml")
# Configure some default settings
set_board_size(3)
set_decision_threshold(0.6)
set_board_model("gpt-4o-mini")
enable_verbose_logging("swarms_board_config.yaml")
print("✅ Board of Directors feature enabled successfully!")
print("📁 Configuration file created: swarms_board_config.yaml")
except Exception as e:
print(f"❌ Failed to enable Board of Directors feature: {e}")
raise
def create_custom_board_members() -> List[BoardMember]: def create_board_members() -> List[BoardMember]:
""" """Create board members with specific roles."""
Create custom board members with specific roles and expertise.
This function demonstrates how to create a custom board with
specialized roles and expertise areas.
Returns:
List[BoardMember]: List of custom board members
"""
print("👥 Creating custom board members...")
# Create specialized board members
chairman = Agent( chairman = Agent(
agent_name="Executive_Chairman", agent_name="Chairman",
agent_description="Executive Chairman with strategic vision and leadership expertise", agent_description="Executive Chairman with strategic vision",
model_name="gpt-4o-mini", model_name="gpt-4o-mini",
max_loops=1, max_loops=1,
system_prompt="""You are the Executive Chairman of the Board. Your role is to: system_prompt="You are the Executive Chairman. Provide strategic leadership and facilitate decision-making.",
1. Provide strategic leadership and vision
2. Facilitate high-level decision-making
3. Ensure board effectiveness and governance
4. Represent the organization's interests
5. Guide long-term strategic planning
You should be visionary, strategic, and focused on organizational success.""",
) )
cto = Agent( cto = Agent(
agent_name="CTO", agent_name="CTO",
agent_description="Chief Technology Officer with deep technical expertise", agent_description="Chief Technology Officer with technical expertise",
model_name="gpt-4o-mini", model_name="gpt-4o-mini",
max_loops=1, max_loops=1,
system_prompt="""You are the Chief Technology Officer. Your role is to: system_prompt="You are the CTO. Provide technical leadership and evaluate technology solutions.",
1. Provide technical leadership and strategy
2. Evaluate technology solutions and architectures
3. Ensure technical feasibility of proposed solutions
4. Guide technology-related decisions
5. Maintain technical standards and best practices
You should be technically proficient, innovative, and focused on technical excellence.""",
) )
cfo = Agent( cfo = Agent(
agent_name="CFO", agent_name="CFO",
agent_description="Chief Financial Officer with financial and risk management expertise", agent_description="Chief Financial Officer with financial expertise",
model_name="gpt-4o-mini", model_name="gpt-4o-mini",
max_loops=1, max_loops=1,
system_prompt="""You are the Chief Financial Officer. Your role is to: system_prompt="You are the CFO. Provide financial analysis and ensure fiscal responsibility.",
1. Provide financial analysis and insights
2. Evaluate financial implications of decisions
3. Ensure financial sustainability and risk management
4. Guide resource allocation and budgeting
5. Maintain financial controls and compliance
You should be financially astute, risk-aware, and focused on financial health.""",
) )
# Create BoardMember objects with roles and expertise return [
board_members = [
BoardMember( BoardMember(
agent=chairman, agent=chairman,
role=BoardMemberRole.CHAIRMAN, role=BoardMemberRole.CHAIRMAN,
voting_weight=2.0, voting_weight=2.0,
expertise_areas=["strategic_planning", "leadership", "governance", "business_strategy"] expertise_areas=["leadership", "strategy"]
), ),
BoardMember( BoardMember(
agent=cto, agent=cto,
role=BoardMemberRole.EXECUTIVE_DIRECTOR, role=BoardMemberRole.EXECUTIVE_DIRECTOR,
voting_weight=1.5, voting_weight=1.5,
expertise_areas=["technology", "architecture", "innovation", "technical_strategy"] expertise_areas=["technology", "innovation"]
), ),
BoardMember( BoardMember(
agent=cfo, agent=cfo,
role=BoardMemberRole.EXECUTIVE_DIRECTOR, role=BoardMemberRole.EXECUTIVE_DIRECTOR,
voting_weight=1.5, voting_weight=1.5,
expertise_areas=["finance", "risk_management", "budgeting", "financial_analysis"] expertise_areas=["finance", "risk_management"]
), ),
] ]
print(f"✅ Created {len(board_members)} custom board members")
for member in board_members:
print(f" - {member.agent.agent_name} ({member.role.value})")
return board_members
def create_worker_agents() -> List[Agent]: def create_worker_agents() -> List[Agent]:
""" """Create worker agents for the swarm."""
Create worker agents for the swarm.
This function creates specialized worker agents that will be
managed by the Board of Directors.
Returns:
List[Agent]: List of worker agents
"""
print("🛠️ Creating worker agents...")
# Create specialized worker agents
researcher = Agent( researcher = Agent(
agent_name="Research_Analyst", agent_name="Researcher",
agent_description="Research analyst specializing in market research and data analysis", agent_description="Research analyst for data analysis",
model_name="gpt-4o-mini", model_name="gpt-4o-mini",
max_loops=1, max_loops=1,
system_prompt="""You are a Research Analyst. Your responsibilities include: system_prompt="You are a Research Analyst. Conduct thorough research and provide data-driven insights.",
1. Conducting thorough research on assigned topics
2. Analyzing data and market trends
3. Preparing comprehensive research reports
4. Providing data-driven insights and recommendations
5. Maintaining high standards of research quality
You should be analytical, thorough, and evidence-based in your work.""",
) )
developer = Agent( developer = Agent(
agent_name="Software_Developer", agent_name="Developer",
agent_description="Software developer with expertise in system design and implementation", agent_description="Software developer for implementation",
model_name="gpt-4o-mini", model_name="gpt-4o-mini",
max_loops=1, max_loops=1,
system_prompt="""You are a Software Developer. Your responsibilities include: system_prompt="You are a Software Developer. Design and implement software solutions.",
1. Designing and implementing software solutions
2. Writing clean, maintainable code
3. Conducting code reviews and testing
4. Collaborating with team members
5. Following best practices and coding standards
You should be technically skilled, detail-oriented, and focused on quality.""",
) )
marketer = Agent( marketer = Agent(
agent_name="Marketing_Specialist", agent_name="Marketer",
agent_description="Marketing specialist with expertise in digital marketing and brand strategy", agent_description="Marketing specialist for strategy",
model_name="gpt-4o-mini", model_name="gpt-4o-mini",
max_loops=1, max_loops=1,
system_prompt="""You are a Marketing Specialist. Your responsibilities include: system_prompt="You are a Marketing Specialist. Develop marketing strategies and campaigns.",
1. Developing marketing strategies and campaigns
2. Creating compelling content and messaging
3. Analyzing market trends and customer behavior
4. Managing brand presence and reputation
5. Measuring and optimizing marketing performance
You should be creative, strategic, and customer-focused in your approach.""",
) )
agents = [researcher, developer, marketer] return [researcher, developer, marketer]
print(f"✅ Created {len(agents)} worker agents")
for agent in agents:
print(f" - {agent.agent_name}: {agent.agent_description}")
return agents
def run_board_of_directors_example() -> None: def run_board_example() -> None:
""" """Run a Board of Directors example."""
Run a comprehensive Board of Directors example.
This function demonstrates the complete workflow of using # Create board members and worker agents
the Board of Directors swarm to orchestrate tasks. board_members = create_board_members()
""" worker_agents = create_worker_agents()
print("\n" + "="*60)
print("🏛️ BOARD OF DIRECTORS SWARM EXAMPLE")
print("="*60)
try: # Create the Board of Directors swarm
# Check if Board of Directors feature is enabled board_swarm = BoardOfDirectorsSwarm(
if not is_board_feature_enabled(): name="Executive_Board",
print("⚠️ Board of Directors feature is not enabled. Enabling now...") board_members=board_members,
enable_board_directors_feature() agents=worker_agents,
max_loops=2,
# Create custom board members verbose=True,
board_members = create_custom_board_members() decision_threshold=0.6,
)
# Create worker agents
worker_agents = create_worker_agents()
# Create the Board of Directors swarm
print("\n🏛️ Creating Board of Directors swarm...")
board_swarm = BoardOfDirectorsSwarm(
name="Executive_Board_Swarm",
description="Executive board with specialized roles for strategic decision-making",
board_members=board_members,
agents=worker_agents,
max_loops=2,
verbose=True,
decision_threshold=0.6,
enable_voting=True,
enable_consensus=True,
)
print("✅ Board of Directors swarm created successfully!")
# Display board summary
summary = board_swarm.get_board_summary()
print(f"\n📊 Board Summary:")
print(f" Board Name: {summary['board_name']}")
print(f" Total Members: {summary['total_members']}")
print(f" Total Agents: {summary['total_agents']}")
print(f" Max Loops: {summary['max_loops']}")
print(f" Decision Threshold: {summary['decision_threshold']}")
print(f"\n👥 Board Members:")
for member in summary['members']:
print(f" - {member['name']} ({member['role']}) - Weight: {member['voting_weight']}")
print(f" Expertise: {', '.join(member['expertise_areas'])}")
# Define a complex task for the board to handle
task = """
Develop a comprehensive strategy for launching a new AI-powered product in the market.
The task involves:
1. Market research and competitive analysis
2. Technical architecture and development planning
3. Marketing strategy and go-to-market plan
4. Financial projections and risk assessment
Please coordinate the efforts of all team members to create a cohesive strategy.
"""
print(f"\n📋 Executing task: {task.strip()[:100]}...")
# Execute the task using the Board of Directors swarm
result = board_swarm.run(task=task)
print("\n✅ Task completed successfully!")
print(f"📄 Result type: {type(result)}")
# Display conversation history
if hasattr(result, 'get') and callable(result.get):
conversation_history = result.get('conversation_history', [])
print(f"\n💬 Conversation History ({len(conversation_history)} messages):")
for i, message in enumerate(conversation_history[-5:], 1): # Show last 5 messages
role = message.get('role', 'Unknown')
content = message.get('content', '')[:100] + "..." if len(message.get('content', '')) > 100 else message.get('content', '')
print(f" {i}. {role}: {content}")
else:
print(f"\n📝 Result: {str(result)[:200]}...")
print("\n🎉 Board of Directors example completed successfully!")
except Exception as e:
print(f"❌ Error in Board of Directors example: {e}")
import traceback
traceback.print_exc()
def run_simple_board_example() -> None:
"""
Run a simple Board of Directors example with default settings.
This function demonstrates a basic usage of the Board of Directors # Define task
swarm with minimal configuration. task = """
Develop a strategy for launching a new AI-powered product in the market.
Include market research, technical planning, marketing strategy, and financial projections.
""" """
print("\n" + "="*60)
print("🏛️ SIMPLE BOARD OF DIRECTORS EXAMPLE")
print("="*60)
try: # Execute the task
# Create simple worker agents result = board_swarm.run(task=task)
print("🛠️ Creating simple worker agents...")
print("Task completed successfully!")
analyst = Agent( print(f"Result: {result}")
agent_name="Data_Analyst",
agent_description="Data analyst for processing and analyzing information",
model_name="gpt-4o-mini",
max_loops=1,
)
writer = Agent(
agent_name="Content_Writer",
agent_description="Content writer for creating reports and documentation",
model_name="gpt-4o-mini",
max_loops=1,
)
agents = [analyst, writer]
# Create Board of Directors swarm with default settings
print("🏛️ Creating Board of Directors swarm with default settings...")
board_swarm = BoardOfDirectorsSwarm(
name="Simple_Board_Swarm",
agents=agents,
verbose=True,
)
print("✅ Simple Board of Directors swarm created!")
# Simple task
task = "Analyze the current market trends and create a summary report with recommendations."
print(f"\n📋 Executing simple task: {task}")
# Execute the task
result = board_swarm.run(task=task)
print("\n✅ Simple task completed successfully!")
print(f"📄 Result type: {type(result)}")
if hasattr(result, 'get') and callable(result.get):
conversation_history = result.get('conversation_history', [])
print(f"\n💬 Conversation History ({len(conversation_history)} messages):")
for i, message in enumerate(conversation_history[-3:], 1): # Show last 3 messages
role = message.get('role', 'Unknown')
content = message.get('content', '')[:80] + "..." if len(message.get('content', '')) > 80 else message.get('content', '')
print(f" {i}. {role}: {content}")
else:
print(f"\n📝 Result: {str(result)[:150]}...")
print("\n🎉 Simple Board of Directors example completed!")
except Exception as e:
print(f"❌ Error in simple Board of Directors example: {e}")
import traceback
traceback.print_exc()
def check_environment() -> bool: def run_simple_example() -> None:
""" """Run a simple Board of Directors example."""
Check if the environment is properly set up for the example.
Returns: # Create simple agents
bool: True if environment is ready, False otherwise analyst = Agent(
""" agent_name="Analyst",
# Check for OpenAI API key agent_description="Data analyst",
if not os.getenv("OPENAI_API_KEY"): model_name="gpt-4o-mini",
print("⚠️ Warning: OPENAI_API_KEY environment variable not set.") max_loops=1,
print(" The example may not work without a valid API key.") )
print(" Please set your OpenAI API key: export OPENAI_API_KEY='your-key-here'")
return False
return True writer = Agent(
agent_name="Writer",
agent_description="Content writer",
model_name="gpt-4o-mini",
max_loops=1,
)
# Create swarm with default settings
board_swarm = BoardOfDirectorsSwarm(
name="Simple_Board",
agents=[analyst, writer],
verbose=True,
)
# Execute simple task
task = "Analyze current market trends and create a summary report."
result = board_swarm.run(task=task)
print("Simple example completed!")
print(f"Result: {result}")
def main() -> None: def main() -> None:
""" """Main function to run the examples."""
Main function to run the Board of Directors examples.
"""
print("🚀 Board of Directors Swarm Examples")
print("="*50)
# Check environment if not os.getenv("OPENAI_API_KEY"):
if not check_environment(): print("Warning: OPENAI_API_KEY not set. Example may not work.")
print("\n⚠️ Environment check failed. Please set up your environment properly.")
return return
try: try:
# Run simple example first print("Running simple Board of Directors example...")
run_simple_board_example() run_simple_example()
# Run comprehensive example
run_board_of_directors_example()
print("\n" + "="*60) print("\nRunning comprehensive Board of Directors example...")
print("🎉 All Board of Directors examples completed successfully!") run_board_example()
print("="*60)
except KeyboardInterrupt:
print("\n⚠️ Examples interrupted by user.")
except Exception as e: except Exception as e:
print(f"\n❌ Unexpected error: {e}") print(f"Error: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

Loading…
Cancel
Save