From 567d238fb0b647d8ebd6d156d2ba7453fd7d0ead Mon Sep 17 00:00:00 2001 From: Kye Gomez Date: Sat, 20 Sep 2025 22:13:26 -0700 Subject: [PATCH] [MAJORITYVOTING][DOCS][Improve Majority Voting docs] --- docs/swarms/structs/majorityvoting.md | 608 ++++++++++++++++-- .../heavy_swarm_example.py | 0 .../workshops/workshop_sep_20/jarvis_agent.py | 3 +- ...g_example.py => majority_voting_example.py | 4 +- scripts/setup.sh | 65 +- scripts/test_python_detection.sh | 75 --- swarms/structs/majority_voting.py | 107 ++- 7 files changed, 703 insertions(+), 159 deletions(-) rename examples/multi_agent/{ => heavy_swarm_examples}/heavy_swarm_example.py (100%) rename examples/workshops/workshop_sep_20/majority_voting_example.py => majority_voting_example.py (97%) delete mode 100644 scripts/test_python_detection.sh diff --git a/docs/swarms/structs/majorityvoting.md b/docs/swarms/structs/majorityvoting.md index 19a00385..c51067c5 100644 --- a/docs/swarms/structs/majorityvoting.md +++ b/docs/swarms/structs/majorityvoting.md @@ -1,37 +1,44 @@ # MajorityVoting Module Documentation -The `MajorityVoting` module provides a mechanism for performing majority voting among a group of agents. Majority voting is a decision rule that selects the option which has the majority of votes. This is particularly useful in systems where multiple agents provide responses to a query, and the most common response needs to be identified as the final output. +The `MajorityVoting` module provides a sophisticated multi-loop consensus building system for agents. Unlike simple majority voting, this system enables iterative consensus building where agents can refine their responses across multiple loops, with each subsequent loop considering the previous consensus. This approach leads to more robust and well-reasoned final decisions by leveraging the collective intelligence of multiple specialized agents. ## Architecture ```mermaid graph TD - A[MajorityVoting System] --> B[Initialize Agents] + A[MajorityVoting System] --> B[Initialize Agents & Consensus Agent] B --> C[Process Task] C --> D{Execution Mode} D --> E[Single Task] D --> F[Batch Tasks] D --> G[Concurrent Tasks] - E --> H[Run Agents] + E --> H[Multi-Loop Execution] F --> H G --> H - H --> I[Collect Responses] - I --> J[Consensus Analysis] - J --> K{Consensus Agent?} - K -->|Yes| L[Use Consensus Agent] - K -->|No| M[Use Last Agent] - L --> N[Final Output] - M --> N + H --> I[Run All Agents Concurrently] + I --> J[Collect Agent Responses] + J --> K[Run Consensus Agent] + K --> L[Add to Conversation History] + L --> M{More Loops?} + M -->|Yes| I + M -->|No| N[Format Final Output] N --> O[Return Result] ``` ### Key Concepts -- **Majority Voting**: A method to determine the most common response from a set of answers. -- **Agents**: Entities (e.g., models, algorithms) that provide responses to tasks or queries. -- **Consensus Agent**: An optional agent that analyzes the responses from all agents to determine the final consensus. -- **Conversation History**: A record of all agent interactions and responses during the voting process. -- **Output Types**: Support for different output formats (string, dictionary, list). + +- **Multi-Loop Consensus Building**: An iterative process where agents can refine their responses across multiple loops, with each loop building upon the previous consensus. + +- **Agents**: Specialized entities (e.g., models, algorithms) that provide expert responses to tasks or queries. + +- **Consensus Agent**: An automatically created agent that analyzes and synthesizes responses from all agents to determine the final consensus. + +- **Conversation History**: A comprehensive record of all agent interactions, responses, and consensus building across all loops. + +- **Output Types**: Support for different output formats (string, dictionary, list) with flexible formatting options. + +- **Concurrent Execution**: Agents run simultaneously for improved performance and efficiency. ## Class Definition: `MajorityVoting` @@ -41,13 +48,17 @@ class MajorityVoting: self, id: str = swarm_id(), name: str = "MajorityVoting", - description: str = "A majority voting system for agents", + description: str = "A multi-loop majority voting system for agents", agents: List[Agent] = None, - consensus_agent: Optional[Agent] = None, autosave: bool = False, verbose: bool = False, max_loops: int = 1, output_type: OutputType = "dict", + consensus_agent_prompt: str = CONSENSUS_AGENT_PROMPT, + consensus_agent_name: str = "Consensus-Agent", + consensus_agent_description: str = "An agent that uses consensus to generate a final answer.", + consensus_agent_model_name: str = "gpt-4o", + additional_consensus_agent_kwargs: dict = {}, *args, **kwargs, ): @@ -59,13 +70,17 @@ class MajorityVoting: |------------------|-------------------|---------------|-----------------------------------------------------------------------------| | `id` | `str` | `swarm_id()` | Unique identifier for the majority voting system. | | `name` | `str` | `"MajorityVoting"` | Name of the majority voting system. | -| `description` | `str` | `"A majority voting system for agents"` | Description of the system. | +| `description` | `str` | `"A multi-loop majority voting system for agents"` | Description of the system. | | `agents` | `List[Agent]` | `None` | A list of agents to be used in the majority voting system. Required. | -| `consensus_agent`| `Optional[Agent]` | `None` | Optional agent for analyzing consensus among responses. If None, uses last agent. | | `autosave` | `bool` | `False` | Whether to autosave conversations. | | `verbose` | `bool` | `False` | Whether to enable verbose logging. | -| `max_loops` | `int` | `1` | Maximum number of voting loops. | +| `max_loops` | `int` | `1` | Maximum number of consensus building loops. | | `output_type` | `OutputType` | `"dict"` | Output format: "str", "dict", "list", or other. | +| `consensus_agent_prompt` | `str` | `CONSENSUS_AGENT_PROMPT` | System prompt for the consensus agent. | +| `consensus_agent_name` | `str` | `"Consensus-Agent"` | Name for the automatically created consensus agent. | +| `consensus_agent_description` | `str` | `"An agent that uses consensus to generate a final answer."` | Description for the consensus agent. | +| `consensus_agent_model_name` | `str` | `"gpt-4o"` | Model name for the consensus agent. | +| `additional_consensus_agent_kwargs` | `dict` | `{}` | Additional keyword arguments passed to the consensus agent. | | `*args` | `Any` | - | Variable length argument list passed to Conversation. | | `**kwargs` | `Any` | - | Arbitrary keyword arguments passed to Conversation. | @@ -73,20 +88,40 @@ class MajorityVoting: #### `run(task: str, *args, **kwargs) -> Any` -Runs the majority voting system for a single task and returns the consensus result. +Runs the multi-loop majority voting system for a single task and returns the consensus result. **Parameters:** + - `task` (`str`): The task to be performed by the agents + - `*args`: Variable length argument list passed to agents + - `**kwargs`: Arbitrary keyword arguments passed to agents **Returns:** + - `Any`: The consensus result in the specified output format (string, dict, or list) +**Process:** + +1. Adds the task to the conversation history + +2. For each loop (up to `max_loops`): + - Runs all agents concurrently on the current conversation + + - Collects agent responses and adds them to conversation history + + - Runs the consensus agent to analyze and synthesize responses + + - Adds consensus output to conversation history + +3. Returns the formatted final result + **Raises:** + - `ValueError`: If agents list is empty #### `batch_run(tasks: List[str], *args, **kwargs) -> List[Any]` @@ -95,12 +130,16 @@ Runs the majority voting system for multiple tasks in sequence. **Parameters:** + - `tasks` (`List[str]`): List of tasks to be performed by the agents + - `*args`: Variable length argument list passed to each run + - `**kwargs`: Arbitrary keyword arguments passed to each run **Returns:** + - `List[Any]`: List of consensus results for each task #### `run_concurrently(tasks: List[str], *args, **kwargs) -> List[Any]` @@ -109,19 +148,516 @@ Runs the majority voting system for multiple tasks concurrently using thread poo **Parameters:** + - `tasks` (`List[str]`): List of tasks to be performed by the agents + - `*args`: Variable length argument list passed to each run + - `**kwargs`: Arbitrary keyword arguments passed to each run **Returns:** + - `List[Any]`: List of consensus results for each task, in completion order **Note:** Uses `os.cpu_count()` workers for optimal performance. +## API Reference + +### Core Methods + +#### `run(task: str, *args, **kwargs) -> Any` + +Executes the multi-loop majority voting system for a single task and returns the consensus result. + +**Signature:** + +```python +def run(self, task: str, *args, **kwargs) -> Any +``` + +**Parameters:** + + +- `task` (`str`): The task or question to be analyzed by the agent panel + + +- `*args` (`Any`): Variable length argument list passed to individual agents + + +- `**kwargs` (`Any`): Arbitrary keyword arguments passed to individual agents + +**Returns:** + +- `Any`: The consensus result formatted according to the specified `output_type` + +**Process Flow:** +1. **Task Initialization**: Adds the input task to the conversation history + +2. **Multi-Loop Execution**: For each loop (up to `max_loops`): + - **Concurrent Agent Execution**: Runs all agents simultaneously on the current conversation state + + - **Response Collection**: Gathers individual agent responses + + - **History Update**: Adds agent responses to conversation history + + - **Consensus Analysis**: Executes the consensus agent to analyze and synthesize responses + + - **Consensus Integration**: Adds consensus output to conversation history + +3. **Result Formatting**: Returns the final result in the specified output format + +**Example:** +```python +from swarms import Agent, MajorityVoting + +# Create specialized agents +agents = [ + Agent(agent_name="Analyst-1", system_prompt="You are a market analyst..."), + Agent(agent_name="Analyst-2", system_prompt="You are a risk specialist..."), + Agent(agent_name="Analyst-3", system_prompt="You are a portfolio manager...") +] + +# Initialize majority voting system +swarm = MajorityVoting( + name="Investment-Swarm", + agents=agents, + max_loops=2, + output_type="dict" +) + +# Execute single task +result = swarm.run( + "Analyze the current market conditions and provide investment recommendations for a $50k portfolio" +) + +print(f"Consensus Result: {result}") +``` + +**Raises:** + +- `ValueError`: If the agents list is empty or None + +--- + +#### `batch_run(tasks: List[str], *args, **kwargs) -> List[Any]` + +Executes the majority voting system for multiple tasks sequentially, processing each task through the complete multi-loop consensus building process. + +**Signature:** +```python +def batch_run(self, tasks: List[str], *args, **kwargs) -> List[Any] +``` + +**Parameters:** + +- `tasks` (`List[str]`): List of tasks or questions to be processed + +- `*args` (`Any`): Variable length argument list passed to each task execution + +- `**kwargs` (`Any`): Arbitrary keyword arguments passed to each task execution + +**Returns:** + +- `List[Any]`: List of consensus results, one for each input task + +**Process Flow:** + +1. **Sequential Processing**: Processes each task in the input list one by one +2. **Independent Execution**: Each task runs through the complete multi-loop consensus process +3. **Result Collection**: Collects and returns all results in the same order as input tasks + +**Example:** +```python +# Define multiple analysis tasks +analysis_tasks = [ + "Analyze the technology sector for growth opportunities", + "Evaluate the healthcare sector for defensive investments", + "Assess the energy sector for value opportunities", + "Review the financial sector for dividend plays" +] + +# Execute batch processing +results = swarm.batch_run(analysis_tasks) + +# Process results +for i, (task, result) in enumerate(zip(analysis_tasks, results)): + print(f"Task {i+1}: {task}") + print(f"Result: {result}") + print("-" * 50) +``` + +**Performance Considerations:** + +- Tasks are processed sequentially, not concurrently + +- Each task maintains its own conversation history + +- Memory usage scales with the number of tasks and conversation length + +--- + +#### `run_concurrently(tasks: List[str], *args, **kwargs) -> List[Any]` + +Executes the majority voting system for multiple tasks concurrently using thread pooling for improved performance. + +**Signature:** +```python +def run_concurrently(self, tasks: List[str], *args, **kwargs) -> List[Any] +``` + +**Parameters:** + +- `tasks` (`List[str]`): List of tasks or questions to be processed + +- `*args` (`Any`): Variable length argument list passed to each task execution + +- `**kwargs` (`Any`): Arbitrary keyword arguments passed to each task execution + +**Returns:** + +- `List[Any]`: List of consensus results in completion order (not input order) + +**Process Flow:** + +1. **Thread Pool Creation**: Creates a thread pool with `os.cpu_count()` workers + +2. **Concurrent Submission**: Submits all tasks to the thread pool simultaneously + +3. **Parallel Execution**: Each task runs independently in its own thread + +4. **Result Collection**: Collects results as they complete (not in input order) + +**Example:** +```python +# Define multiple research questions +research_questions = [ + "What are the environmental impacts of electric vehicles?", + "How does AI affect job markets?", + "What are the economic implications of renewable energy?", + "How will blockchain technology transform finance?" +] + +# Execute concurrent processing +concurrent_results = swarm.run_concurrently(research_questions) + +# Results are in completion order, not input order +print(f"Processed {len(concurrent_results)} research questions concurrently") +for i, result in enumerate(concurrent_results): + print(f"Result {i+1}: {str(result)[:200]}...") +``` + +**Performance Benefits:** + +- **Parallel Execution**: Multiple tasks run simultaneously + +- **Optimal Resource Usage**: Uses all available CPU cores + +- **Reduced Total Time**: Significantly faster than sequential processing for multiple tasks + +**Important Notes:** + +- Results are returned in completion order, not input order + +- Each task maintains independent conversation history + +- Thread safety is handled automatically by the implementation + +--- + +### Configuration Methods + +#### `reliability_check() -> None` + +Performs validation checks on the majority voting system configuration. + +**Signature:** +```python +def reliability_check(self) -> None +``` + +**Process:** +1. **Agent Validation**: Ensures the agents list is not empty +2. **System Logging**: Logs initialization information with agent details +3. **Error Handling**: Raises `ValueError` if validation fails + +**Raises:** + +- `ValueError`: If agents list is empty or None + +--- + +### Properties + +| Property | Type | Description | +|----------|------|-------------| +| `id` | `str` | Unique identifier for the majority voting system | +| `name` | `str` | Human-readable name of the system | +| `description` | `str` | Detailed description of the system's purpose | +| `agents` | `List[Agent]` | List of participating agents | +| `max_loops` | `int` | Maximum number of consensus building loops | +| `output_type` | `OutputType` | Format for returned results | +| `conversation` | `Conversation` | Conversation history management object | +| `consensus_agent` | `Agent` | Automatically created consensus analysis agent | + +## Consensus Agent + +The MajorityVoting system automatically creates a specialized consensus agent that analyzes and synthesizes responses from all participating agents. This consensus agent uses a sophisticated prompt that: + +1. **Comprehensively evaluates** each agent's response across multiple dimensions: + - Accuracy and correctness + - Depth of analysis and insight + - Relevance to the original task + - Clarity, structure, and communication quality + - Unique perspectives or innovative ideas + +2. **Performs comparative analysis** by: + - Identifying overlapping themes and points of agreement + - Highlighting divergent viewpoints or conflicting recommendations + - Assessing strengths and weaknesses of each approach + +3. **Builds consensus** by: + - Identifying the most effective response(s) with clear justification + - Synthesizing the best elements from multiple responses when appropriate + - Providing ranked recommendations with detailed rationales + +4. **Delivers actionable results** that are: + - Fair and balanced + - Evidence-based and rigorous + - Well-supported and clearly communicated + +The consensus agent can be customized through the constructor parameters: + + +- `consensus_agent_prompt`: Custom system prompt for the consensus agent + +- `consensus_agent_name`: Name for the consensus agent + +- `consensus_agent_description`: Description for the consensus agent + +- `consensus_agent_model_name`: Model to use for the consensus agent + +- `additional_consensus_agent_kwargs`: Additional configuration options + +## Usage Patterns + +### Single Task Analysis +For focused analysis on a single complex question or task: + +```python +# Simple single task execution +result = swarm.run("What are the key risks in the current market?") + +# With custom parameters +result = swarm.run( + "Analyze this investment opportunity", + temperature=0.7, + max_tokens=1000 +) +``` + +### Batch Processing +For processing multiple related tasks sequentially: + +```python +# Process multiple sectors +sectors = ["Technology", "Healthcare", "Energy", "Finance"] +tasks = [f"Analyze {sector} sector opportunities" for sector in sectors] +results = swarm.batch_run(tasks) +``` + +### Concurrent Processing +For maximum performance when processing multiple independent tasks: + +```python +# Process multiple research questions concurrently +questions = [ + "What are the environmental impacts of AI?", + "How will quantum computing affect cryptography?", + "What are the economic implications of space exploration?" +] +results = swarm.run_concurrently(questions) +``` + + ## Usage Examples -### Example 1: Investment Analysis with Consensus Agent +### Example 1: Quantitative Financial Analysis with Specialized Agents + +This example demonstrates using MajorityVoting for comprehensive financial analysis with three specialized quantitative agents, each focusing on different aspects of investment analysis. + +```python +from swarms import Agent +from swarms.structs.majority_voting import MajorityVoting + +# Technical Analysis Quant Agent System Prompt +TECHNICAL_ANALYSIS_PROMPT = """ +You are a Quantitative Technical Analysis Specialist with deep expertise in market chart patterns, technical indicators, and algorithmic trading signals. Your primary focus is on price action, volume analysis, and statistical patterns in financial markets. + +## Core Expertise Areas: +1. **Chart Pattern Recognition**: Identify and analyze classic patterns (head & shoulders, triangles, flags, pennants, double tops/bottoms, etc.) +2. **Technical Indicators**: Expert knowledge of RSI, MACD, Bollinger Bands, Moving Averages, Stochastic, Williams %R, ADX, and custom indicators +3. **Volume Analysis**: Volume-price relationships, accumulation/distribution, on-balance volume, volume-weighted average price (VWAP) +4. **Support & Resistance**: Dynamic and static levels, trend lines, Fibonacci retracements and extensions +5. **Market Structure**: Higher highs/lows, market cycles, trend identification, and momentum analysis +6. **Quantitative Methods**: Statistical analysis, backtesting, signal generation, and risk-reward calculations + +## Analysis Framework: + +- Always provide specific price levels, timeframes, and probability assessments + +- Include risk management parameters (stop losses, take profits, position sizing) + +- Explain the statistical significance and historical performance of patterns + +- Consider multiple timeframes for comprehensive analysis + +- Factor in market volatility and current market conditions + +## Output Requirements: + +- Clear buy/sell/hold recommendations with confidence levels + +- Specific entry, stop-loss, and target price levels + +- Risk-reward ratios and probability assessments + +- Time horizon for the analysis + +- Key levels to watch for confirmation or invalidation + +Remember: Focus on objective, data-driven analysis based on price action and technical indicators rather than fundamental factors. +""" + +# Fundamental Analysis Quant Agent System Prompt +FUNDAMENTAL_ANALYSIS_PROMPT = """ +You are a Quantitative Fundamental Analysis Specialist with expertise in financial statement analysis, valuation models, and company performance metrics. Your focus is on intrinsic value, financial health, and long-term investment potential. + +## Core Expertise Areas: +1. **Financial Statement Analysis**: Deep dive into income statements, balance sheets, and cash flow statements +2. **Valuation Models**: DCF analysis, P/E ratios, P/B ratios, PEG ratios, EV/EBITDA, and other valuation metrics +3. **Financial Ratios**: Liquidity, profitability, efficiency, leverage, and market ratios +4. **Growth Analysis**: Revenue growth, earnings growth, margin analysis, and sustainable growth rates +5. **Industry Analysis**: Competitive positioning, market share, industry trends, and comparative analysis +6. **Economic Indicators**: Interest rates, inflation, GDP growth, and their impact on company performance + +## Analysis Framework: + +- Calculate and interpret key financial ratios and metrics + +- Assess company's competitive moat and business model sustainability + +- Evaluate management quality and corporate governance + +- Consider macroeconomic factors and industry trends + +- Provide fair value estimates and margin of safety calculations + +## Output Requirements: + +- Intrinsic value estimates with confidence intervals + +- Key financial metrics and their interpretation + +- Strengths, weaknesses, opportunities, and threats (SWOT) analysis + +- Investment thesis with supporting evidence + +- Risk factors and potential catalysts + +- Long-term growth prospects and sustainability + +Remember: Focus on quantitative metrics and fundamental factors that drive long-term value creation rather than short-term price movements. +""" + +# Risk Management Quant Agent System Prompt +RISK_MANAGEMENT_PROMPT = """ +You are a Quantitative Risk Management Specialist with expertise in portfolio optimization, risk metrics, and hedging strategies. Your focus is on risk-adjusted returns, diversification, and capital preservation. + +## Core Expertise Areas: +1. **Portfolio Theory**: Modern Portfolio Theory, efficient frontier, and optimal asset allocation +2. **Risk Metrics**: VaR (Value at Risk), CVaR, Sharpe ratio, Sortino ratio, Maximum Drawdown, Beta, and correlation analysis +3. **Diversification**: Asset correlation analysis, sector allocation, geographic diversification, and alternative investments +4. **Hedging Strategies**: Options strategies, futures, swaps, and other derivative instruments +5. **Stress Testing**: Scenario analysis, Monte Carlo simulations, and tail risk assessment +6. **Regulatory Compliance**: Basel III, Solvency II, and other regulatory risk requirements + +## Analysis Framework: + +- Calculate comprehensive risk metrics and performance ratios + +- Assess portfolio concentration and diversification benefits + +- Identify potential risk factors and stress scenarios + +- Recommend hedging strategies and risk mitigation techniques + +- Optimize portfolio allocation for risk-adjusted returns + +- Consider liquidity risk, credit risk, and operational risk factors + +## Output Requirements: + +- Risk-adjusted performance metrics and rankings + +- Portfolio optimization recommendations + +- Risk factor analysis and stress test results + +- Hedging strategy recommendations with cost-benefit analysis + +- Diversification analysis and concentration risk assessment + +- Capital allocation recommendations based on risk tolerance + +Remember: Focus on quantitative risk assessment and portfolio optimization techniques that maximize risk-adjusted returns while maintaining appropriate risk levels. +""" + +# Initialize the three specialized quant agents +technical_agent = Agent( + agent_name="Technical-Analysis-Quant", + agent_description="Specialized in technical analysis, chart patterns, and trading signals", + system_prompt=TECHNICAL_ANALYSIS_PROMPT, + max_loops=1, + model_name="gpt-4o", +) + +fundamental_agent = Agent( + agent_name="Fundamental-Analysis-Quant", + agent_description="Specialized in financial statement analysis and company valuation", + system_prompt=FUNDAMENTAL_ANALYSIS_PROMPT, + max_loops=1, + model_name="gpt-4o", +) + +risk_agent = Agent( + agent_name="Risk-Management-Quant", + agent_description="Specialized in portfolio optimization and risk management strategies", + system_prompt=RISK_MANAGEMENT_PROMPT, + max_loops=1, + model_name="gpt-4o", +) + +# Create the majority voting swarm with the three specialized quant agents +swarm = MajorityVoting( + name="Quant-Analysis-Swarm", + description="Analysis of the current market conditions and provide investment recommendations for a $40k portfolio.", + agents=[technical_agent, fundamental_agent, risk_agent], +) + +# Run the quant analysis swarm +result = swarm.run( + "Analyze the current market conditions and provide investment recommendations for a $40k portfolio. " + "Focus on AI and technology sectors with emphasis on risk management and diversification. " + "Include specific entry points, risk levels, and expected returns for each recommendation." +) + +print("Quant Analysis Results:") +print("=" * 50) +print(result) +``` + +### Example 2: Investment Analysis with Consensus Agent This example demonstrates using MajorityVoting for financial analysis with specialized agents and a dedicated consensus agent. @@ -153,21 +689,11 @@ agents = [ ) ] -# Dedicated consensus agent for final analysis -consensus_agent = Agent( - agent_name="Investment-Consensus-Agent", - agent_description="Investment consensus analyzer", - system_prompt="You are an expert at synthesizing investment advice from multiple perspectives into a coherent recommendation.", - max_loops=1, - model_name="gpt-4o" -) - -# Create majority voting system +# Create majority voting system (consensus agent is automatically created) investment_system = MajorityVoting( name="Investment-Analysis-System", description="Multi-agent investment analysis with consensus evaluation", agents=agents, - consensus_agent=consensus_agent, verbose=True, output_type="dict" ) @@ -225,7 +751,7 @@ content_agents = [ ) ] -# Create majority voting system without dedicated consensus agent +# Create majority voting system (consensus agent is automatically created) content_system = MajorityVoting( name="Content-Creation-System", description="Multi-style content creation with majority voting", @@ -297,21 +823,11 @@ research_agents = [ ) ] -# Consensus agent for synthesizing research findings -research_consensus = Agent( - agent_name="Research-Synthesis-Agent", - agent_description="Research synthesis specialist", - system_prompt="You are an expert at synthesizing diverse research perspectives into comprehensive, well-supported conclusions.", - max_loops=1, - model_name="gpt-4o" -) - -# Create majority voting system for research +# Create majority voting system for research (consensus agent is automatically created) research_system = MajorityVoting( name="Research-Analysis-System", description="Concurrent multi-perspective research analysis", agents=research_agents, - consensus_agent=research_consensus, verbose=True, output_type="list" ) @@ -337,6 +853,4 @@ for i, result in enumerate(concurrent_results, 1): print(f"Sample output: {str(result)[:300]}...") else: print(f"Result: {result}") - ``` - diff --git a/examples/multi_agent/heavy_swarm_example.py b/examples/multi_agent/heavy_swarm_examples/heavy_swarm_example.py similarity index 100% rename from examples/multi_agent/heavy_swarm_example.py rename to examples/multi_agent/heavy_swarm_examples/heavy_swarm_example.py diff --git a/examples/workshops/workshop_sep_20/jarvis_agent.py b/examples/workshops/workshop_sep_20/jarvis_agent.py index 315c2606..ad4d1ba7 100644 --- a/examples/workshops/workshop_sep_20/jarvis_agent.py +++ b/examples/workshops/workshop_sep_20/jarvis_agent.py @@ -10,7 +10,7 @@ SYSTEM_PROMPT = ( agent = Agent( agent_name="Tactical-Strategist-Agent", agent_description="Agent specialized in tactical strategy, scenario analysis, and actionable recommendations for complex situations.", - model_name="gemini/gemini-2.5-flash-image-preview", #"gemini/gemini-2.5-flash-image-preview", + model_name="gemini/gemini-2.5-flash-image-preview", # "gemini/gemini-2.5-flash-image-preview", dynamic_temperature_enabled=True, max_loops=1, dynamic_context_window=True, @@ -23,4 +23,3 @@ out = agent.run( task=f"{SYSTEM_PROMPT} \n\n Annotate all the tallest buildings in the image", img="hk.jpg", ) - diff --git a/examples/workshops/workshop_sep_20/majority_voting_example.py b/majority_voting_example.py similarity index 97% rename from examples/workshops/workshop_sep_20/majority_voting_example.py rename to majority_voting_example.py index 126c473d..9989a557 100644 --- a/examples/workshops/workshop_sep_20/majority_voting_example.py +++ b/majority_voting_example.py @@ -118,8 +118,8 @@ risk_agent = Agent( # Create the majority voting swarm with the three specialized quant agents swarm = MajorityVoting( - name = "Quant-Analysis-Swarm", - description = "Analysis of the current market conditions and provide investment recommendations for a $40k portfolio.", + name="Quant-Analysis-Swarm", + description="Analysis of the current market conditions and provide investment recommendations for a $40k portfolio.", agents=[technical_agent, fundamental_agent, risk_agent], ) diff --git a/scripts/setup.sh b/scripts/setup.sh index 2ae94254..b40061df 100644 --- a/scripts/setup.sh +++ b/scripts/setup.sh @@ -38,21 +38,21 @@ print_status "Starting Swarms development environment setup..." # Check Python version print_status "Checking Python version..." -PYTHON_CMD="" -# Try to find Python command (check both python and python3) -if command_exists python3; then - PYTHON_CMD="python3" -elif command_exists python; then - # Check if it's Python 3.x +# Try to find Python executable (check both python and python3) +PYTHON_CMD="" +if command_exists python; then + # Check if python is version 3.x if python -c 'import sys; exit(0 if sys.version_info[0] == 3 else 1)' 2>/dev/null; then PYTHON_CMD="python" fi +elif command_exists python3; then + PYTHON_CMD="python3" fi if [ -n "$PYTHON_CMD" ]; then PYTHON_VERSION=$($PYTHON_CMD -c 'import sys; print(".".join(map(str, sys.version_info[:2])))') - print_status "Found Python $PYTHON_VERSION using command: $PYTHON_CMD" + print_status "Found Python $PYTHON_VERSION using '$PYTHON_CMD'" # Check if Python version meets requirements (>=3.10) if $PYTHON_CMD -c 'import sys; exit(0 if sys.version_info >= (3, 10) else 1)'; then @@ -70,17 +70,58 @@ fi # Install Poetry if not present if ! command_exists poetry; then print_status "Poetry not found. Installing Poetry..." - curl -sSL https://install.python-poetry.org | $PYTHON_CMD - + + # Detect OS for Poetry installation + if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "win32" ]]; then + # Windows/GitBash specific installation + print_status "Detected Windows environment, using pip to install Poetry..." + $PYTHON_CMD -m pip install --user poetry + else + # Unix-like systems + curl -sSL https://install.python-poetry.org | $PYTHON_CMD - + fi # Add Poetry to PATH for current session - export PATH="$HOME/.local/bin:$PATH" + if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "win32" ]]; then + # Windows: Add Python Scripts directory to PATH + export PATH="$HOME/AppData/Roaming/Python/Scripts:$PATH" + else + # Unix-like systems + export PATH="$HOME/.local/bin:$PATH" + fi # Check if installation was successful if command_exists poetry; then print_success "Poetry installed successfully" else - print_error "Failed to install Poetry. Please install manually from https://python-poetry.org/" - exit 1 + # Try to find poetry in common Windows locations + if [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "win32" ]]; then + POETRY_PATH="" + for path in "$HOME/AppData/Roaming/Python/Scripts/poetry" "$HOME/.local/bin/poetry" "$APPDATA/Python/Scripts/poetry"; do + if [ -f "$path" ] || [ -f "$path.exe" ]; then + POETRY_PATH="$path" + break + fi + done + + if [ -n "$POETRY_PATH" ]; then + print_status "Found Poetry at $POETRY_PATH, adding to PATH..." + export PATH="$(dirname "$POETRY_PATH"):$PATH" + if command_exists poetry; then + print_success "Poetry found and added to PATH" + else + print_error "Failed to add Poetry to PATH. Please add it manually." + exit 1 + fi + else + print_error "Failed to install Poetry. Please install manually from https://python-poetry.org/" + print_error "For Windows, you can also try: pip install poetry" + exit 1 + fi + else + print_error "Failed to install Poetry. Please install manually from https://python-poetry.org/" + exit 1 + fi fi else print_success "Poetry is already installed" @@ -91,7 +132,7 @@ fi print_status "Configuring Poetry..." poetry config virtualenvs.in-project true -# Check if the prefer-active-python option exists (available in newer Poetry versions) +# Check if the prefer-active-python config option exists before setting it if poetry config --list | grep -q "virtualenvs.prefer-active-python"; then poetry config virtualenvs.prefer-active-python true print_status "Set virtualenvs.prefer-active-python to true" diff --git a/scripts/test_python_detection.sh b/scripts/test_python_detection.sh deleted file mode 100644 index a7562f73..00000000 --- a/scripts/test_python_detection.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash - -# Test script to verify Python detection logic -# This script tests the Python detection improvements made to setup.sh - -set -e - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -BLUE='\033[0;34m' -NC='\033[0m' # No Color - -# Function to print colored output -print_status() { - echo -e "${BLUE}[INFO]${NC} $1" -} - -print_success() { - echo -e "${GREEN}[SUCCESS]${NC} $1" -} - -print_warning() { - echo -e "${YELLOW}[WARNING]${NC} $1" -} - -print_error() { - echo -e "${RED}[ERROR]${NC} $1" -} - -# Function to check if command exists -command_exists() { - command -v "$1" >/dev/null 2>&1 -} - -print_status "Testing Python detection logic..." - -# Test Python detection (same logic as in setup.sh) -PYTHON_CMD="" - -# Try to find Python command (check both python and python3) -if command_exists python3; then - PYTHON_CMD="python3" - print_status "Found python3 command" -elif command_exists python; then - # Check if it's Python 3.x - if python -c 'import sys; exit(0 if sys.version_info[0] == 3 else 1)' 2>/dev/null; then - PYTHON_CMD="python" - print_status "Found python command (Python 3.x)" - else - print_warning "Found python command but it's not Python 3.x" - fi -fi - -if [ -n "$PYTHON_CMD" ]; then - PYTHON_VERSION=$($PYTHON_CMD -c 'import sys; print(".".join(map(str, sys.version_info[:2])))') - print_status "Found Python $PYTHON_VERSION using command: $PYTHON_CMD" - - # Check if Python version meets requirements (>=3.10) - if $PYTHON_CMD -c 'import sys; exit(0 if sys.version_info >= (3, 10) else 1)'; then - print_success "Python version is compatible (>=3.10)" - else - print_error "Python 3.10 or higher is required. Current version: $PYTHON_VERSION" - exit 1 - fi -else - print_error "Python is not installed or not found." - print_error "Make sure Python is in your PATH and accessible as 'python' or 'python3'" - exit 1 -fi - -print_success "Python detection test passed!" -print_status "Detected Python command: $PYTHON_CMD" -print_status "Python version: $PYTHON_VERSION" diff --git a/swarms/structs/majority_voting.py b/swarms/structs/majority_voting.py index 083a3207..3451f27c 100644 --- a/swarms/structs/majority_voting.py +++ b/swarms/structs/majority_voting.py @@ -1,7 +1,7 @@ import concurrent.futures import os from concurrent.futures import ThreadPoolExecutor -from typing import Any, List, Optional +from typing import Any, List from swarms.structs.agent import Agent from swarms.structs.conversation import Conversation @@ -18,16 +18,69 @@ logger = initialize_logger(log_folder="majority_voting") CONSENSUS_AGENT_PROMPT = """ -Review the responses from all agents above. For each agent (referenced by their name), -provide a thorough, objective evaluation of their contribution to the task. -Compare and contrast the responses, highlighting strengths, weaknesses, and unique perspectives. -Determine which response(s) best address the task overall, and explain your reasoning clearly. -If possible, provide a ranked list or clear recommendation for the best response(s) based on the quality, -relevance, and completeness of the answers. -Be fair, detailed, and unbiased in your analysis, regardless of the topic. +You are the Consensus Agent, responsible for synthesizing and evaluating the responses from a panel of expert agents. Your task is to deliver a rigorous, insightful, and actionable consensus based on their outputs. + +**Instructions:** + +1. **Comprehensive Evaluation:** + For each agent (referenced by their name), provide a detailed, objective critique of their response. Assess the following dimensions: + - Accuracy and correctness + - Depth of analysis and insight + - Relevance to the original task or question + - Clarity, structure, and communication quality + - Unique perspectives or innovative ideas + +2. **Comparative Analysis:** + Compare and contrast the agents’ responses. Highlight: + - Overlapping themes or points of agreement + - Divergent viewpoints or conflicting recommendations + - Notable strengths and weaknesses of each approach + +3. **Consensus Building:** + - Identify which response(s) most effectively address the task, providing clear justification for your choices. + - If appropriate, synthesize the best elements from multiple responses into a unified, superior answer. + - Clearly explain your reasoning and the criteria used for your judgment. + +4. **Ranking and Recommendation:** + - Provide a ranked list of agent responses, from most to least effective, with concise rationales for each position. + - Offer a final, well-justified recommendation or summary that represents the optimal consensus. + +5. **Fairness and Rigor:** + - Remain impartial, thorough, and evidence-based in your analysis. + - Avoid bias towards any agent or perspective. + - Ensure your consensus is actionable, well-supported, and clearly communicated. + +**Output Format:** +- For each agent: [Agent Name]: [Evaluation] +- Comparative Analysis: [Summary] +- Ranked List: [1. Agent Name, 2. Agent Name, ...] +- Final Consensus/Recommendation: [Your synthesized answer or recommendation] + +Your goal is to deliver a consensus that is not only fair and balanced, but also maximizes the quality, relevance, and utility of the collective agent output. """ +def default_consensus_agent( + name: str = "Consensus-Agent", + system_prompt: str = None, + description: str = "An agent that uses consensus to generate a final answer.", + model_name: str = "gpt-4o", + *args, + **kwargs, +): + return Agent( + agent_name=name, + agent_description=description, + model_name=model_name, + max_loops=1, + system_prompt=system_prompt, + dynamic_context_window=True, + dynamic_temperature_enabled=True, + *args, + **kwargs, + ) + + class MajorityVoting: """ A multi-loop majority voting system for agents that enables iterative consensus building. @@ -51,12 +104,15 @@ class MajorityVoting: name: str = "MajorityVoting", description: str = "A multi-loop majority voting system for agents", agents: List[Agent] = None, - consensus_agent: Optional[Agent] = None, autosave: bool = False, verbose: bool = False, max_loops: int = 1, output_type: OutputType = "dict", consensus_agent_prompt: str = CONSENSUS_AGENT_PROMPT, + consensus_agent_name: str = "Consensus-Agent", + consensus_agent_description: str = "An agent that uses consensus to generate a final answer.", + consensus_agent_model_name: str = "gpt-4o", + additional_consensus_agent_kwargs: dict = {}, *args, **kwargs, ): @@ -64,7 +120,6 @@ class MajorityVoting: self.name = name self.description = description self.agents = agents - self.consensus_agent = consensus_agent self.autosave = autosave self.verbose = verbose self.max_loops = max_loops @@ -75,23 +130,35 @@ class MajorityVoting: time_enabled=False, *args, **kwargs ) - self.initialize_majority_voting() + self.consensus_agent = default_consensus_agent( + name=consensus_agent_name, + system_prompt=consensus_agent_prompt, + description=consensus_agent_description, + model_name=consensus_agent_model_name, + **additional_consensus_agent_kwargs, + ) - def initialize_majority_voting(self): + self.reliability_check() + + def reliability_check(self): if self.agents is None: raise ValueError("Agents list is empty") - # Log the agents + # Log the agents in a more formatted, readable way + agent_list = "\n".join( + [f" - {agent.agent_name}" for agent in self.agents] + ) + panel_content = ( + f"[bold]Initializing Majority Voting System[/bold]\n" + f"[bold]Number of agents:[/bold] {len(self.agents)}\n" + f"[bold]Agents:[/bold]\n{agent_list}" + ) formatter.print_panel( - f"Initializing majority voting system\nNumber of agents: {len(self.agents)}\nAgents: {', '.join(agent.agent_name for agent in self.agents)}", + panel_content, title="Majority Voting", ) - if self.consensus_agent is None: - # if no consensus agent is provided, use the last agent - self.consensus_agent = self.agents[-1] - def run(self, task: str, *args, **kwargs) -> List[Any]: """ Runs the majority voting system with multi-loop functionality and returns the majority vote. @@ -126,9 +193,7 @@ class MajorityVoting: # Now run the consensus agent consensus_output = self.consensus_agent.run( - task=( - f"History: {self.conversation.get_str()} \n\n {self.consensus_agent_prompt}" - ), + task=(f"History: {self.conversation.get_str()}"), ) self.conversation.add(