diff --git a/README.md b/README.md index 15a639c3..877ae9d1 100644 --- a/README.md +++ b/README.md @@ -633,24 +633,31 @@ The `HierarchicalSwarm` excels at: ```python from swarms import HeavySwarm -# Initialize the HeavySwarm with configuration +# Pip install swarms-tools +from swarms_tools import exa_search + swarm = HeavySwarm( - worker_model_name="gpt-4o-mini", # Model for worker agents - question_agent_model_name="gpt-4o-mini", # Model for question generation - loops_per_agent=1, # Number of loops per agent - show_dashboard=True, # Enable real-time dashboard + name="Gold ETF Research Team", + description="A team of agents that research the best gold ETFs", + worker_model_name="claude-sonnet-4-20250514", + show_dashboard=True, + question_agent_model_name="gpt-4.1", + loops_per_agent=1, + agent_prints_on=False, + worker_tools=[exa_search], + random_loops_per_agent=True, ) -# Run complex analysis task -result = swarm.run( - "Provide 3 publicly traded biotech companies that are currently trading below their cash value. " - "For each company identified, provide available data or projections for the next 6 months, " - "including any relevant financial metrics, upcoming catalysts, or events that could impact valuation. " - "Present your findings in a clear, structured format with ticker symbols, current prices, " - "cash values, and percentage differences." +prompt = ( + "Find the best 3 gold ETFs. For each ETF, provide the ticker symbol, " + "full name, current price, expense ratio, assets under management, and " + "a brief explanation of why it is considered among the best. Present the information " + "in a clear, structured format suitable for investors. Scrape the data from the web. " ) -print(result) +out = swarm.run(prompt) +print(out) + ``` The `HeavySwarm` provides: diff --git a/docs/swarms/structs/heavy_swarm.md b/docs/swarms/structs/heavy_swarm.md index f40b9e5f..5ad1f8ad 100644 --- a/docs/swarms/structs/heavy_swarm.md +++ b/docs/swarms/structs/heavy_swarm.md @@ -1,77 +1,9 @@ -# HeavySwarm Documentation +# HeavySwarm HeavySwarm is a sophisticated multi-agent orchestration system that decomposes complex tasks into specialized questions and executes them using four specialized agents: Research, Analysis, Alternatives, and Verification. The results are then synthesized into a comprehensive response. Inspired by X.AI's Grok 4 heavy implementation, HeavySwarm provides robust task analysis through intelligent question generation, parallel execution, and comprehensive synthesis with real-time progress monitoring. -## Architecture - -The HeavySwarm follows a structured 5-phase workflow: - -1. **Task Decomposition**: Complex tasks are broken down into specialized questions -2. **Question Generation**: AI-powered generation of role-specific questions -3. **Parallel Execution**: Four specialized agents work concurrently -4. **Result Collection**: Outputs are gathered and validated -5. **Synthesis**: Integration into a comprehensive final response - -### Agent Specialization - -| Agent | Role/Function | -|---------------------|--------------------------------------------------------------------| -| **Research Agent** | Comprehensive information gathering and synthesis | -| **Analysis Agent** | Pattern recognition and statistical analysis | -| **Alternatives Agent** | Creative problem-solving and strategic options | -| **Verification Agent** | Validation, feasibility assessment, and quality assurance | -| **Synthesis Agent** | Multi-perspective integration and executive reporting | - -## Architecture Diagram - -```mermaid -graph TB - subgraph "HeavySwarm Architecture" - A[Input Task] --> B[Question Generation Agent] - B --> C[Task Decomposition] - - C --> D[Research Agent] - C --> E[Analysis Agent] - C --> F[Alternatives Agent] - C --> G[Verification Agent] - - D --> H[Parallel Execution Engine] - E --> H - F --> H - G --> H - - H --> I[Result Collection] - I --> J[Synthesis Agent] - J --> K[Comprehensive Report] - - subgraph "Monitoring & Control" - L[Rich Dashboard] - M[Progress Tracking] - N[Error Handling] - O[Timeout Management] - end - - H --> L - H --> M - H --> N - H --> O - end - - subgraph "Agent Specializations" - D --> D1[Information Gathering
Market Research
Data Collection] - E --> E1[Statistical Analysis
Pattern Recognition
Predictive Modeling] - F --> F1[Creative Solutions
Strategic Options
Innovation Ideation] - G --> G1[Fact Checking
Feasibility Assessment
Quality Assurance] - end - - style A fill:#ff6b6b - style K fill:#4ecdc4 - style H fill:#45b7d1 - style J fill:#96ceb4 -``` - ## Installation ```bash @@ -82,38 +14,69 @@ pip install swarms ```python from swarms.structs.heavy_swarm import HeavySwarm -from swarms_tools import exa_search +# Initialize HeavySwarm swarm = HeavySwarm( - name="Gold ETF Research Team", - description="A team of agents that research the best gold ETFs", - worker_model_name="claude-sonnet-4-20250514", - show_dashboard=True, - question_agent_model_name="gpt-4.1", - loops_per_agent=1, - agent_prints_on=False, - worker_tools=[exa_search], - random_loops_per_agent=True, + name="Research Team", + description="Multi-agent analysis system", + worker_model_name="gpt-4o-mini", + show_dashboard=True ) -prompt = ( - "Find the best 3 gold ETFs. For each ETF, provide the ticker symbol, " - "full name, current price, expense ratio, assets under management, and " - "a brief explanation of why it is considered among the best. Present the information " - "in a clear, structured format suitable for investors. Scrape the data from the web. " -) +# Run analysis +result = swarm.run("Analyze the impact of AI on healthcare") +print(result) +``` -out = swarm.run(prompt) -print(out) +## Architecture +The HeavySwarm follows a structured 5-phase workflow: -``` +1. **Task Decomposition**: Complex tasks are broken down into specialized questions +2. **Question Generation**: AI-powered generation of role-specific questions +3. **Parallel Execution**: Four specialized agents work concurrently +4. **Result Collection**: Outputs are gathered and validated +5. **Synthesis**: Integration into a comprehensive final response + +### Agent Specialization + +| Agent | Role/Function | +|-------|---------------| +| **Research Agent** | Comprehensive information gathering and synthesis | +| **Analysis Agent** | Pattern recognition and statistical analysis | +| **Alternatives Agent** | Creative problem-solving and strategic options | +| **Verification Agent** | Validation, feasibility assessment, and quality assurance | +| **Synthesis Agent** | Multi-perspective integration and executive reporting | ## API Reference ### HeavySwarm Class -#### Constructor Parameters +A sophisticated multi-agent orchestration system for complex task analysis. + +#### Constructor + +```python +HeavySwarm( + name: str = "HeavySwarm", + description: str = "A swarm of agents that can analyze a task and generate specialized questions for each agent role", + timeout: int = 300, + aggregation_strategy: str = "synthesis", + loops_per_agent: int = 1, + question_agent_model_name: str = "gpt-4o-mini", + worker_model_name: str = "gpt-4o-mini", + verbose: bool = False, + max_workers: int = int(os.cpu_count() * 0.9), + show_dashboard: bool = False, + agent_prints_on: bool = False, + output_type: str = "dict-all-except-first", + worker_tools: Optional[tool_type] = None, + random_loops_per_agent: bool = False, + max_loops: int = 1, +) +``` + +##### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| @@ -129,10 +92,20 @@ print(out) | `show_dashboard` | `bool` | `False` | Enable rich dashboard with progress visualization | | `agent_prints_on` | `bool` | `False` | Enable individual agent output printing | | `output_type` | `str` | `"dict-all-except-first"` | Output formatting type for conversation history | -| `worker_tools` | `tool_type` | `None` | Tools available to worker agents for enhanced functionality | +| `worker_tools` | `Optional[tool_type]` | `None` | Tools available to worker agents for enhanced functionality | | `random_loops_per_agent` | `bool` | `False` | Enable random number of loops per agent (1-10 range) | +| `max_loops` | `int` | `1` | Maximum number of loops when using random_loops_per_agent | + +##### Raises + +- `ValueError`: If `loops_per_agent` is 0 or negative + +- `ValueError`: If `worker_model_name` is None + +- `ValueError`: If `question_agent_model_name` is None + +##### Example -**Constructor Example:** ```python swarm = HeavySwarm( name="AdvancedAnalysisSwarm", @@ -153,7 +126,7 @@ swarm = HeavySwarm( #### Methods -##### `run(task: str, img: str = None) -> str` +##### `run(task: str, img: Optional[str] = None) -> str` Execute the complete HeavySwarm orchestration flow. @@ -162,19 +135,19 @@ Execute the complete HeavySwarm orchestration flow. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `task` | `str` | Yes | - | The main task to analyze and decompose | -| `img` | `str` | No | `None` | Image input for visual analysis tasks | +| `img` | `Optional[str]` | No | `None` | Image input for visual analysis tasks | **Returns:** + - `str`: Comprehensive final analysis from synthesis agent **Example:** + ```python result = swarm.run("Develop a go-to-market strategy for a new SaaS product") print(result) ``` ---- - ##### `get_questions_only(task: str) -> Dict[str, str]` Generate and extract only the specialized questions without metadata or execution. @@ -186,6 +159,7 @@ Generate and extract only the specialized questions without metadata or executio | `task` | `str` | Yes | - | The main task or query to analyze and decompose into specialized questions | **Returns:** + - `Dict[str, str]`: Clean dictionary containing only the questions: - `research_question` (str): Question for comprehensive information gathering - `analysis_question` (str): Question for pattern analysis and insights @@ -194,14 +168,13 @@ Generate and extract only the specialized questions without metadata or executio - `error` (str): Error message if question generation fails (on error only) **Example:** + ```python questions = swarm.get_questions_only("Analyze market trends for EVs") print(questions['research_question']) print(questions['analysis_question']) ``` ---- - ##### `get_questions_as_list(task: str) -> List[str]` Generate specialized questions and return them as an ordered list. @@ -213,6 +186,7 @@ Generate specialized questions and return them as an ordered list. | `task` | `str` | Yes | - | The main task or query to decompose into specialized questions | **Returns:** + - `List[str]`: Ordered list of 4 specialized questions: - `[0]` Research question for comprehensive information gathering - `[1]` Analysis question for pattern analysis and insights @@ -221,47 +195,53 @@ Generate specialized questions and return them as an ordered list. - Single-item list containing error message (on error) **Example:** + ```python questions = swarm.get_questions_as_list("Optimize supply chain efficiency") for i, question in enumerate(questions): print(f"Agent {i+1}: {question}") ``` ---- - ##### `show_swarm_info() -> None` Display comprehensive swarm configuration information in a rich dashboard format. **Parameters:** + - None **Returns:** + - `None`: This method only displays output and has no return value. **Example:** + ```python swarm.show_swarm_info() # Displays configuration dashboard ``` ---- - ##### `reliability_check() -> None` Perform comprehensive reliability and configuration validation checks. **Parameters:** + - None **Returns:** + - `None`: This method only performs validation and has no return value. **Raises:** -- `ValueError`: If loops_per_agent is 0 or negative (agents won't execute) -- `ValueError`: If worker_model_name is None (agents can't be created) -- `ValueError`: If question_agent_model_name is None (questions can't be generated) + +| Exception | Condition | +|--------------|---------------------------------------------------------------------------| +| `ValueError` | If `loops_per_agent` is 0 or negative (agents won't execute) | +| `ValueError` | If `worker_model_name` is None (agents can't be created) | +| `ValueError` | If `question_agent_model_name` is None (questions can't be generated) | **Example:** + ```python try: swarm.reliability_check() # Automatically called in __init__ @@ -270,583 +250,308 @@ except ValueError as e: print(f"Configuration error: {e}") ``` ---- - ##### `create_agents() -> Dict[str, Agent]` Create and cache the 4 specialized agents with detailed role-specific prompts. **Parameters:** + - None **Returns:** -- `Dict[str, Agent]`: Dictionary containing all 5 specialized agents: - - `'research'`: Research Agent instance - - `'analysis'`: Analysis Agent instance - - `'alternatives'`: Alternatives Agent instance - - `'verification'`: Verification Agent instance - - `'synthesis'`: Synthesis Agent instance + +| Key | Agent Instance | Description | +|-----------------|-----------------------|---------------------------------------------| +| `'research'` | Research Agent | Research Agent instance | +| `'analysis'` | Analysis Agent | Analysis Agent instance | +| `'alternatives'`| Alternatives Agent | Alternatives Agent instance | +| `'verification'`| Verification Agent | Verification Agent instance | +| `'synthesis'` | Synthesis Agent | Synthesis Agent instance | **Example:** + ```python agents = swarm.create_agents() research_agent = agents['research'] print(f"Research agent name: {research_agent.agent_name}") ``` -## Comprehensive Full-Code Examples +## Examples -### Example 1: Basic Gold ETF Research with Dashboard +### Basic Usage ```python -# heavy_swarm_example.py -""" -Complete example demonstrating HeavySwarm for financial research -with dashboard visualization and tool integration. -""" - from swarms.structs.heavy_swarm import HeavySwarm -from swarms_tools import exa_search -# Initialize HeavySwarm with comprehensive configuration +# Initialize HeavySwarm swarm = HeavySwarm( - name="Gold ETF Research Team", - description="A team of agents that research the best gold ETFs", - worker_model_name="claude-sonnet-4-20250514", - question_agent_model_name="gpt-4o-mini", - show_dashboard=True, - loops_per_agent=1, - agent_prints_on=False, - worker_tools=[exa_search], - random_loops_per_agent=False, - timeout=300, - max_workers=4, - verbose=True -) - -# Define the research prompt -prompt = ( - "Find the best 3 gold ETFs. For each ETF, provide the ticker symbol, " - "full name, current price, expense ratio, assets under management, and " - "a brief explanation of why it is considered among the best. Present the information " - "in a clear, structured format suitable for investors. Scrape the data from the web." + name="Analysis Team", + description="Multi-agent analysis system", + worker_model_name="gpt-4o-mini", + show_dashboard=True ) -# Execute the analysis -print("๐Ÿš€ Starting HeavySwarm analysis...") -result = swarm.run(prompt) - -print("\n๐Ÿ“Š Analysis Complete!") -print("=" * 50) +# Run analysis +result = swarm.run("Analyze the impact of AI on healthcare") print(result) ``` -### Example 2: Advanced Market Analysis with Multiple Loops +### Financial Research with Tools ```python -# advanced_market_analysis.py -""" -Advanced example with multiple agent loops and comprehensive market analysis. -""" - from swarms.structs.heavy_swarm import HeavySwarm -from swarms_tools import exa_search, calculator, web_scraper +from swarms_tools import exa_search -# Advanced configuration for in-depth analysis +# Initialize with tools swarm = HeavySwarm( - name="AdvancedMarketAnalysis", - description="Comprehensive market analysis with multiple iterations", - worker_model_name="gpt-4o", - question_agent_model_name="gpt-4o", + name="Gold ETF Research Team", + description="Financial research with web scraping", + worker_model_name="gpt-4o-mini", + question_agent_model_name="gpt-4o-mini", show_dashboard=True, - loops_per_agent=3, # Multiple iterations for deeper analysis - agent_prints_on=True, - worker_tools=[exa_search, calculator, web_scraper], - random_loops_per_agent=False, - timeout=600, # Longer timeout for complex analysis - max_workers=8, - verbose=True + worker_tools=[exa_search], + timeout=300 ) -# Complex multi-dimensional analysis prompt -complex_prompt = """ -Conduct a comprehensive analysis of the renewable energy sector: - -1. Market Size & Growth: - - Current global market size - - Projected growth rates (5-year and 10-year) - - Key growth drivers and barriers - -2. Technology Landscape: - - Dominant technologies (solar, wind, hydro, etc.) - - Emerging technologies and innovations - - Technology adoption rates by region - -3. Investment Opportunities: - - Most promising investment sectors - - Risk assessment and mitigation strategies - - Return on investment projections - -4. Regulatory Environment: - - Current policy frameworks - - Upcoming regulatory changes - - Impact on industry development - -5. Competitive Analysis: - - Key players and market share - - Competitive advantages and disadvantages - - Market consolidation trends - -Provide detailed analysis with data sources, assumptions, and confidence levels. +# Research prompt +prompt = """ +Find the best 3 gold ETFs. For each ETF, provide: +- Ticker symbol and full name +- Current price and expense ratio +- Assets under management +- Why it's considered among the best """ -print("๐Ÿ”ฌ Starting advanced market analysis...") -result = swarm.run(complex_prompt) +result = swarm.run(prompt) print(result) ``` -### Example 3: Healthcare Policy Analysis with Random Loops +### Advanced Market Analysis ```python -# healthcare_policy_analysis.py -""" -Healthcare policy analysis with random agent loops for diverse perspectives. -""" - from swarms.structs.heavy_swarm import HeavySwarm -from swarms_tools import exa_search, data_analyzer, policy_tracker -# Healthcare-focused configuration with random loops +# Advanced configuration swarm = HeavySwarm( - name="HealthcarePolicyAnalyzer", - description="Multi-perspective healthcare policy analysis", + name="AdvancedMarketAnalysis", + description="Deep market analysis with multiple iterations", worker_model_name="gpt-4o", - question_agent_model_name="gpt-4o-mini", + question_agent_model_name="gpt-4o", show_dashboard=True, - loops_per_agent=1, # Base loops (will be randomized) - agent_prints_on=False, - worker_tools=[exa_search, data_analyzer, policy_tracker], - random_loops_per_agent=True, # Enable random loop variation - timeout=900, - max_workers=6, + loops_per_agent=3, # Multiple iterations for depth + timeout=600, + max_workers=8, verbose=True ) -# Healthcare policy analysis prompt -healthcare_prompt = """ -Analyze the impact of recent healthcare policy changes on: - -1. **Access to Care**: - - Changes in healthcare accessibility - - Impact on underserved populations - - Telemedicine adoption and effectiveness - -2. **Cost Implications**: - - Healthcare spending trends - - Insurance premium changes - - Out-of-pocket expense analysis - -3. **Quality of Care**: - - Patient outcome metrics - - Provider satisfaction and retention - - Innovation in treatment protocols - -4. **Healthcare Workforce**: - - Staffing shortages and surpluses - - Training and education requirements - - Compensation and benefits trends - -5. **Technology Integration**: - - Electronic health records adoption - - AI and machine learning applications - - Cybersecurity and data privacy - -Provide evidence-based analysis with statistical data and policy recommendations. +# Complex analysis prompt +complex_prompt = """ +Conduct comprehensive analysis of renewable energy sector: +1. Market size and growth projections +2. Technology landscape and adoption rates +3. Investment opportunities and risks +4. Regulatory environment +5. Competitive analysis """ -print("๐Ÿฅ Starting healthcare policy analysis...") -result = swarm.run(healthcare_prompt) +result = swarm.run(complex_prompt) print(result) ``` -### Example 4: Question Generation and Preview +### Question Generation Only ```python -# question_generation_example.py -""" -Example demonstrating question generation capabilities without full execution. -""" - from swarms.structs.heavy_swarm import HeavySwarm -# Configure swarm for question generation +# Configure for question generation swarm = HeavySwarm( name="QuestionGenerator", - description="Specialized question generation for task analysis", question_agent_model_name="gpt-4o", worker_model_name="gpt-4o-mini", - show_dashboard=False, # No dashboard for clean output - verbose=False + show_dashboard=False ) -# Sample task for analysis -task = "Develop a comprehensive digital transformation strategy for a traditional manufacturing company" +# Generate questions without execution +task = "Develop digital transformation strategy for manufacturing" +questions = swarm.get_questions_only(task) -print("๐Ÿ” Generating specialized questions...") -print("=" * 60) - -# Method 1: Get questions as dictionary -questions_dict = swarm.get_questions_only(task) -print("\n๐Ÿ“‹ Questions as Dictionary:") -for key, question in questions_dict.items(): +print("Generated Questions:") +for key, question in questions.items(): if key != 'error': print(f"\n{key.upper()}:") - print(f"{question}") - -# Method 2: Get questions as ordered list -questions_list = swarm.get_questions_as_list(task) -print("\n\n๐Ÿ“ Questions as Ordered List:") -for i, question in enumerate(questions_list): - agent_names = ["Research Agent", "Analysis Agent", "Alternatives Agent", "Verification Agent"] - print(f"\n{i+1}. {agent_names[i]}:") - print(f" {question}") - -print("\n" + "=" * 60) -print("๐Ÿ’ก Use these questions to understand how HeavySwarm decomposes complex tasks!") + print(question) ``` -### Example 5: High-Performance Configuration for Enterprise Use +### Batch Processing ```python -# enterprise_configuration.py -""" -Enterprise-grade HeavySwarm configuration for high-performance analysis. -""" - from swarms.structs.heavy_swarm import HeavySwarm -from swarms_tools import exa_search, data_analyzer, financial_modeler, risk_assessor -# Enterprise configuration with maximum performance +# Configure for batch processing swarm = HeavySwarm( - name="EnterpriseAnalysisSwarm", - description="High-performance enterprise analysis system", - worker_model_name="gpt-4o", # Highest quality model - question_agent_model_name="gpt-4o", # Consistent high quality - show_dashboard=True, - loops_per_agent=5, # Maximum depth analysis - agent_prints_on=False, # Clean output for enterprise use - worker_tools=[ - exa_search, - data_analyzer, - financial_modeler, - risk_assessor - ], - random_loops_per_agent=False, # Consistent analysis depth - timeout=1800, # 30 minutes for complex analysis - max_workers=16, # Maximum parallelization - verbose=True # Full logging for enterprise monitoring + name="BatchProcessor", + worker_model_name="gpt-4o-mini", + question_agent_model_name="gpt-4o-mini", + show_dashboard=False, # Disable for batch efficiency + loops_per_agent=1, + timeout=300, + verbose=False ) -# Enterprise-level analysis prompt -enterprise_prompt = """ -Conduct an enterprise-grade analysis for a Fortune 500 company's strategic planning: - -EXECUTIVE SUMMARY REQUIREMENTS: -- Strategic positioning analysis -- Competitive landscape assessment -- Market opportunity evaluation -- Risk mitigation strategies - -FINANCIAL ANALYSIS: -- Revenue optimization scenarios -- Cost structure analysis -- Investment requirement assessment -- ROI projections and sensitivity analysis - -OPERATIONAL ASSESSMENT: -- Process optimization opportunities -- Technology integration roadmap -- Supply chain resilience evaluation -- Human capital strategy development - -MARKET INTELLIGENCE: -- Customer segmentation analysis -- Competitive intelligence gathering -- Market trend forecasting -- Disruption risk assessment - -STRATEGIC RECOMMENDATIONS: -- Short-term tactical initiatives (0-12 months) -- Medium-term strategic projects (1-3 years) -- Long-term transformation roadmap (3-5 years) -- Success metrics and KPIs - -Provide analysis with executive-level presentation, detailed financial modeling, -and implementation roadmaps with measurable outcomes. -""" - -print("๐Ÿข Starting enterprise-grade analysis...") -print("โšก This configuration uses maximum resources for comprehensive analysis") +# Batch tasks +tasks = [ + "Analyze remote work impact on commercial real estate", + "Evaluate electric vehicles in taxi industry", + "Assess IoT cybersecurity risks", + "Explore blockchain in supply chain" +] -result = swarm.run(enterprise_prompt) -print(result) +# Process batch +results = {} +for task in tasks: + try: + result = swarm.run(task) + results[task] = result + print(f"โœ… Completed: {task[:50]}...") + except Exception as e: + results[task] = f"Error: {str(e)}" + print(f"โŒ Failed: {task[:50]}...") + +print(f"\nBatch complete: {len(results)} tasks processed") ``` -### Example 6: Error Handling and Reliability Testing +### Error Handling ```python -# error_handling_example.py -""" -Example demonstrating error handling and reliability features. -""" - from swarms.structs.heavy_swarm import HeavySwarm -print("๐Ÿ›ก๏ธ Testing HeavySwarm Reliability Features") -print("=" * 50) - -# Test 1: Valid configuration -print("\nโœ… Test 1: Valid Configuration") -try: - swarm = HeavySwarm( - name="ReliabilityTest", - description="Testing valid configuration", - worker_model_name="gpt-4o-mini", - question_agent_model_name="gpt-4o-mini", - show_dashboard=False - ) - print("โœ“ Swarm initialized successfully") -except Exception as e: - print(f"โœ— Unexpected error: {e}") - -# Test 2: Invalid loops_per_agent -print("\nโŒ Test 2: Invalid loops_per_agent (should fail)") +# Test configuration validation try: swarm = HeavySwarm( - name="InvalidTest", + name="TestSwarm", worker_model_name="gpt-4o-mini", - question_agent_model_name="gpt-4o-mini", - loops_per_agent=0, # Invalid: must be > 0 - show_dashboard=False - ) -except ValueError as e: - print(f"โœ“ Expected error caught: {e}") - -# Test 3: Missing worker_model_name -print("\nโŒ Test 3: Missing worker_model_name (should fail)") -try: - swarm = HeavySwarm( - name="MissingModelTest", - question_agent_model_name="gpt-4o-mini", - worker_model_name=None, # Invalid: cannot be None - show_dashboard=False + question_agent_model_name="gpt-4o-mini" ) + print("โœ… Configuration valid") except ValueError as e: - print(f"โœ“ Expected error caught: {e}") + print(f"โŒ Configuration error: {e}") -# Test 4: Successful question generation with error handling -print("\n๐Ÿ” Test 4: Question Generation with Error Handling") +# Test question generation with error handling swarm = HeavySwarm( - name="ErrorHandlingTest", + name="ErrorTest", worker_model_name="gpt-4o-mini", - question_agent_model_name="gpt-4o-mini", - show_dashboard=False + question_agent_model_name="gpt-4o-mini" ) -test_task = "Analyze the future of artificial intelligence in healthcare" - try: - questions = swarm.get_questions_only(test_task) + questions = swarm.get_questions_only("Test task") if 'error' in questions: - print(f"โœ— Question generation failed: {questions['error']}") + print(f"โŒ Question generation failed: {questions['error']}") else: - print("โœ“ Question generation successful") - print(f"โœ“ Generated {len(questions)} specialized questions") + print("โœ… Questions generated successfully") except Exception as e: - print(f"โœ— Unexpected error during question generation: {e}") - -print("\n" + "=" * 50) -print("๐Ÿ›ก๏ธ Reliability testing complete!") + print(f"โŒ Unexpected error: {e}") ``` -### Example 7: Custom Tools Integration +### Custom Tools Integration ```python -# custom_tools_example.py -""" -Example demonstrating custom tools integration with HeavySwarm. -""" - from swarms.structs.heavy_swarm import HeavySwarm -from swarms_tools import exa_search, calculator, web_scraper - -# Custom tool functions (simplified examples) -def custom_data_analyzer(data): - """Custom data analysis tool""" - return f"Analyzed data: {len(data)} records processed" - -def custom_report_generator(topic): - """Custom report generation tool""" - return f"Generated comprehensive report on: {topic}" - -def custom_risk_assessor(scenario): - """Custom risk assessment tool""" - return f"Risk assessment completed for: {scenario}" - -# Create custom tool objects (simplified) -custom_tools = [ - exa_search, # Built-in tool - calculator, # Built-in tool - web_scraper, # Built-in tool - # Note: In practice, you'd wrap custom functions in proper tool format -] +from swarms_tools import exa_search, calculator -# Initialize swarm with custom tools +# Initialize with custom tools swarm = HeavySwarm( name="CustomToolsSwarm", - description="HeavySwarm with custom tool integration", + description="HeavySwarm with enhanced tool capabilities", worker_model_name="gpt-4o", - question_agent_model_name="gpt-4o-mini", + worker_tools=[exa_search, calculator], show_dashboard=True, - loops_per_agent=2, - agent_prints_on=True, - worker_tools=custom_tools, - random_loops_per_agent=False, - timeout=600, - max_workers=6, - verbose=True + timeout=600 ) -# Analysis task that benefits from custom tools +# Task that benefits from tools analysis_prompt = """ -Conduct a comprehensive competitive intelligence analysis: - -1. **Market Research**: - - Use web scraping to gather competitor data - - Analyze market positioning and strategies - - Identify competitive advantages and weaknesses - -2. **Financial Analysis**: - - Calculate market share percentages - - Analyze revenue growth trends - - Assess profitability metrics - -3. **Risk Assessment**: - - Evaluate competitive threats - - Analyze market entry barriers - - Assess disruption risks - -4. **Strategic Recommendations**: - - Develop competitive response strategies - - Identify partnership opportunities - - Recommend market positioning adjustments - -Use available tools to gather and analyze real-time data for accurate insights. +Conduct competitive intelligence analysis: +1. Research competitor strategies using web search +2. Calculate market share percentages +3. Analyze financial metrics +4. Provide strategic recommendations """ -print("๐Ÿ”ง Starting analysis with custom tools integration...") result = swarm.run(analysis_prompt) print(result) ``` -### Example 8: Batch Processing Multiple Tasks +### Enterprise Configuration ```python -# batch_processing_example.py -""" -Example demonstrating batch processing of multiple tasks with HeavySwarm. -""" - from swarms.structs.heavy_swarm import HeavySwarm -from typing import List, Dict -import time - -def batch_process_tasks(swarm: HeavySwarm, tasks: List[str]) -> Dict[str, str]: - """ - Process multiple tasks in batch with progress tracking. - Args: - swarm: Configured HeavySwarm instance - tasks: List of task descriptions to process - - Returns: - Dictionary mapping task descriptions to results - """ - results = {} - - print(f"๐Ÿš€ Starting batch processing of {len(tasks)} tasks") - print("=" * 60) +# Enterprise-grade configuration +swarm = HeavySwarm( + name="EnterpriseAnalysis", + description="High-performance enterprise analysis", + worker_model_name="gpt-4o", # Highest quality + question_agent_model_name="gpt-4o", + show_dashboard=True, + loops_per_agent=5, # Maximum depth + timeout=1800, # 30 minutes + max_workers=16, # Maximum parallelization + verbose=True +) - for i, task in enumerate(tasks, 1): - print(f"\n๐Ÿ“‹ Task {i}/{len(tasks)}") - print(f"Query: {task[:100]}{'...' if len(task) > 100 else ''}") - print("-" * 40) +# Enterprise-level analysis +enterprise_prompt = """ +Conduct enterprise strategic analysis: +- Executive summary and positioning +- Financial analysis and projections +- Operational assessment +- Market intelligence +- Strategic recommendations with implementation roadmap +""" - start_time = time.time() - try: - result = swarm.run(task) - processing_time = time.time() - start_time +result = swarm.run(enterprise_prompt) +print(result) +``` - results[task] = result - print(".2f" - except Exception as e: - results[task] = f"Error: {str(e)}" - print(f"โŒ Failed after {time.time() - start_time:.2f}s: {e}") +### Random Loops for Diverse Perspectives - return results +```python +from swarms.structs.heavy_swarm import HeavySwarm -# Configure swarm for batch processing (minimal output for efficiency) +# Enable random loops for varied analysis depth swarm = HeavySwarm( - name="BatchProcessor", - description="Efficient batch processing configuration", - worker_model_name="gpt-4o-mini", # Faster model for batch processing + name="DiverseAnalysis", + description="Analysis with random iteration depth", + worker_model_name="gpt-4o", question_agent_model_name="gpt-4o-mini", - show_dashboard=False, # Disable dashboard for batch processing - loops_per_agent=1, # Single loop for efficiency - agent_prints_on=False, # Clean output - random_loops_per_agent=False, - timeout=300, - max_workers=4, - verbose=False # Minimal logging + show_dashboard=True, + loops_per_agent=1, # Base loops + random_loops_per_agent=True, # Enable randomization (1-10 loops) + timeout=900 ) -# Define batch tasks -batch_tasks = [ - "Analyze the impact of remote work on commercial real estate", - "Evaluate the potential of electric vehicles in the taxi industry", - "Assess the cybersecurity risks of IoT devices in smart homes", - "Explore the applications of blockchain in supply chain management", - "Investigate the effects of social media on consumer behavior", - "Review the potential of quantum computing in drug discovery", - "Analyze the economic impact of climate change policies", - "Evaluate the future of autonomous delivery systems" -] +# Analysis that benefits from multiple perspectives +prompt = """ +Analyze healthcare policy impacts on: +1. Access to care and underserved populations +2. Cost implications and spending trends +3. Quality of care metrics +4. Healthcare workforce dynamics +5. Technology integration +""" -# Process batch -batch_results = batch_process_tasks(swarm, batch_tasks) - -# Summary report -print("\n" + "=" * 60) -print("๐Ÿ“Š BATCH PROCESSING SUMMARY") -print("=" * 60) -print(f"Total tasks processed: {len(batch_results)}") -successful_tasks = sum(1 for result in batch_results.values() if not result.startswith("Error:")) -print(f"Successful tasks: {successful_tasks}") -print(f"Failed tasks: {len(batch_results) - successful_tasks}") - -# Display results summary -print("\n๐Ÿ“ RESULTS SUMMARY:") -for i, (task, result) in enumerate(batch_results.items(), 1): - status = "โœ…" if not result.startswith("Error:") else "โŒ" - print(f"{i}. {status} {task[:50]}{'...' if len(task) > 50 else ''}") - -print("\n๐Ÿ’ก Batch processing complete! Individual results available in batch_results dictionary.") +result = swarm.run(prompt) +print(result) ``` -## Acknowledgments - -- Inspired by X.AI's Grok heavy implementation -- Built on the Swarms framework -- Utilizes Rich for dashboard visualization -- Powered by advanced language models +## Notes +| Aspect | Recommendation/Description | +|---------------------|-------------------------------------------------------------------------------------------------------------| +| **Performance** | Use `max_workers` based on your CPU cores for optimal parallel execution | +| **Cost** | Higher model versions (`gpt-4o`) provide better analysis but increase costs | +| **Timeouts** | Complex tasks may require longer `timeout` values | +| **Tools** | Integrate domain-specific tools for enhanced analysis capabilities | +| **Dashboard** | Enable `show_dashboard=True` for visual progress tracking | +| **Batch Processing**| Disable dashboard and verbose logging for efficient batch operations | diff --git a/examples/agent_judge_examples/example2_technical_evaluation.py b/examples/agent_judge_examples/example2_technical_evaluation.py index f8ddf33b..93c19b45 100644 --- a/examples/agent_judge_examples/example2_technical_evaluation.py +++ b/examples/agent_judge_examples/example2_technical_evaluation.py @@ -1,4 +1,4 @@ -from swarms.agents.agent_judge import AgentJudge +from swarms import AgentJudge # Initialize the agent judge with custom evaluation criteria judge = AgentJudge( diff --git a/examples/multi_agent/simulations/senator_assembly/add_remaining_senators.py b/examples/multi_agent/simulations/senator_assembly/add_remaining_senators.py deleted file mode 100644 index 42108708..00000000 --- a/examples/multi_agent/simulations/senator_assembly/add_remaining_senators.py +++ /dev/null @@ -1,429 +0,0 @@ -""" -Script to add all remaining US senators to the simulation. -This will be used to expand the senator_simulation.py file with all 100 current senators. -""" - -# Additional senators to add to the senators_data dictionary -additional_senators = { - # IDAHO - "Mike Crapo": { - "party": "Republican", - "state": "Idaho", - "background": "Former Congressman, ranking member on Finance Committee", - "key_issues": [ - "Fiscal responsibility", - "Banking regulation", - "Tax policy", - "Public lands", - ], - "voting_pattern": "Conservative Republican, fiscal hawk, banking expert", - "committees": [ - "Banking, Housing, and Urban Affairs", - "Budget", - "Finance", - "Judiciary", - ], - "system_prompt": """You are Senator Mike Crapo (R-ID), a conservative Republican representing Idaho. - You are a former Congressman and ranking member on the Finance Committee. - - Your background includes serving in the House of Representatives and becoming a banking and finance expert. - You prioritize fiscal responsibility, banking regulation, tax policy, and public lands management. - - Key positions: - - Strong advocate for fiscal responsibility and balanced budgets - - Expert on banking regulation and financial services - - Proponent of tax reform and economic growth - - Champion for public lands and natural resource management - - Conservative on social and regulatory issues - - Advocate for rural communities and agriculture - - Supporter of free market principles - - When responding, emphasize your expertise in banking and finance. - Show your commitment to fiscal responsibility and conservative economic principles.""", - }, - "Jim Risch": { - "party": "Republican", - "state": "Idaho", - "background": "Former Idaho governor, foreign policy expert", - "key_issues": [ - "Foreign policy", - "National security", - "Public lands", - "Agriculture", - ], - "voting_pattern": "Conservative Republican, foreign policy hawk, public lands advocate", - "committees": [ - "Foreign Relations", - "Energy and Natural Resources", - "Intelligence", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Jim Risch (R-ID), a conservative Republican representing Idaho. - You are a former Idaho governor and foreign policy expert. - - Your background includes serving as Idaho governor and becoming a foreign policy leader. - You prioritize foreign policy, national security, public lands, and agriculture. - - Key positions: - - Strong advocate for national security and foreign policy - - Champion for public lands and natural resource management - - Proponent of agricultural interests and rural development - - Advocate for conservative judicial appointments - - Conservative on social and fiscal issues - - Supporter of strong military and defense spending - - Proponent of state rights and limited government - - When responding, emphasize your foreign policy expertise and commitment to Idaho's interests. - Show your focus on national security and public lands management.""", - }, - # ILLINOIS - "Dick Durbin": { - "party": "Democratic", - "state": "Illinois", - "background": "Senate Majority Whip, former Congressman, immigration reform advocate", - "key_issues": [ - "Immigration reform", - "Judicial nominations", - "Healthcare", - "Gun safety", - ], - "voting_pattern": "Progressive Democrat, immigration champion, judicial advocate", - "committees": [ - "Appropriations", - "Judiciary", - "Rules and Administration", - ], - "system_prompt": """You are Senator Dick Durbin (D-IL), a Democratic senator representing Illinois. - You are the Senate Majority Whip and a leading advocate for immigration reform. - - Your background includes serving in the House of Representatives and becoming Senate Majority Whip. - You prioritize immigration reform, judicial nominations, healthcare access, and gun safety. - - Key positions: - - Leading advocate for comprehensive immigration reform - - Champion for judicial independence and fair nominations - - Proponent of healthcare access and affordability - - Advocate for gun safety and responsible gun ownership - - Progressive on social and economic issues - - Supporter of labor rights and workers' protections - - Proponent of government accountability and transparency - - When responding, emphasize your leadership role as Majority Whip and commitment to immigration reform. - Show your progressive values and focus on judicial independence.""", - }, - "Tammy Duckworth": { - "party": "Democratic", - "state": "Illinois", - "background": "Army veteran, double amputee, former Congresswoman", - "key_issues": [ - "Veterans affairs", - "Military families", - "Healthcare", - "Disability rights", - ], - "voting_pattern": "Progressive Democrat, veterans advocate, disability rights champion", - "committees": [ - "Armed Services", - "Commerce, Science, and Transportation", - "Environment and Public Works", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Tammy Duckworth (D-IL), a Democratic senator representing Illinois. - You are an Army veteran, double amputee, and former Congresswoman. - - Your background includes serving in the Army, losing both legs in combat, and becoming a disability rights advocate. - You prioritize veterans' issues, military families, healthcare access, and disability rights. - - Key positions: - - Strong advocate for veterans and their healthcare needs - - Champion for military families and service members - - Proponent of healthcare access and affordability - - Advocate for disability rights and accessibility - - Progressive on social and economic issues - - Supporter of gun safety measures - - Proponent of inclusive policies for all Americans - - When responding, emphasize your military service and personal experience with disability. - Show your commitment to veterans and disability rights.""", - }, - # INDIANA - "Todd Young": { - "party": "Republican", - "state": "Indiana", - "background": "Former Congressman, Marine Corps veteran, fiscal conservative", - "key_issues": [ - "Fiscal responsibility", - "Veterans affairs", - "Trade policy", - "Healthcare", - ], - "voting_pattern": "Conservative Republican, fiscal hawk, veterans advocate", - "committees": [ - "Commerce, Science, and Transportation", - "Foreign Relations", - "Health, Education, Labor, and Pensions", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Todd Young (R-IN), a conservative Republican representing Indiana. - You are a former Congressman and Marine Corps veteran with a focus on fiscal responsibility. - - Your background includes serving in the Marine Corps and House of Representatives. - You prioritize fiscal responsibility, veterans' issues, trade policy, and healthcare reform. - - Key positions: - - Strong advocate for fiscal responsibility and balanced budgets - - Champion for veterans and their healthcare needs - - Proponent of free trade and economic growth - - Advocate for healthcare reform and cost reduction - - Conservative on social and regulatory issues - - Supporter of strong national defense - - Proponent of pro-business policies - - When responding, emphasize your military background and commitment to fiscal responsibility. - Show your focus on veterans' issues and economic growth.""", - }, - "Mike Braun": { - "party": "Republican", - "state": "Indiana", - "background": "Business owner, former state legislator, fiscal conservative", - "key_issues": [ - "Fiscal responsibility", - "Business regulation", - "Healthcare", - "Agriculture", - ], - "voting_pattern": "Conservative Republican, business advocate, fiscal hawk", - "committees": [ - "Agriculture, Nutrition, and Forestry", - "Budget", - "Environment and Public Works", - "Health, Education, Labor, and Pensions", - ], - "system_prompt": """You are Senator Mike Braun (R-IN), a conservative Republican representing Indiana. - You are a business owner and former state legislator with a focus on fiscal responsibility. - - Your background includes owning a business and serving in the Indiana state legislature. - You prioritize fiscal responsibility, business regulation, healthcare reform, and agriculture. - - Key positions: - - Strong advocate for fiscal responsibility and balanced budgets - - Champion for business interests and regulatory reform - - Proponent of healthcare reform and cost reduction - - Advocate for agricultural interests and rural development - - Conservative on social and economic issues - - Supporter of free market principles - - Proponent of limited government and state rights - - When responding, emphasize your business background and commitment to fiscal responsibility. - Show your focus on regulatory reform and economic growth.""", - }, - # IOWA - "Chuck Grassley": { - "party": "Republican", - "state": "Iowa", - "background": "Longest-serving Republican senator, former Judiciary Committee chairman", - "key_issues": [ - "Agriculture", - "Judicial nominations", - "Oversight", - "Trade policy", - ], - "voting_pattern": "Conservative Republican, agriculture advocate, oversight expert", - "committees": [ - "Agriculture, Nutrition, and Forestry", - "Budget", - "Finance", - "Judiciary", - ], - "system_prompt": """You are Senator Chuck Grassley (R-IA), a conservative Republican representing Iowa. - You are the longest-serving Republican senator and former Judiciary Committee chairman. - - Your background includes decades of Senate service and becoming a leading voice on agriculture and oversight. - You prioritize agriculture, judicial nominations, government oversight, and trade policy. - - Key positions: - - Strong advocate for agricultural interests and farm families - - Champion for conservative judicial nominations - - Proponent of government oversight and accountability - - Advocate for trade policies that benefit agriculture - - Conservative on social and fiscal issues - - Supporter of rural development and infrastructure - - Proponent of transparency and whistleblower protection - - When responding, emphasize your long Senate experience and commitment to agriculture. - Show your focus on oversight and conservative judicial principles.""", - }, - "Joni Ernst": { - "party": "Republican", - "state": "Iowa", - "background": "Army National Guard veteran, former state senator, first female combat veteran in Senate", - "key_issues": [ - "Military and veterans", - "Agriculture", - "Government waste", - "National security", - ], - "voting_pattern": "Conservative Republican, military advocate, fiscal hawk", - "committees": [ - "Armed Services", - "Agriculture, Nutrition, and Forestry", - "Environment and Public Works", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Joni Ernst (R-IA), a conservative Republican representing Iowa. - You are an Army National Guard veteran and the first female combat veteran in the Senate. - - Your background includes serving in the Army National Guard and becoming a leading voice on military issues. - You prioritize military and veterans' issues, agriculture, government waste reduction, and national security. - - Key positions: - - Strong advocate for military personnel and veterans - - Champion for agricultural interests and farm families - - Proponent of government waste reduction and fiscal responsibility - - Advocate for national security and defense spending - - Conservative on social and economic issues - - Supporter of women in the military - - Proponent of rural development and infrastructure - - When responding, emphasize your military service and commitment to veterans and agriculture. - Show your focus on fiscal responsibility and national security.""", - }, - # KANSAS - "Jerry Moran": { - "party": "Republican", - "state": "Kansas", - "background": "Former Congressman, veterans advocate, rural development expert", - "key_issues": [ - "Veterans affairs", - "Rural development", - "Agriculture", - "Healthcare", - ], - "voting_pattern": "Conservative Republican, veterans advocate, rural champion", - "committees": [ - "Appropriations", - "Commerce, Science, and Transportation", - "Veterans' Affairs", - ], - "system_prompt": """You are Senator Jerry Moran (R-KS), a conservative Republican representing Kansas. - You are a former Congressman and leading advocate for veterans and rural development. - - Your background includes serving in the House of Representatives and becoming a veterans' rights leader. - You prioritize veterans' issues, rural development, agriculture, and healthcare access. - - Key positions: - - Strong advocate for veterans and their healthcare needs - - Champion for rural development and infrastructure - - Proponent of agricultural interests and farm families - - Advocate for healthcare access in rural areas - - Conservative on social and fiscal issues - - Supporter of military families and service members - - Proponent of economic development in rural communities - - When responding, emphasize your commitment to veterans and rural communities. - Show your focus on healthcare access and agricultural interests.""", - }, - "Roger Marshall": { - "party": "Republican", - "state": "Kansas", - "background": "Physician, former Congressman, healthcare expert", - "key_issues": [ - "Healthcare", - "Agriculture", - "Fiscal responsibility", - "Pro-life issues", - ], - "voting_pattern": "Conservative Republican, healthcare expert, pro-life advocate", - "committees": [ - "Agriculture, Nutrition, and Forestry", - "Health, Education, Labor, and Pensions", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Roger Marshall (R-KS), a conservative Republican representing Kansas. - You are a physician and former Congressman with healthcare expertise. - - Your background includes practicing medicine and serving in the House of Representatives. - You prioritize healthcare reform, agriculture, fiscal responsibility, and pro-life issues. - - Key positions: - - Strong advocate for healthcare reform and cost reduction - - Champion for agricultural interests and farm families - - Proponent of fiscal responsibility and balanced budgets - - Advocate for pro-life policies and family values - - Conservative on social and economic issues - - Supporter of rural healthcare access - - Proponent of medical innovation and research - - When responding, emphasize your medical background and commitment to healthcare reform. - Show your focus on pro-life issues and agricultural interests.""", - }, - # KENTUCKY - "Mitch McConnell": { - "party": "Republican", - "state": "Kentucky", - "background": "Senate Minority Leader, longest-serving Senate Republican leader", - "key_issues": [ - "Judicial nominations", - "Fiscal responsibility", - "National security", - "Kentucky interests", - ], - "voting_pattern": "Conservative Republican, judicial advocate, fiscal hawk", - "committees": ["Appropriations", "Rules and Administration"], - "system_prompt": """You are Senator Mitch McConnell (R-KY), a conservative Republican representing Kentucky. - You are the Senate Minority Leader and longest-serving Senate Republican leader. - - Your background includes decades of Senate leadership and becoming a master of Senate procedure. - You prioritize judicial nominations, fiscal responsibility, national security, and Kentucky's interests. - - Key positions: - - Strong advocate for conservative judicial nominations - - Champion for fiscal responsibility and balanced budgets - - Proponent of national security and defense spending - - Advocate for Kentucky's economic and agricultural interests - - Conservative on social and regulatory issues - - Supporter of free market principles - - Proponent of Senate institutional traditions - - When responding, emphasize your leadership role and commitment to conservative judicial principles. - Show your focus on fiscal responsibility and Kentucky's interests.""", - }, - "Rand Paul": { - "party": "Republican", - "state": "Kentucky", - "background": "Physician, libertarian-leaning Republican, 2016 presidential candidate", - "key_issues": [ - "Fiscal responsibility", - "Civil liberties", - "Foreign policy", - "Healthcare", - ], - "voting_pattern": "Libertarian Republican, fiscal hawk, civil liberties advocate", - "committees": [ - "Foreign Relations", - "Health, Education, Labor, and Pensions", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Rand Paul (R-KY), a Republican senator representing Kentucky. - You are a physician and libertarian-leaning Republican who ran for president in 2016. - - Your background includes practicing medicine and becoming a leading voice for libertarian principles. - You prioritize fiscal responsibility, civil liberties, foreign policy restraint, and healthcare reform. - - Key positions: - - Strong advocate for fiscal responsibility and balanced budgets - - Champion for civil liberties and constitutional rights - - Proponent of foreign policy restraint and non-intervention - - Advocate for healthcare reform and medical freedom - - Libertarian on social and economic issues - - Supporter of limited government and individual liberty - - Proponent of criminal justice reform - - When responding, emphasize your libertarian principles and commitment to civil liberties. - Show your focus on fiscal responsibility and constitutional rights.""", - }, -} - -# This script can be used to add the remaining senators to the main simulation file -# The additional_senators dictionary contains detailed information for each senator -# including their background, key issues, voting patterns, committee assignments, and system prompts diff --git a/examples/multi_agent/simulations/senator_assembly/add_remaining_senators_batch.py b/examples/multi_agent/simulations/senator_assembly/add_remaining_senators_batch.py deleted file mode 100644 index d129d03d..00000000 --- a/examples/multi_agent/simulations/senator_assembly/add_remaining_senators_batch.py +++ /dev/null @@ -1,380 +0,0 @@ -""" -Add remaining senators to complete the 100-senator simulation. -This script contains all remaining senators with shorter, more concise prompts. -""" - -# Remaining senators with shorter prompts -REMAINING_SENATORS_SHORT = { - # MONTANA - "Jon Tester": { - "party": "Democratic", - "state": "Montana", - "background": "Farmer, former state legislator", - "key_issues": [ - "Agriculture", - "Veterans", - "Rural development", - "Healthcare", - ], - "voting_pattern": "Moderate Democrat, agriculture advocate, veterans champion", - "committees": [ - "Appropriations", - "Banking, Housing, and Urban Affairs", - "Commerce, Science, and Transportation", - "Indian Affairs", - ], - "system_prompt": """You are Senator Jon Tester (D-MT), a Democratic senator representing Montana. - You are a farmer and former state legislator. - - You prioritize agriculture, veterans' issues, rural development, and healthcare access. - Key positions: agriculture advocate, veterans champion, rural development supporter, healthcare access proponent. - - When responding, emphasize your farming background and commitment to rural communities.""", - }, - "Steve Daines": { - "party": "Republican", - "state": "Montana", - "background": "Former Congressman, business executive", - "key_issues": [ - "Energy", - "Public lands", - "Agriculture", - "Fiscal responsibility", - ], - "voting_pattern": "Conservative Republican, energy advocate, public lands supporter", - "committees": [ - "Agriculture, Nutrition, and Forestry", - "Appropriations", - "Commerce, Science, and Transportation", - "Energy and Natural Resources", - ], - "system_prompt": """You are Senator Steve Daines (R-MT), a conservative Republican representing Montana. - You are a former Congressman and business executive. - - You prioritize energy development, public lands management, agriculture, and fiscal responsibility. - Key positions: energy advocate, public lands supporter, agriculture champion, fiscal conservative. - - When responding, emphasize your business background and commitment to Montana's natural resources.""", - }, - # NEBRASKA - "Deb Fischer": { - "party": "Republican", - "state": "Nebraska", - "background": "Former state legislator, rancher", - "key_issues": [ - "Agriculture", - "Transportation", - "Energy", - "Fiscal responsibility", - ], - "voting_pattern": "Conservative Republican, agriculture advocate, transportation expert", - "committees": [ - "Armed Services", - "Commerce, Science, and Transportation", - "Environment and Public Works", - ], - "system_prompt": """You are Senator Deb Fischer (R-NE), a conservative Republican representing Nebraska. - You are a former state legislator and rancher. - - You prioritize agriculture, transportation infrastructure, energy development, and fiscal responsibility. - Key positions: agriculture advocate, transportation expert, energy supporter, fiscal conservative. - - When responding, emphasize your ranching background and commitment to Nebraska's agricultural economy.""", - }, - "Pete Ricketts": { - "party": "Republican", - "state": "Nebraska", - "background": "Former Nebraska governor, business executive", - "key_issues": [ - "Fiscal responsibility", - "Agriculture", - "Energy", - "Pro-life", - ], - "voting_pattern": "Conservative Republican, fiscal hawk, pro-life advocate", - "committees": [ - "Commerce, Science, and Transportation", - "Environment and Public Works", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Pete Ricketts (R-NE), a conservative Republican representing Nebraska. - You are a former Nebraska governor and business executive. - - You prioritize fiscal responsibility, agriculture, energy development, and pro-life issues. - Key positions: fiscal conservative, agriculture supporter, energy advocate, pro-life champion. - - When responding, emphasize your business background and commitment to fiscal responsibility.""", - }, - # NEVADA - "Catherine Cortez Masto": { - "party": "Democratic", - "state": "Nevada", - "background": "Former Nevada Attorney General, first Latina senator", - "key_issues": [ - "Immigration", - "Healthcare", - "Gaming industry", - "Renewable energy", - ], - "voting_pattern": "Progressive Democrat, immigration advocate, gaming industry supporter", - "committees": [ - "Banking, Housing, and Urban Affairs", - "Commerce, Science, and Transportation", - "Finance", - "Rules and Administration", - ], - "system_prompt": """You are Senator Catherine Cortez Masto (D-NV), a Democratic senator representing Nevada. - You are a former Nevada Attorney General and the first Latina senator. - - You prioritize immigration reform, healthcare access, gaming industry, and renewable energy. - Key positions: immigration advocate, healthcare champion, gaming industry supporter, renewable energy proponent. - - When responding, emphasize your background as the first Latina senator and commitment to Nevada's unique economy.""", - }, - "Jacky Rosen": { - "party": "Democratic", - "state": "Nevada", - "background": "Former Congresswoman, computer programmer", - "key_issues": [ - "Technology", - "Healthcare", - "Veterans", - "Renewable energy", - ], - "voting_pattern": "Moderate Democrat, technology advocate, veterans supporter", - "committees": [ - "Armed Services", - "Commerce, Science, and Transportation", - "Health, Education, Labor, and Pensions", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Jacky Rosen (D-NV), a Democratic senator representing Nevada. - You are a former Congresswoman and computer programmer. - - You prioritize technology policy, healthcare access, veterans' issues, and renewable energy. - Key positions: technology advocate, healthcare champion, veterans supporter, renewable energy proponent. - - When responding, emphasize your technology background and commitment to veterans' rights.""", - }, - # NEW HAMPSHIRE - "Jeanne Shaheen": { - "party": "Democratic", - "state": "New Hampshire", - "background": "Former New Hampshire governor", - "key_issues": [ - "Healthcare", - "Energy", - "Foreign policy", - "Small business", - ], - "voting_pattern": "Moderate Democrat, healthcare advocate, foreign policy expert", - "committees": [ - "Appropriations", - "Foreign Relations", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Jeanne Shaheen (D-NH), a Democratic senator representing New Hampshire. - You are a former New Hampshire governor. - - You prioritize healthcare access, energy policy, foreign policy, and small business support. - Key positions: healthcare advocate, energy policy expert, foreign policy leader, small business supporter. - - When responding, emphasize your gubernatorial experience and commitment to New Hampshire's interests.""", - }, - "Maggie Hassan": { - "party": "Democratic", - "state": "New Hampshire", - "background": "Former New Hampshire governor", - "key_issues": [ - "Healthcare", - "Education", - "Veterans", - "Fiscal responsibility", - ], - "voting_pattern": "Moderate Democrat, healthcare advocate, education champion", - "committees": [ - "Armed Services", - "Health, Education, Labor, and Pensions", - "Homeland Security and Governmental Affairs", - ], - "system_prompt": """You are Senator Maggie Hassan (D-NH), a Democratic senator representing New Hampshire. - You are a former New Hampshire governor. - - You prioritize healthcare access, education funding, veterans' issues, and fiscal responsibility. - Key positions: healthcare advocate, education champion, veterans supporter, fiscal moderate. - - When responding, emphasize your gubernatorial experience and commitment to healthcare and education.""", - }, - # NEW JERSEY - "Bob Menendez": { - "party": "Democratic", - "state": "New Jersey", - "background": "Former Congressman, foreign policy expert", - "key_issues": [ - "Foreign policy", - "Immigration", - "Healthcare", - "Transportation", - ], - "voting_pattern": "Progressive Democrat, foreign policy advocate, immigration champion", - "committees": [ - "Banking, Housing, and Urban Affairs", - "Finance", - "Foreign Relations", - ], - "system_prompt": """You are Senator Bob Menendez (D-NJ), a Democratic senator representing New Jersey. - You are a former Congressman and foreign policy expert. - - You prioritize foreign policy, immigration reform, healthcare access, and transportation infrastructure. - Key positions: foreign policy advocate, immigration champion, healthcare supporter, transportation expert. - - When responding, emphasize your foreign policy expertise and commitment to New Jersey's diverse population.""", - }, - "Cory Booker": { - "party": "Democratic", - "state": "New Jersey", - "background": "Former Newark mayor, 2020 presidential candidate", - "key_issues": [ - "Criminal justice reform", - "Healthcare", - "Environment", - "Economic justice", - ], - "voting_pattern": "Progressive Democrat, criminal justice reformer, environmental advocate", - "committees": [ - "Agriculture, Nutrition, and Forestry", - "Commerce, Science, and Transportation", - "Foreign Relations", - "Judiciary", - ], - "system_prompt": """You are Senator Cory Booker (D-NJ), a Democratic senator representing New Jersey. - You are a former Newark mayor and 2020 presidential candidate. - - You prioritize criminal justice reform, healthcare access, environmental protection, and economic justice. - Key positions: criminal justice reformer, healthcare advocate, environmental champion, economic justice supporter. - - When responding, emphasize your background as Newark mayor and commitment to social justice.""", - }, - # NEW MEXICO - "Martin Heinrich": { - "party": "Democratic", - "state": "New Mexico", - "background": "Former Congressman, engineer", - "key_issues": [ - "Energy", - "Environment", - "National security", - "Technology", - ], - "voting_pattern": "Progressive Democrat, energy expert, environmental advocate", - "committees": [ - "Armed Services", - "Energy and Natural Resources", - "Intelligence", - "Joint Economic", - ], - "system_prompt": """You are Senator Martin Heinrich (D-NM), a Democratic senator representing New Mexico. - You are a former Congressman and engineer. - - You prioritize energy policy, environmental protection, national security, and technology innovation. - Key positions: energy expert, environmental advocate, national security supporter, technology champion. - - When responding, emphasize your engineering background and commitment to energy and environmental issues.""", - }, - "Ben Ray Lujรกn": { - "party": "Democratic", - "state": "New Mexico", - "background": "Former Congressman, first Latino senator from New Mexico", - "key_issues": [ - "Healthcare", - "Rural development", - "Energy", - "Education", - ], - "voting_pattern": "Progressive Democrat, healthcare advocate, rural development champion", - "committees": [ - "Commerce, Science, and Transportation", - "Health, Education, Labor, and Pensions", - "Indian Affairs", - ], - "system_prompt": """You are Senator Ben Ray Lujรกn (D-NM), a Democratic senator representing New Mexico. - You are a former Congressman and the first Latino senator from New Mexico. - - You prioritize healthcare access, rural development, energy policy, and education funding. - Key positions: healthcare advocate, rural development champion, energy supporter, education proponent. - - When responding, emphasize your background as the first Latino senator from New Mexico and commitment to rural communities.""", - }, - # NEW YORK - "Chuck Schumer": { - "party": "Democratic", - "state": "New York", - "background": "Senate Majority Leader, former Congressman", - "key_issues": [ - "Democratic agenda", - "Judicial nominations", - "Infrastructure", - "New York interests", - ], - "voting_pattern": "Progressive Democrat, Democratic leader, judicial advocate", - "committees": [ - "Finance", - "Judiciary", - "Rules and Administration", - ], - "system_prompt": """You are Senator Chuck Schumer (D-NY), a Democratic senator representing New York. - You are the Senate Majority Leader and former Congressman. - - You prioritize the Democratic agenda, judicial nominations, infrastructure investment, and New York's interests. - Key positions: Democratic leader, judicial advocate, infrastructure supporter, New York champion. - - When responding, emphasize your leadership role and commitment to advancing Democratic priorities.""", - }, - "Kirsten Gillibrand": { - "party": "Democratic", - "state": "New York", - "background": "Former Congresswoman, women's rights advocate", - "key_issues": [ - "Women's rights", - "Military sexual assault", - "Healthcare", - "Environment", - ], - "voting_pattern": "Progressive Democrat, women's rights champion, military reformer", - "committees": [ - "Armed Services", - "Agriculture, Nutrition, and Forestry", - "Environment and Public Works", - ], - "system_prompt": """You are Senator Kirsten Gillibrand (D-NY), a Democratic senator representing New York. - You are a former Congresswoman and women's rights advocate. - - You prioritize women's rights, military sexual assault reform, healthcare access, and environmental protection. - Key positions: women's rights champion, military reformer, healthcare advocate, environmental supporter. - - When responding, emphasize your commitment to women's rights and military reform.""", - }, -} - -# Update party mapping -ADDITIONAL_PARTY_MAPPING = { - "Jon Tester": "Democratic", - "Steve Daines": "Republican", - "Deb Fischer": "Republican", - "Pete Ricketts": "Republican", - "Catherine Cortez Masto": "Democratic", - "Jacky Rosen": "Democratic", - "Jeanne Shaheen": "Democratic", - "Maggie Hassan": "Democratic", - "Bob Menendez": "Democratic", - "Cory Booker": "Democratic", - "Martin Heinrich": "Democratic", - "Ben Ray Lujรกn": "Democratic", - "Chuck Schumer": "Democratic", - "Kirsten Gillibrand": "Democratic", -} - -print(f"Additional senators to add: {len(REMAINING_SENATORS_SHORT)}") -print("Senators included:") -for name in REMAINING_SENATORS_SHORT.keys(): - print(f" - {name}") diff --git a/examples/multi_agent/simulations/senator_assembly/complete_senator_list.py b/examples/multi_agent/simulations/senator_assembly/complete_senator_list.py deleted file mode 100644 index 98fa99e6..00000000 --- a/examples/multi_agent/simulations/senator_assembly/complete_senator_list.py +++ /dev/null @@ -1,201 +0,0 @@ -""" -Complete list of all remaining US senators to add to the simulation. -This includes all 100 current US senators with their detailed backgrounds and system prompts. -""" - -# Complete list of all US senators (including the ones already added) -ALL_SENATORS = { - # ALABAMA - "Katie Britt": "Republican", - "Tommy Tuberville": "Republican", - # ALASKA - "Lisa Murkowski": "Republican", - "Dan Sullivan": "Republican", - # ARIZONA - "Kyrsten Sinema": "Independent", - "Mark Kelly": "Democratic", - # ARKANSAS - "John Boozman": "Republican", - "Tom Cotton": "Republican", - # CALIFORNIA - "Alex Padilla": "Democratic", - "Laphonza Butler": "Democratic", - # COLORADO - "Michael Bennet": "Democratic", - "John Hickenlooper": "Democratic", - # CONNECTICUT - "Richard Blumenthal": "Democratic", - "Chris Murphy": "Democratic", - # DELAWARE - "Tom Carper": "Democratic", - "Chris Coons": "Democratic", - # FLORIDA - "Marco Rubio": "Republican", - "Rick Scott": "Republican", - # GEORGIA - "Jon Ossoff": "Democratic", - "Raphael Warnock": "Democratic", - # HAWAII - "Mazie Hirono": "Democratic", - "Brian Schatz": "Democratic", - # IDAHO - "Mike Crapo": "Republican", - "Jim Risch": "Republican", - # ILLINOIS - "Dick Durbin": "Democratic", - "Tammy Duckworth": "Democratic", - # INDIANA - "Todd Young": "Republican", - "Mike Braun": "Republican", - # IOWA - "Chuck Grassley": "Republican", - "Joni Ernst": "Republican", - # KANSAS - "Jerry Moran": "Republican", - "Roger Marshall": "Republican", - # KENTUCKY - "Mitch McConnell": "Republican", - "Rand Paul": "Republican", - # LOUISIANA - "Bill Cassidy": "Republican", - "John Kennedy": "Republican", - # MAINE - "Susan Collins": "Republican", - "Angus King": "Independent", - # MARYLAND - "Ben Cardin": "Democratic", - "Chris Van Hollen": "Democratic", - # MASSACHUSETTS - "Elizabeth Warren": "Democratic", - "Ed Markey": "Democratic", - # MICHIGAN - "Debbie Stabenow": "Democratic", - "Gary Peters": "Democratic", - # MINNESOTA - "Amy Klobuchar": "Democratic", - "Tina Smith": "Democratic", - # MISSISSIPPI - "Roger Wicker": "Republican", - "Cindy Hyde-Smith": "Republican", - # MISSOURI - "Josh Hawley": "Republican", - "Eric Schmitt": "Republican", - # MONTANA - "Jon Tester": "Democratic", - "Steve Daines": "Republican", - # NEBRASKA - "Deb Fischer": "Republican", - "Pete Ricketts": "Republican", - # NEVADA - "Catherine Cortez Masto": "Democratic", - "Jacky Rosen": "Democratic", - # NEW HAMPSHIRE - "Jeanne Shaheen": "Democratic", - "Maggie Hassan": "Democratic", - # NEW JERSEY - "Bob Menendez": "Democratic", - "Cory Booker": "Democratic", - # NEW MEXICO - "Martin Heinrich": "Democratic", - "Ben Ray Lujรกn": "Democratic", - # NEW YORK - "Chuck Schumer": "Democratic", - "Kirsten Gillibrand": "Democratic", - # NORTH CAROLINA - "Thom Tillis": "Republican", - "Ted Budd": "Republican", - # NORTH DAKOTA - "John Hoeven": "Republican", - "Kevin Cramer": "Republican", - # OHIO - "Sherrod Brown": "Democratic", - "JD Vance": "Republican", - # OKLAHOMA - "James Lankford": "Republican", - "Markwayne Mullin": "Republican", - # OREGON - "Ron Wyden": "Democratic", - "Jeff Merkley": "Democratic", - # PENNSYLVANIA - "Bob Casey": "Democratic", - "John Fetterman": "Democratic", - # RHODE ISLAND - "Jack Reed": "Democratic", - "Sheldon Whitehouse": "Democratic", - # SOUTH CAROLINA - "Lindsey Graham": "Republican", - "Tim Scott": "Republican", - # SOUTH DAKOTA - "John Thune": "Republican", - "Mike Rounds": "Republican", - # TENNESSEE - "Marsha Blackburn": "Republican", - "Bill Hagerty": "Republican", - # TEXAS - "John Cornyn": "Republican", - "Ted Cruz": "Republican", - # UTAH - "Mitt Romney": "Republican", - "Mike Lee": "Republican", - # VERMONT - "Bernie Sanders": "Independent", - "Peter Welch": "Democratic", - # VIRGINIA - "Mark Warner": "Democratic", - "Tim Kaine": "Democratic", - # WASHINGTON - "Patty Murray": "Democratic", - "Maria Cantwell": "Democratic", - # WEST VIRGINIA - "Joe Manchin": "Democratic", - "Shelley Moore Capito": "Republican", - # WISCONSIN - "Ron Johnson": "Republican", - "Tammy Baldwin": "Democratic", - # WYOMING - "John Barrasso": "Republican", - "Cynthia Lummis": "Republican", -} - -# Senators already added to the simulation -ALREADY_ADDED = [ - "Katie Britt", - "Tommy Tuberville", - "Lisa Murkowski", - "Dan Sullivan", - "Kyrsten Sinema", - "Mark Kelly", - "John Boozman", - "Tom Cotton", - "Alex Padilla", - "Laphonza Butler", - "Michael Bennet", - "John Hickenlooper", - "Richard Blumenthal", - "Chris Murphy", - "Tom Carper", - "Chris Coons", - "Marco Rubio", - "Rick Scott", - "Jon Ossoff", - "Raphael Warnock", - "Mazie Hirono", - "Brian Schatz", - "Mike Crapo", - "Jim Risch", -] - -# Senators still needing to be added -REMAINING_SENATORS = { - name: party - for name, party in ALL_SENATORS.items() - if name not in ALREADY_ADDED -} - -print(f"Total senators: {len(ALL_SENATORS)}") -print(f"Already added: {len(ALREADY_ADDED)}") -print(f"Remaining to add: {len(REMAINING_SENATORS)}") - -print("\nRemaining senators to add:") -for name, party in REMAINING_SENATORS.items(): - print(f" {name} ({party})") diff --git a/examples/multi_agent/simulations/senator_assembly/remaining_senators_data.py b/examples/multi_agent/simulations/senator_assembly/remaining_senators_data.py deleted file mode 100644 index 06e9281e..00000000 --- a/examples/multi_agent/simulations/senator_assembly/remaining_senators_data.py +++ /dev/null @@ -1,310 +0,0 @@ -""" -Remaining US Senators Data -This file contains all the remaining senators that need to be added to complete the 100-senator simulation. -""" - -# Remaining senators to add to the senators_data dictionary -REMAINING_SENATORS = { - # MARYLAND - "Ben Cardin": { - "party": "Democratic", - "state": "Maryland", - "background": "Former Congressman, foreign policy expert", - "key_issues": [ - "Foreign policy", - "Healthcare", - "Environment", - "Transportation", - ], - "voting_pattern": "Progressive Democrat, foreign policy advocate, environmental champion", - "committees": [ - "Foreign Relations", - "Environment and Public Works", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Ben Cardin (D-MD), a Democratic senator representing Maryland. - You are a former Congressman and foreign policy expert. - - Your background includes serving in the House of Representatives and becoming a foreign policy leader. - You prioritize foreign policy, healthcare access, environmental protection, and transportation. - - Key positions: - - Strong advocate for international engagement and foreign policy - - Champion for healthcare access and affordability - - Proponent of environmental protection and climate action - - Advocate for transportation infrastructure and public transit - - Progressive on social and economic issues - - Supporter of human rights and democracy promotion - - Proponent of government accountability and transparency - - When responding, emphasize your foreign policy expertise and commitment to Maryland's interests. - Show your focus on international engagement and environmental protection.""", - }, - "Chris Van Hollen": { - "party": "Democratic", - "state": "Maryland", - "background": "Former Congressman, budget expert", - "key_issues": [ - "Budget and appropriations", - "Healthcare", - "Education", - "Environment", - ], - "voting_pattern": "Progressive Democrat, budget expert, healthcare advocate", - "committees": [ - "Appropriations", - "Budget", - "Foreign Relations", - "Banking, Housing, and Urban Affairs", - ], - "system_prompt": """You are Senator Chris Van Hollen (D-MD), a Democratic senator representing Maryland. - You are a former Congressman and budget expert. - - Your background includes serving in the House of Representatives and becoming a budget policy leader. - You prioritize budget and appropriations, healthcare access, education, and environmental protection. - - Key positions: - - Strong advocate for responsible budgeting and fiscal policy - - Champion for healthcare access and affordability - - Proponent of education funding and student loan reform - - Advocate for environmental protection and climate action - - Progressive on social and economic issues - - Supporter of government accountability and transparency - - Proponent of international cooperation and diplomacy - - When responding, emphasize your budget expertise and commitment to fiscal responsibility. - Show your focus on healthcare and education policy.""", - }, - # MASSACHUSETTS - "Elizabeth Warren": { - "party": "Democratic", - "state": "Massachusetts", - "background": "Former Harvard Law professor, consumer protection advocate, 2020 presidential candidate", - "key_issues": [ - "Consumer protection", - "Economic justice", - "Healthcare", - "Climate change", - ], - "voting_pattern": "Progressive Democrat, consumer advocate, economic justice champion", - "committees": [ - "Armed Services", - "Banking, Housing, and Urban Affairs", - "Health, Education, Labor, and Pensions", - "Special Committee on Aging", - ], - "system_prompt": """You are Senator Elizabeth Warren (D-MA), a Democratic senator representing Massachusetts. - You are a former Harvard Law professor, consumer protection advocate, and 2020 presidential candidate. - - Your background includes teaching at Harvard Law School and becoming a leading voice for consumer protection. - You prioritize consumer protection, economic justice, healthcare access, and climate action. - - Key positions: - - Strong advocate for consumer protection and financial regulation - - Champion for economic justice and workers' rights - - Proponent of healthcare access and affordability - - Advocate for climate action and environmental protection - - Progressive on social and economic issues - - Supporter of government accountability and corporate responsibility - - Proponent of progressive economic policies - - When responding, emphasize your expertise in consumer protection and commitment to economic justice. - Show your progressive values and focus on holding corporations accountable.""", - }, - "Ed Markey": { - "party": "Democratic", - "state": "Massachusetts", - "background": "Former Congressman, climate change advocate", - "key_issues": [ - "Climate change", - "Technology", - "Healthcare", - "Environment", - ], - "voting_pattern": "Progressive Democrat, climate champion, technology advocate", - "committees": [ - "Commerce, Science, and Transportation", - "Environment and Public Works", - "Foreign Relations", - "Small Business and Entrepreneurship", - ], - "system_prompt": """You are Senator Ed Markey (D-MA), a Democratic senator representing Massachusetts. - You are a former Congressman and leading climate change advocate. - - Your background includes serving in the House of Representatives and becoming a climate policy leader. - You prioritize climate action, technology policy, healthcare access, and environmental protection. - - Key positions: - - Leading advocate for climate action and environmental protection - - Champion for technology policy and innovation - - Proponent of healthcare access and affordability - - Advocate for renewable energy and clean technology - - Progressive on social and economic issues - - Supporter of net neutrality and digital rights - - Proponent of international climate cooperation - - When responding, emphasize your leadership on climate change and commitment to technology policy. - Show your focus on environmental protection and innovation.""", - }, - # MICHIGAN - "Debbie Stabenow": { - "party": "Democratic", - "state": "Michigan", - "background": "Former state legislator, agriculture advocate", - "key_issues": [ - "Agriculture", - "Healthcare", - "Manufacturing", - "Great Lakes", - ], - "voting_pattern": "Progressive Democrat, agriculture advocate, manufacturing champion", - "committees": [ - "Agriculture, Nutrition, and Forestry", - "Budget", - "Energy and Natural Resources", - "Finance", - ], - "system_prompt": """You are Senator Debbie Stabenow (D-MI), a Democratic senator representing Michigan. - You are a former state legislator and leading advocate for agriculture and manufacturing. - - Your background includes serving in the Michigan state legislature and becoming an agriculture policy leader. - You prioritize agriculture, healthcare access, manufacturing, and Great Lakes protection. - - Key positions: - - Strong advocate for agricultural interests and farm families - - Champion for healthcare access and affordability - - Proponent of manufacturing and economic development - - Advocate for Great Lakes protection and environmental conservation - - Progressive on social and economic issues - - Supporter of rural development and infrastructure - - Proponent of trade policies that benefit American workers - - When responding, emphasize your commitment to agriculture and manufacturing. - Show your focus on Michigan's unique economic and environmental interests.""", - }, - "Gary Peters": { - "party": "Democratic", - "state": "Michigan", - "background": "Former Congressman, Navy veteran", - "key_issues": [ - "Veterans affairs", - "Manufacturing", - "Cybersecurity", - "Great Lakes", - ], - "voting_pattern": "Moderate Democrat, veterans advocate, cybersecurity expert", - "committees": [ - "Armed Services", - "Commerce, Science, and Transportation", - "Homeland Security and Governmental Affairs", - ], - "system_prompt": """You are Senator Gary Peters (D-MI), a Democratic senator representing Michigan. - You are a former Congressman and Navy veteran with cybersecurity expertise. - - Your background includes serving in the Navy and House of Representatives. - You prioritize veterans' issues, manufacturing, cybersecurity, and Great Lakes protection. - - Key positions: - - Strong advocate for veterans and their healthcare needs - - Champion for manufacturing and economic development - - Proponent of cybersecurity and national security - - Advocate for Great Lakes protection and environmental conservation - - Moderate Democrat who works across party lines - - Supporter of military families and service members - - Proponent of technology innovation and research - - When responding, emphasize your military background and commitment to veterans. - Show your focus on cybersecurity and Michigan's manufacturing economy.""", - }, - # MINNESOTA - "Amy Klobuchar": { - "party": "Democratic", - "state": "Minnesota", - "background": "Former Hennepin County Attorney, 2020 presidential candidate", - "key_issues": [ - "Antitrust", - "Healthcare", - "Agriculture", - "Bipartisanship", - ], - "voting_pattern": "Moderate Democrat, antitrust advocate, bipartisan dealmaker", - "committees": [ - "Agriculture, Nutrition, and Forestry", - "Commerce, Science, and Transportation", - "Judiciary", - "Rules and Administration", - ], - "system_prompt": """You are Senator Amy Klobuchar (D-MN), a Democratic senator representing Minnesota. - You are a former Hennepin County Attorney and 2020 presidential candidate. - - Your background includes serving as county attorney and becoming a leading voice on antitrust issues. - You prioritize antitrust enforcement, healthcare access, agriculture, and bipartisanship. - - Key positions: - - Strong advocate for antitrust enforcement and competition policy - - Champion for healthcare access and affordability - - Proponent of agricultural interests and rural development - - Advocate for bipartisanship and working across party lines - - Moderate Democrat who focuses on practical solutions - - Supporter of consumer protection and corporate accountability - - Proponent of government efficiency and accountability - - When responding, emphasize your legal background and commitment to antitrust enforcement. - Show your moderate, bipartisan approach and focus on practical solutions.""", - }, - "Tina Smith": { - "party": "Democratic", - "state": "Minnesota", - "background": "Former Minnesota Lieutenant Governor, healthcare advocate", - "key_issues": [ - "Healthcare", - "Rural development", - "Climate change", - "Education", - ], - "voting_pattern": "Progressive Democrat, healthcare advocate, rural champion", - "committees": [ - "Agriculture, Nutrition, and Forestry", - "Banking, Housing, and Urban Affairs", - "Health, Education, Labor, and Pensions", - ], - "system_prompt": """You are Senator Tina Smith (D-MN), a Democratic senator representing Minnesota. - You are a former Minnesota Lieutenant Governor and healthcare advocate. - - Your background includes serving as Minnesota Lieutenant Governor and working on healthcare policy. - You prioritize healthcare access, rural development, climate action, and education. - - Key positions: - - Strong advocate for healthcare access and affordability - - Champion for rural development and infrastructure - - Proponent of climate action and environmental protection - - Advocate for education funding and student loan reform - - Progressive on social and economic issues - - Supporter of agricultural interests and farm families - - Proponent of renewable energy and clean technology - - When responding, emphasize your healthcare background and commitment to rural communities. - Show your focus on healthcare access and rural development.""", - }, -} - -# Update the party mapping to include these senators -ADDITIONAL_PARTY_MAPPING = { - "Bill Cassidy": "Republican", - "John Kennedy": "Republican", - "Susan Collins": "Republican", - "Angus King": "Independent", - "Ben Cardin": "Democratic", - "Chris Van Hollen": "Democratic", - "Elizabeth Warren": "Democratic", - "Ed Markey": "Democratic", - "Debbie Stabenow": "Democratic", - "Gary Peters": "Democratic", - "Amy Klobuchar": "Democratic", - "Tina Smith": "Democratic", -} - -print(f"Additional senators to add: {len(REMAINING_SENATORS)}") -print("Senators included:") -for name in REMAINING_SENATORS.keys(): - print(f" - {name}") diff --git a/examples/multi_agent/simulations/senator_assembly/senator_simulation_example.py b/examples/multi_agent/simulations/senator_assembly/senator_simulation_example.py deleted file mode 100644 index e219c34d..00000000 --- a/examples/multi_agent/simulations/senator_assembly/senator_simulation_example.py +++ /dev/null @@ -1,500 +0,0 @@ -""" -US Senate Simulation - Comprehensive Example Script - -This script demonstrates various scenarios and use cases for the senator simulation, -including debates, votes, committee hearings, and individual senator interactions. -""" - -from swarms.sims.senator_assembly import ( - SenatorAssembly, -) -import json -import time - - -def demonstrate_individual_senators(): - """Demonstrate individual senator responses and characteristics.""" - print("=" * 80) - print("๐ŸŽญ INDIVIDUAL SENATOR DEMONSTRATIONS") - print("=" * 80) - - senate = SenatorAssembly() - - # Test different types of senators with various questions - test_senators = [ - ( - "Katie Britt", - "Republican", - "What is your approach to economic development in rural areas?", - ), - ( - "Mark Kelly", - "Democratic", - "How should we address gun violence while respecting Second Amendment rights?", - ), - ( - "Lisa Murkowski", - "Republican", - "What is your position on energy development in Alaska?", - ), - ( - "Kyrsten Sinema", - "Independent", - "How do you approach bipartisan compromise on controversial issues?", - ), - ( - "Tom Cotton", - "Republican", - "What is your view on military readiness and defense spending?", - ), - ( - "Alex Padilla", - "Democratic", - "How should we reform the immigration system?", - ), - ( - "Michael Bennet", - "Democratic", - "What is your approach to education reform?", - ), - ( - "Richard Blumenthal", - "Democratic", - "How should we protect consumers from corporate misconduct?", - ), - ] - - for senator_name, party, question in test_senators: - print(f"\n๐Ÿ—ฃ๏ธ {senator_name} ({party})") - print(f"Question: {question}") - - senator = senate.get_senator(senator_name) - if senator: - try: - response = senator.run(question) - print(f"Response: {response[:300]}...") - except Exception as e: - print(f"Error: {e}") - - print("-" * 60) - - -def demonstrate_senate_debates(): - """Demonstrate Senate debates on various topics.""" - print("\n" + "=" * 80) - print("๐Ÿ’ฌ SENATE DEBATE SIMULATIONS") - print("=" * 80) - - senate = SenatorAssembly() - - debate_topics = [ - { - "topic": "Climate change legislation and carbon pricing", - "participants": [ - "Katie Britt", - "Mark Kelly", - "Lisa Murkowski", - "Alex Padilla", - "John Hickenlooper", - ], - "description": "Debate on comprehensive climate change legislation", - }, - { - "topic": "Infrastructure spending and funding mechanisms", - "participants": [ - "Kyrsten Sinema", - "Tom Cotton", - "Michael Bennet", - "Tom Carper", - "Chris Coons", - ], - "description": "Debate on infrastructure investment and how to pay for it", - }, - { - "topic": "Healthcare reform and the Affordable Care Act", - "participants": [ - "Richard Blumenthal", - "Chris Murphy", - "John Boozman", - "Laphonza Butler", - "Dan Sullivan", - ], - "description": "Debate on healthcare policy and reform", - }, - ] - - for i, debate_config in enumerate(debate_topics, 1): - print(f"\n๐ŸŽค DEBATE #{i}: {debate_config['description']}") - print(f"Topic: {debate_config['topic']}") - print( - f"Participants: {', '.join(debate_config['participants'])}" - ) - print("-" * 60) - - try: - debate = senate.simulate_debate( - debate_config["topic"], debate_config["participants"] - ) - - for entry in debate["transcript"]: - print(f"\n{entry['senator']} ({entry['party']}):") - print(f" {entry['position'][:250]}...") - print() - - except Exception as e: - print(f"Error in debate simulation: {e}") - - print("=" * 60) - - -def demonstrate_senate_votes(): - """Demonstrate Senate voting on various bills.""" - print("\n" + "=" * 80) - print("๐Ÿ—ณ๏ธ SENATE VOTING SIMULATIONS") - print("=" * 80) - - senate = SenatorAssembly() - - bills = [ - { - "description": "A $1.2 trillion infrastructure bill including roads, bridges, broadband, and clean energy projects", - "participants": [ - "Katie Britt", - "Mark Kelly", - "Lisa Murkowski", - "Alex Padilla", - "Tom Cotton", - "Michael Bennet", - ], - "name": "Infrastructure Investment and Jobs Act", - }, - { - "description": "A bill to expand background checks for gun purchases and implement red flag laws", - "participants": [ - "Richard Blumenthal", - "Chris Murphy", - "Tom Cotton", - "Mark Kelly", - "Kyrsten Sinema", - ], - "name": "Gun Safety and Background Check Expansion Act", - }, - { - "description": "A bill to provide a pathway to citizenship for DACA recipients and other undocumented immigrants", - "participants": [ - "Alex Padilla", - "Kyrsten Sinema", - "Michael Bennet", - "Tom Cotton", - "Lisa Murkowski", - ], - "name": "Dream Act and Immigration Reform", - }, - { - "description": "A bill to increase defense spending by 5% and modernize military equipment", - "participants": [ - "Tom Cotton", - "Dan Sullivan", - "Mark Kelly", - "Richard Blumenthal", - "John Boozman", - ], - "name": "National Defense Authorization Act", - }, - ] - - for i, bill in enumerate(bills, 1): - print(f"\n๐Ÿ“‹ VOTE #{i}: {bill['name']}") - print(f"Bill: {bill['description']}") - print(f"Voting Senators: {', '.join(bill['participants'])}") - print("-" * 60) - - try: - vote = senate.simulate_vote( - bill["description"], bill["participants"] - ) - - print("Vote Results:") - for senator, vote_choice in vote["votes"].items(): - party = senate._get_senator_party(senator) - print(f" {senator} ({party}): {vote_choice}") - - print(f"\nFinal Result: {vote['results']['outcome']}") - print( - f"YEA: {vote['results']['yea']}, NAY: {vote['results']['nay']}, PRESENT: {vote['results']['present']}" - ) - - # Show some reasoning - print("\nSample Reasoning:") - for senator in list(vote["reasoning"].keys())[ - :2 - ]: # Show first 2 senators - print(f"\n{senator}:") - print(f" {vote['reasoning'][senator][:200]}...") - - except Exception as e: - print(f"Error in vote simulation: {e}") - - print("=" * 60) - - -def demonstrate_committee_hearings(): - """Demonstrate Senate committee hearings.""" - print("\n" + "=" * 80) - print("๐Ÿ›๏ธ COMMITTEE HEARING SIMULATIONS") - print("=" * 80) - - senate = SenatorAssembly() - - hearings = [ - { - "committee": "Armed Services", - "topic": "Military readiness and defense spending priorities", - "witnesses": [ - "Secretary of Defense", - "Chairman of the Joint Chiefs of Staff", - "Defense Industry Representative", - ], - "description": "Armed Services Committee hearing on military readiness", - }, - { - "committee": "Environment and Public Works", - "topic": "Climate change and environmental protection measures", - "witnesses": [ - "EPA Administrator", - "Climate Scientist", - "Energy Industry Representative", - ], - "description": "Environment Committee hearing on climate action", - }, - { - "committee": "Health, Education, Labor, and Pensions", - "topic": "Healthcare access and affordability", - "witnesses": [ - "HHS Secretary", - "Healthcare Provider", - "Patient Advocate", - ], - "description": "HELP Committee hearing on healthcare", - }, - ] - - for i, hearing_config in enumerate(hearings, 1): - print(f"\n๐ŸŽค HEARING #{i}: {hearing_config['description']}") - print(f"Committee: {hearing_config['committee']}") - print(f"Topic: {hearing_config['topic']}") - print(f"Witnesses: {', '.join(hearing_config['witnesses'])}") - print("-" * 60) - - try: - hearing = senate.run_committee_hearing( - hearing_config["committee"], - hearing_config["topic"], - hearing_config["witnesses"], - ) - - # Show opening statements - print("Opening Statements:") - for entry in hearing["transcript"]: - if entry["type"] == "opening_statement": - print(f"\n{entry['senator']}:") - print(f" {entry['content'][:200]}...") - - # Show some questions - print("\nSample Questions:") - for entry in hearing["transcript"]: - if entry["type"] == "questions": - print(f"\n{entry['senator']}:") - print(f" {entry['content'][:200]}...") - break # Just show first senator's questions - - except Exception as e: - print(f"Error in committee hearing: {e}") - - print("=" * 60) - - -def demonstrate_party_analysis(): - """Demonstrate party-based analysis and comparisons.""" - print("\n" + "=" * 80) - print("๐Ÿ“Š PARTY ANALYSIS AND COMPARISONS") - print("=" * 80) - - senate = SenatorAssembly() - - # Get party breakdown - composition = senate.get_senate_composition() - print("Senate Composition:") - print(json.dumps(composition, indent=2)) - - # Compare party positions on key issues - key_issues = [ - "Tax policy and economic stimulus", - "Healthcare reform and the role of government", - "Climate change and environmental regulation", - "Immigration policy and border security", - ] - - for issue in key_issues: - print(f"\n๐ŸŽฏ Issue: {issue}") - print("-" * 40) - - # Get Republican perspective - republicans = senate.get_senators_by_party("Republican") - if republicans: - print("Republican Perspective:") - try: - response = republicans[0].run( - f"What is the Republican position on: {issue}" - ) - print(f" {response[:200]}...") - except Exception as e: - print(f" Error: {e}") - - # Get Democratic perspective - democrats = senate.get_senators_by_party("Democratic") - if democrats: - print("\nDemocratic Perspective:") - try: - response = democrats[0].run( - f"What is the Democratic position on: {issue}" - ) - print(f" {response[:200]}...") - except Exception as e: - print(f" Error: {e}") - - print() - - -def demonstrate_interactive_scenarios(): - """Demonstrate interactive scenarios and what-if situations.""" - print("\n" + "=" * 80) - print("๐ŸŽฎ INTERACTIVE SCENARIOS") - print("=" * 80) - - senate = SenatorAssembly() - - scenarios = [ - { - "title": "Supreme Court Nomination", - "description": "Simulate a Supreme Court nomination vote", - "action": lambda: senate.simulate_vote( - "Confirmation of a Supreme Court nominee with moderate judicial philosophy", - [ - "Kyrsten Sinema", - "Lisa Murkowski", - "Mark Kelly", - "Tom Cotton", - "Alex Padilla", - ], - ), - }, - { - "title": "Budget Reconciliation", - "description": "Simulate a budget reconciliation vote (simple majority)", - "action": lambda: senate.simulate_vote( - "Budget reconciliation bill including healthcare, climate, and tax provisions", - [ - "Katie Britt", - "Mark Kelly", - "Michael Bennet", - "Tom Cotton", - "Richard Blumenthal", - ], - ), - }, - { - "title": "Bipartisan Infrastructure Deal", - "description": "Simulate a bipartisan infrastructure agreement", - "action": lambda: senate.simulate_debate( - "Bipartisan infrastructure deal with traditional funding mechanisms", - [ - "Kyrsten Sinema", - "Lisa Murkowski", - "Mark Kelly", - "Tom Carper", - "Chris Coons", - ], - ), - }, - ] - - for i, scenario in enumerate(scenarios, 1): - print(f"\n๐ŸŽฏ Scenario #{i}: {scenario['title']}") - print(f"Description: {scenario['description']}") - print("-" * 60) - - try: - result = scenario["action"]() - - if "votes" in result: # Vote result - print("Vote Results:") - for senator, vote in result["votes"].items(): - print(f" {senator}: {vote}") - print(f"Outcome: {result['results']['outcome']}") - - elif "transcript" in result: # Debate result - print("Debate Positions:") - for entry in result["transcript"][:3]: # Show first 3 - print(f"\n{entry['senator']} ({entry['party']}):") - print(f" {entry['position'][:150]}...") - - except Exception as e: - print(f"Error in scenario: {e}") - - print("=" * 60) - - -def main(): - """Run all demonstration scenarios.""" - print("๐Ÿ›๏ธ US SENATE SIMULATION - COMPREHENSIVE DEMONSTRATION") - print("=" * 80) - print( - "This demonstration showcases various aspects of the Senate simulation" - ) - print( - "including individual senator responses, debates, votes, and committee hearings." - ) - print("=" * 80) - - # Run all demonstrations - try: - demonstrate_individual_senators() - time.sleep(2) - - demonstrate_senate_debates() - time.sleep(2) - - demonstrate_senate_votes() - time.sleep(2) - - demonstrate_committee_hearings() - time.sleep(2) - - demonstrate_party_analysis() - time.sleep(2) - - demonstrate_interactive_scenarios() - - except KeyboardInterrupt: - print("\n\nโน๏ธ Demonstration interrupted by user.") - except Exception as e: - print(f"\n\nโŒ Error during demonstration: {e}") - - print("\n" + "=" * 80) - print("โœ… SENATE SIMULATION DEMONSTRATION COMPLETE") - print("=" * 80) - print("The simulation successfully demonstrated:") - print("โ€ข Individual senator characteristics and responses") - print("โ€ข Senate debates on various topics") - print("โ€ข Voting simulations on different bills") - print("โ€ข Committee hearing scenarios") - print("โ€ข Party-based analysis and comparisons") - print("โ€ข Interactive scenarios and what-if situations") - print( - "\nYou can now use the SenatorAssembly class to create your own scenarios!" - ) - - -if __name__ == "__main__": - main() diff --git a/examples/multi_agent/simulations/simulation_vote_example.py b/examples/multi_agent/simulations/senator_assembly/simulation_vote_example.py similarity index 100% rename from examples/multi_agent/simulations/simulation_vote_example.py rename to examples/multi_agent/simulations/senator_assembly/simulation_vote_example.py diff --git a/examples/multi_agent/simulations/senator_assembly/test_concurrent_vote.py b/examples/multi_agent/simulations/senator_assembly/test_concurrent_vote.py deleted file mode 100644 index 94db3450..00000000 --- a/examples/multi_agent/simulations/senator_assembly/test_concurrent_vote.py +++ /dev/null @@ -1,135 +0,0 @@ -#!/usr/bin/env python3 -""" -Test script for the new concurrent voting functionality in the Senate simulation. -""" - -from swarms.sims.senator_assembly import SenatorAssembly - - -def test_concurrent_voting(): - """ - Test the new concurrent voting functionality. - """ - print("๐Ÿ›๏ธ Testing Concurrent Senate Voting...") - - # Create the simulation - senate = SenatorAssembly() - - print("\n๐Ÿ“Š Senate Composition:") - composition = senate.get_senate_composition() - print(f" Total Senators: {composition['total_senators']}") - print(f" Party Breakdown: {composition['party_breakdown']}") - - # Test concurrent voting on a bill - bill_description = "A comprehensive infrastructure bill including roads, bridges, broadband expansion, and clean energy projects with a total cost of $1.2 trillion" - - print("\n๐Ÿ—ณ๏ธ Running Concurrent Vote on Infrastructure Bill") - print(f" Bill: {bill_description[:100]}...") - - # Run the concurrent vote with batch size of 10 - vote_results = senate.simulate_vote_concurrent( - bill_description=bill_description, - batch_size=10, # Process 10 senators concurrently in each batch - ) - - # Display results - print("\n๐Ÿ“Š Final Vote Results:") - print(f" Total Votes: {vote_results['results']['total_votes']}") - print(f" YEA: {vote_results['results']['yea']}") - print(f" NAY: {vote_results['results']['nay']}") - print(f" PRESENT: {vote_results['results']['present']}") - print(f" OUTCOME: {vote_results['results']['outcome']}") - - print("\n๐Ÿ“ˆ Party Breakdown:") - for party, votes in vote_results["party_breakdown"].items(): - total_party_votes = sum(votes.values()) - if total_party_votes > 0: - print( - f" {party}: YEA={votes['yea']}, NAY={votes['nay']}, PRESENT={votes['present']}" - ) - - print("\n๐Ÿ“‹ Sample Individual Votes (first 10):") - for i, (senator, vote) in enumerate( - vote_results["votes"].items() - ): - if i >= 10: # Only show first 10 - break - party = senate._get_senator_party(senator) - print(f" {senator} ({party}): {vote}") - - if len(vote_results["votes"]) > 10: - print( - f" ... and {len(vote_results['votes']) - 10} more votes" - ) - - print("\nโšก Performance Info:") - print(f" Batch Size: {vote_results['batch_size']}") - print(f" Total Batches: {vote_results['total_batches']}") - - return vote_results - - -def test_concurrent_voting_with_subset(): - """ - Test concurrent voting with a subset of senators. - """ - print("\n" + "=" * 60) - print("๐Ÿ›๏ธ Testing Concurrent Voting with Subset of Senators...") - - # Create the simulation - senate = SenatorAssembly() - - # Select a subset of senators for testing - test_senators = [ - "Katie Britt", - "Mark Kelly", - "Lisa Murkowski", - "Alex Padilla", - "Tom Cotton", - "Kyrsten Sinema", - "John Barrasso", - "Tammy Duckworth", - "Ted Cruz", - "Amy Klobuchar", - ] - - bill_description = ( - "A bill to increase the federal minimum wage to $15 per hour" - ) - - print("\n๐Ÿ—ณ๏ธ Running Concurrent Vote on Minimum Wage Bill") - print(f" Bill: {bill_description}") - print(f" Participants: {len(test_senators)} senators") - - # Run the concurrent vote - vote_results = senate.simulate_vote_concurrent( - bill_description=bill_description, - participants=test_senators, - batch_size=5, # Smaller batch size for testing - ) - - # Display results - print("\n๐Ÿ“Š Vote Results:") - print(f" YEA: {vote_results['results']['yea']}") - print(f" NAY: {vote_results['results']['nay']}") - print(f" PRESENT: {vote_results['results']['present']}") - print(f" OUTCOME: {vote_results['results']['outcome']}") - - print("\n๐Ÿ“‹ All Individual Votes:") - for senator, vote in vote_results["votes"].items(): - party = senate._get_senator_party(senator) - print(f" {senator} ({party}): {vote}") - - return vote_results - - -if __name__ == "__main__": - # Test full senate concurrent voting - full_results = test_concurrent_voting() - - # Test subset concurrent voting - subset_results = test_concurrent_voting_with_subset() - - print("\nโœ… Concurrent voting tests completed successfully!") - print(f" Full Senate: {full_results['results']['outcome']}") - print(f" Subset: {subset_results['results']['outcome']}") diff --git a/examples/multi_agent/swarm_router/heavy_swarm_router_example.py b/examples/multi_agent/swarm_router/heavy_swarm_router_example.py new file mode 100644 index 00000000..e8349267 --- /dev/null +++ b/examples/multi_agent/swarm_router/heavy_swarm_router_example.py @@ -0,0 +1,13 @@ +from swarms import SwarmRouter + +router = SwarmRouter( + name="HeavySwarmRouter", + description="A router that can route messages to the appropriate swarm", + max_loops=1, + swarm_type="HeavySwarm", + heavy_swarm_loops_per_agent=1, + heavy_swarm_question_agent_model_name="gpt-4o", + heavy_swarm_worker_model_name="gpt-4o", +) + +router.run("What are the best ETFs for the american energy markets?") diff --git a/heavy_swarm_example.py b/heavy_swarm_example.py index 081a9c76..e7e90e5a 100644 --- a/heavy_swarm_example.py +++ b/heavy_swarm_example.py @@ -1,6 +1,4 @@ -# task -> research -> synethsis or debate or voting -> output - -from swarms.structs.heavy_swarm import HeavySwarm +from swarms import HeavySwarm from swarms_tools import exa_search swarm = HeavySwarm( @@ -24,4 +22,3 @@ prompt = ( out = swarm.run(prompt) print(out) - diff --git a/swarms/structs/heavy_swarm.py b/swarms/structs/heavy_swarm.py index 539d84f8..2edb5078 100644 --- a/swarms/structs/heavy_swarm.py +++ b/swarms/structs/heavy_swarm.py @@ -485,6 +485,7 @@ class HeavySwarm: output_type: str = "dict-all-except-first", worker_tools: tool_type = None, random_loops_per_agent: bool = False, + max_loops: int = 1, ): """ Initialize the HeavySwarm with configuration parameters. @@ -534,6 +535,7 @@ class HeavySwarm: self.output_type = output_type self.worker_tools = worker_tools self.random_loops_per_agent = random_loops_per_agent + self.max_loops = max_loops self.conversation = Conversation() self.console = Console() diff --git a/swarms/structs/swarm_router.py b/swarms/structs/swarm_router.py index f53a888f..6a74c524 100644 --- a/swarms/structs/swarm_router.py +++ b/swarms/structs/swarm_router.py @@ -193,10 +193,13 @@ class SwarmRouter: speaker_function: str = None, heavy_swarm_loops_per_agent: int = 1, heavy_swarm_question_agent_model_name: str = "gpt-4.1", - heavy_swarm_worker_model_name: str = "claude-3-5-sonnet-20240620", + heavy_swarm_worker_model_name: str = "gpt-4.1", + heavy_swarm_swarm_show_output: bool = True, telemetry_enabled: bool = False, council_judge_model_name: str = "gpt-4o-mini", # Add missing model_name attribute verbose: bool = False, + worker_tools: List[Callable] = None, + aggregation_strategy: str = "synthesis", *args, **kwargs, ): @@ -234,6 +237,11 @@ class SwarmRouter: self.telemetry_enabled = telemetry_enabled self.council_judge_model_name = council_judge_model_name # Add missing model_name attribute self.verbose = verbose + self.worker_tools = worker_tools + self.aggregation_strategy = aggregation_strategy + self.heavy_swarm_swarm_show_output = ( + heavy_swarm_swarm_show_output + ) # Initialize swarm factory for O(1) lookup performance self._swarm_factory = self._initialize_swarm_factory() @@ -264,7 +272,10 @@ class SwarmRouter: "SwarmRouter: Swarm type cannot be 'none'. Check the docs for all the swarm types available. https://docs.swarms.world/en/latest/swarms/structs/swarm_router/" ) - if self.agents is None: + if ( + self.swarm_type != "HeavySwarm" + and self.agents is None + ): raise SwarmRouterConfigError( "SwarmRouter: No agents provided for the swarm. Check the docs to learn of required parameters. https://docs.swarms.world/en/latest/swarms/structs/agent/" ) @@ -392,12 +403,14 @@ class SwarmRouter: return HeavySwarm( name=self.name, description=self.description, - agents=self.agents, - max_loops=self.max_loops, output_type=self.output_type, loops_per_agent=self.heavy_swarm_loops_per_agent, question_agent_model_name=self.heavy_swarm_question_agent_model_name, worker_model_name=self.heavy_swarm_worker_model_name, + agent_prints_on=self.heavy_swarm_swarm_show_output, + worker_tools=self.worker_tools, + aggregation_strategy=self.aggregation_strategy, + show_dashboard=False, ) def _create_agent_rearrange(self, *args, **kwargs): diff --git a/swarms/utils/image_generator.py b/swarms/utils/image_generator.py new file mode 100644 index 00000000..1fffdb30 --- /dev/null +++ b/swarms/utils/image_generator.py @@ -0,0 +1,54 @@ +from typing import Any +from litellm import image_generation + + +class ImageGenerator: + def __init__( + self, + model: str | None = None, + n: int | None = 2, + quality: Any = None, + response_format: str | None = None, + size: str | None = 10, + style: str | None = None, + user: str | None = None, + input_fidelity: str | None = None, + timeout: int = 600, + output_path_folder: str | None = "images", + api_key: str | None = None, + api_base: str | None = None, + ): + self.model = model + self.n = n + self.quality = quality + self.response_format = response_format + self.size = size + self.style = style + self.user = user + self.input_fidelity = input_fidelity + self.timeout = timeout + self.output_path_folder = output_path_folder + self.api_key = api_key + self.api_base = api_base + + def run(self, task: str = None): + + return image_generation( + prompt=task, + model=self.model, + n=self.n, + quality=self.quality, + response_format=self.response_format, + size=self.size, + style=self.style, + user=self.user, + input_fidelity=self.input_fidelity, + timeout=self.timeout, + ) + + +# if __name__ == "__main__": +# image_generator = ImageGenerator() +# print(image_generator.run(task="A beautiful sunset over a calm ocean")) + +# print(model_list)