diff --git a/rearrange_test.py b/examples/multi_agent/agent_rearrange_examples/rearrange_test.py similarity index 100% rename from rearrange_test.py rename to examples/multi_agent/agent_rearrange_examples/rearrange_test.py diff --git a/heavy_swarm_example.py b/examples/multi_agent/heavy_swarm_example.py similarity index 100% rename from heavy_swarm_example.py rename to examples/multi_agent/heavy_swarm_example.py diff --git a/examples/multi_agent/hiearchical_swarm/hierarchical_swarm_comparison_demo.py b/examples/multi_agent/hiearchical_swarm/hierarchical_swarm_comparison_demo.py index d2ef65d1..4fa68631 100644 --- a/examples/multi_agent/hiearchical_swarm/hierarchical_swarm_comparison_demo.py +++ b/examples/multi_agent/hiearchical_swarm/hierarchical_swarm_comparison_demo.py @@ -1,11 +1,3 @@ -#!/usr/bin/env python3 -""" -Hierarchical Swarm Comparison Demo - -This demo compares traditional swarm execution (without streaming) -versus streaming execution to show the difference in behavior. -""" - from swarms.structs.hiearchical_swarm import HierarchicalSwarm from swarms.agents import Agent diff --git a/fallback_test.py b/examples/single_agent/utils/fallback_test.py similarity index 100% rename from fallback_test.py rename to examples/single_agent/utils/fallback_test.py diff --git a/examples/workshops/workshop_sep_20/agent_tools_dict_example.py b/examples/workshops/workshop_sep_20/agent_tools_dict_example.py new file mode 100644 index 00000000..81efec2e --- /dev/null +++ b/examples/workshops/workshop_sep_20/agent_tools_dict_example.py @@ -0,0 +1,17 @@ +from swarms import Agent + + +# Initialize the agent +agent = Agent( + agent_name="Financial-Analysis-Agent", + agent_description="Personal finance advisor agent", + max_loops=1, + output_type="final", + mcp_url="http://0.0.0.0:8000/mcp", +) + +out = agent.run( + "Use the multiply tool to multiply 3 and 4 together. Look at the tools available to you.", +) + +print(agent.short_memory.get_str()) diff --git a/examples/workshops/workshop_sep_20/batched_grid_simple_example.py b/examples/workshops/workshop_sep_20/batched_grid_simple_example.py new file mode 100644 index 00000000..6c455e73 --- /dev/null +++ b/examples/workshops/workshop_sep_20/batched_grid_simple_example.py @@ -0,0 +1,42 @@ +from swarms import Agent +from swarms.structs.batched_grid_workflow import BatchedGridWorkflow + +# Initialize the ETF-focused agent +agent = Agent( + agent_name="ETF-Research-Agent", + agent_description="Specialized agent for researching, analyzing, and recommending Exchange-Traded Funds (ETFs) across various sectors and markets.", + model_name="groq/moonshotai/kimi-k2-instruct", + dynamic_temperature_enabled=True, + max_loops=1, + dynamic_context_window=True, +) + +agent_two = Agent( + agent_name="ETF-Research-Agent-2", + agent_description="Specialized agent for researching, analyzing, and recommending Exchange-Traded Funds (ETFs) across various sectors and markets.", + model_name="groq/moonshotai/kimi-k2-instruct", + dynamic_temperature_enabled=True, + max_loops=1, + dynamic_context_window=True, +) + + +# Create workflow with default settings +workflow = BatchedGridWorkflow( + name="ETF-Research-Workflow", + description="Research and recommend ETFs across various sectors and markets.", + agents=[agent, agent_two], + max_loops=1, +) + +# Define simple tasks +tasks = [ + "What are the best GOLD ETFs?", + "What are the best american energy ETFs?", +] + +# Run the workflow +result = workflow.run(tasks) + + +print(result) diff --git a/examples/workshops/workshop_sep_20/geo_guesser_agent.py b/examples/workshops/workshop_sep_20/geo_guesser_agent.py new file mode 100644 index 00000000..93b1bff9 --- /dev/null +++ b/examples/workshops/workshop_sep_20/geo_guesser_agent.py @@ -0,0 +1,27 @@ +from swarms import Agent + + +SYSTEM_PROMPT = ( + "You are an expert in image geolocalization. Given an image, provide the most likely location it was taken. " + "Analyze visual cues such as architecture, landscape, vegetation, weather patterns, cultural elements, " + "and any other geographical indicators to determine the precise location. Provide your reasoning and " + "confidence level for your prediction." +) + +# Agent for image geolocalization +agent = Agent( + agent_name="Geo-Guesser-Agent", + agent_description="Expert agent specialized in image geolocalization, capable of identifying geographical locations from visual cues in images.", + model_name="gemini/gemini-2.5-flash-image-preview", + dynamic_temperature_enabled=True, + max_loops=1, + dynamic_context_window=True, + retry_interval=1, +) + +out = agent.run( + task=f"{SYSTEM_PROMPT}", + img="mountains.jpg", +) + +print(out) diff --git a/examples/workshops/workshop_sep_20/hk.jpg b/examples/workshops/workshop_sep_20/hk.jpg new file mode 100644 index 00000000..2e2dc405 Binary files /dev/null and b/examples/workshops/workshop_sep_20/hk.jpg differ diff --git a/examples/workshops/workshop_sep_20/jarvis_agent.py b/examples/workshops/workshop_sep_20/jarvis_agent.py new file mode 100644 index 00000000..315c2606 --- /dev/null +++ b/examples/workshops/workshop_sep_20/jarvis_agent.py @@ -0,0 +1,26 @@ +from swarms import Agent + + +SYSTEM_PROMPT = ( + "You are a location-based AR experience generator. Highlight points of interest in this image and annotate relevant information about it. " + "Generate the new image only." +) + +# Agent for AR annotation +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", + dynamic_temperature_enabled=True, + max_loops=1, + dynamic_context_window=True, + retry_interval=1, + verbose=True, +) + + +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/examples/workshops/workshop_sep_20/majority_voting_example.py new file mode 100644 index 00000000..126c473d --- /dev/null +++ b/examples/workshops/workshop_sep_20/majority_voting_example.py @@ -0,0 +1,135 @@ +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) diff --git a/examples/workshops/workshop_sep_20/miami.jpg b/examples/workshops/workshop_sep_20/miami.jpg new file mode 100644 index 00000000..8ed057a5 Binary files /dev/null and b/examples/workshops/workshop_sep_20/miami.jpg differ diff --git a/examples/workshops/workshop_sep_20/mountains.jpg b/examples/workshops/workshop_sep_20/mountains.jpg new file mode 100644 index 00000000..1846e6ac Binary files /dev/null and b/examples/workshops/workshop_sep_20/mountains.jpg differ diff --git a/examples/workshops/workshop_sep_20/same_task_example.py b/examples/workshops/workshop_sep_20/same_task_example.py new file mode 100644 index 00000000..1a6fed3b --- /dev/null +++ b/examples/workshops/workshop_sep_20/same_task_example.py @@ -0,0 +1,38 @@ +from swarms.structs.agent import Agent +from swarms.structs.multi_agent_exec import ( + run_agents_concurrently_uvloop, +) + + +def create_example_agents(num_agents: int = 3): + """ + Create example agents for demonstration. + + Args: + num_agents: Number of agents to create + + Returns: + List of Agent instances + """ + agents = [] + for i in range(num_agents): + agent = Agent( + agent_name=f"Agent_{i+1}", + system_prompt=f"You are Agent {i+1}, a helpful AI assistant.", + model_name="gpt-4o-mini", # Using a lightweight model for examples + max_loops=1, + autosave=False, + verbose=False, + ) + agents.append(agent) + return agents + + +agents = create_example_agents(3) + +task = "Write a creative story about sci fi with no cliches. Make it 1000 words." + +results = run_agents_concurrently_uvloop(agents=agents, task=task) + + +print(results) diff --git a/pyproject.toml b/pyproject.toml index 67fb80b1..9095ce51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -81,7 +81,7 @@ mcp = "*" openai = "*" aiohttp = "*" schedule = "*" -uvloop = "*" +uvloop = {version = "*", markers = "sys_platform != 'win32'"} [tool.poetry.scripts] swarms = "swarms.cli.main:main" diff --git a/scripts/setup.sh b/scripts/setup.sh index 6a8ebcad..2ae94254 100644 --- a/scripts/setup.sh +++ b/scripts/setup.sh @@ -38,26 +38,39 @@ 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_VERSION=$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))') - print_status "Found Python $PYTHON_VERSION" + PYTHON_CMD="python3" +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" + 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 python3 -c 'import sys; exit(0 if sys.version_info >= (3, 10) else 1)'; then + 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. Please install a compatible Python version." exit 1 fi else - print_error "Python3 is not installed. Please install Python 3.10 or higher." + print_error "Python is not installed or not found. Please install Python 3.10 or higher." + print_error "Make sure Python is in your PATH and accessible as 'python' or 'python3'" exit 1 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 | python3 - + curl -sSL https://install.python-poetry.org | $PYTHON_CMD - # Add Poetry to PATH for current session export PATH="$HOME/.local/bin:$PATH" @@ -77,7 +90,14 @@ fi # Configure Poetry to create virtual environments in project directory print_status "Configuring Poetry..." poetry config virtualenvs.in-project true -poetry config virtualenvs.prefer-active-python true + +# Check if the prefer-active-python option exists (available in newer Poetry versions) +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" +else + print_warning "virtualenvs.prefer-active-python option not available in this Poetry version, skipping..." +fi # Install dependencies print_status "Installing project dependencies..." diff --git a/scripts/test_python_detection.sh b/scripts/test_python_detection.sh new file mode 100644 index 00000000..a7562f73 --- /dev/null +++ b/scripts/test_python_detection.sh @@ -0,0 +1,75 @@ +#!/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/agent.py b/swarms/structs/agent.py index 7eb371cf..970c2a7a 100644 --- a/swarms/structs/agent.py +++ b/swarms/structs/agent.py @@ -14,6 +14,7 @@ from typing import ( Callable, Dict, List, + Literal, Optional, Sequence, Tuple, @@ -464,6 +465,7 @@ class Agent: reasoning_enabled: bool = False, handoffs: Optional[Union[Sequence[Callable], Any]] = None, capabilities: Optional[List[str]] = None, + mode: Literal["interactive", "fast", "standard"] = "standard", *args, **kwargs, ): @@ -614,6 +616,7 @@ class Agent: self.fallback_model_name = fallback_model_name self.handoffs = handoffs self.capabilities = capabilities + self.mode = mode # Initialize transforms if transforms is None: @@ -683,6 +686,10 @@ class Agent: self.reliability_check() + if self.mode == "fast": + self.print_on = False + self.verbose = False + def handle_handoffs(self, task: Optional[str] = None): router = MultiAgentRouter( name=self.agent_name,