diff --git a/docs/llm.txt b/docs/llm.txt index 6ddd4924..7927b99a 100644 --- a/docs/llm.txt +++ b/docs/llm.txt @@ -7696,7 +7696,7 @@ agents = [ # Initialize the swarm to run these agents concurrently swarm = SpreadSheetSwarm( agents=agents, - autosave_on=True, + autosave=True, save_file_path="marketing_posts.csv", ) @@ -42470,7 +42470,7 @@ agents = [ # Initialize the swarm to run these agents concurrently swarm = SpreadSheetSwarm( agents=agents, - autosave_on=True, + autosave=True, save_file_path="marketing_posts.csv", ) @@ -47159,7 +47159,7 @@ The `SpreadSheetSwarm` class contains several attributes that define its behavio | `name` | `str` | The name of the swarm. | | `description` | `str` | A description of the swarm's purpose. | | `agents` | `Union[Agent, List[Agent]]` | The agents participating in the swarm. Can be a single agent or a list of agents. | -| `autosave_on` | `bool` | Flag indicating whether autosave is enabled. | +| `autosave` | `bool` | Flag indicating whether autosave is enabled. | | `save_file_path` | `str` | The file path where the swarm data will be saved. | | `task_queue` | `queue.Queue` | The queue that stores tasks to be processed by the agents. | | `lock` | `threading.Lock` | A lock used for thread synchronization to prevent race conditions. | @@ -47173,7 +47173,7 @@ The `SpreadSheetSwarm` class contains several attributes that define its behavio - **`name`** (`str`, optional): The name of the swarm. Default is `"Spreadsheet-Swarm"`. - **`description`** (`str`, optional): A brief description of the swarm. Default is `"A swarm that processes tasks from a queue using multiple agents on different threads."`. - **`agents`** (`Union[Agent, List[Agent]]`, optional): The agents participating in the swarm. Default is an empty list. -- **`autosave_on`** (`bool`, optional): A flag to indicate if autosave is enabled. Default is `True`. +- **`autosave`** (`bool`, optional): A flag to indicate if autosave is enabled. Default is `True`. - **`save_file_path`** (`str`, optional): The file path where swarm data will be saved. Default is `"spreedsheet_swarm.csv"`. - **`run_all_agents`** (`bool`, optional): Flag to determine if all agents should run. Default is `True`. - **`max_loops`** (`int`, optional): The number of times to repeat the task. Default is `1`. @@ -47351,7 +47351,7 @@ swarm = SpreadSheetSwarm( name="Finance-Spreadsheet-Swarm", description="A swarm that processes tasks from a queue using multiple agents on different threads.", agents=agents, - autosave_on=True, + autosave=True, save_file_path="financial_spreed_sheet_swarm_demo.csv", run_all_agents=False, max_loops=1, @@ -47409,7 +47409,7 @@ swarm = SpreadSheetSwarm( name="QR-Code-Generation-Swarm", description="A swarm that generates Python scripts to create QR codes for specific links.", agents=agents, - autosave_on=True, + autosave=True, save_file_path="qr_code_generation_results.csv", run_all_agents=False, max_loops=1, @@ -47503,7 +47503,7 @@ swarm = SpreadSheetSwarm( name="Social-Media-Marketing-Swarm", description="A swarm that processes social media marketing tasks using multiple agents on different threads.", agents=agents, - autosave_on=True, + autosave=True, save_file_path="social_media_marketing_spreadsheet.csv", run_all_agents=False, max_loops=2, @@ -47522,7 +47522,7 @@ swarm.run( | Tip/Feature | Description | |------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | **Thread Synchronization** | When working with multiple agents in a concurrent environment, it's crucial to ensure that access to shared resources is properly synchronized using locks to avoid race conditions. | -| **Autosave Feature** | If you enable the `autosave_on` flag, ensure that the file path provided is correct and writable. This feature is handy for long-running tasks where you want to periodically save the state. | +| **Autosave Feature** | If you enable the `autosave` flag, ensure that the file path provided is correct and writable. This feature is handy for long-running tasks where you want to periodically save the state. | | **Error Handling** | Implementing proper error handling within your agents can prevent the swarm from crashing during execution. Consider catching exceptions in the `run` method and logging errors appropriately. | | **Custom Agents** | You can extend the `Agent` class to create custom agents that perform specific tasks tailored to your application's needs. | @@ -49595,7 +49595,7 @@ The `TaskQueueSwarm` class is designed to manage and execute tasks using multipl | `agents` | `List[Agent]` | The list of agents in the swarm. | | `task_queue` | `queue.Queue` | A queue to store tasks for processing. | | `lock` | `threading.Lock` | A lock for thread synchronization. | -| `autosave_on` | `bool` | Whether to automatically save the swarm metadata. | +| `autosave` | `bool` | Whether to automatically save the swarm metadata. | | `save_file_path` | `str` | The file path for saving swarm metadata. | | `workspace_dir` | `str` | The directory path of the workspace. | | `return_metadata_on` | `bool` | Whether to return the swarm metadata after running. | @@ -49604,7 +49604,7 @@ The `TaskQueueSwarm` class is designed to manage and execute tasks using multipl ## Methods -### `__init__(self, agents: List[Agent], name: str = "Task-Queue-Swarm", description: str = "A swarm that processes tasks from a queue using multiple agents on different threads.", autosave_on: bool = True, save_file_path: str = "swarm_run_metadata.json", workspace_dir: str = os.getenv("WORKSPACE_DIR"), return_metadata_on: bool = False, max_loops: int = 1, *args, **kwargs)` +### `__init__(self, agents: List[Agent], name: str = "Task-Queue-Swarm", description: str = "A swarm that processes tasks from a queue using multiple agents on different threads.", autosave: bool = True, save_file_path: str = "swarm_run_metadata.json", workspace_dir: str = os.getenv("WORKSPACE_DIR"), return_metadata_on: bool = False, max_loops: int = 1, *args, **kwargs)` The constructor initializes the `TaskQueueSwarm` object. @@ -49612,7 +49612,7 @@ The constructor initializes the `TaskQueueSwarm` object. - `agents` (`List[Agent]`): The list of agents in the swarm. - `name` (`str`, optional): The name of the swarm. Defaults to "Task-Queue-Swarm". - `description` (`str`, optional): The description of the swarm. Defaults to "A swarm that processes tasks from a queue using multiple agents on different threads.". - - `autosave_on` (`bool`, optional): Whether to automatically save the swarm metadata. Defaults to True. + - `autosave` (`bool`, optional): Whether to automatically save the swarm metadata. Defaults to True. - `save_file_path` (`str`, optional): The file path to save the swarm metadata. Defaults to "swarm_run_metadata.json". - `workspace_dir` (`str`, optional): The directory path of the workspace. Defaults to os.getenv("WORKSPACE_DIR"). - `return_metadata_on` (`bool`, optional): Whether to return the swarm metadata after running. Defaults to False. diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 3dbe9e3f..13ac92ea 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -237,13 +237,12 @@ nav: - Overview: "swarms/framework/agents_explained.md" - Quickstart: "swarms/agents/index.md" - Reference: "swarms/structs/agent.md" - - LLM Providers: "swarms/models/agent_and_models.md" - Tools and MCP: "swarms/tools/tools_examples.md" - Multi-Agent Helpers: "swarms/structs/agent_multi_agent_communication.md" - - Running Agents with YAML: "swarms/agents/create_agents_yaml.md" - - - Additional Capabilities: + - Capabilities: + - Fallback Models: "swarms/utils/fallback_models.md" + - Running Agents with YAML: "swarms/agents/create_agents_yaml.md" - Tools Reference: - Overview: "swarms/tools/main.md" - What are tools?: "swarms/tools/build_tool.md" diff --git a/docs/quickstart.md b/docs/quickstart.md index f05def6f..1780748a 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -192,7 +192,7 @@ agents = [ # Initialize the swarm to run these agents concurrently swarm = SpreadSheetSwarm( agents=agents, - autosave_on=True, + autosave=True, save_file_path="marketing_posts.csv", ) diff --git a/docs/swarms/structs/agent.md b/docs/swarms/structs/agent.md index 8f729c8f..063cf11f 100644 --- a/docs/swarms/structs/agent.md +++ b/docs/swarms/structs/agent.md @@ -91,6 +91,7 @@ The `Agent` class establishes a conversational loop with a language model, allow | `callback` | `Optional[Callable]` | Callable function to be called after each agent loop. | | `metadata` | `Optional[Dict[str, Any]]` | Dictionary containing metadata for the agent. | | `callbacks` | `Optional[List[Callable]]` | List of callable functions to be called during execution. | +| `handoffs` | `Optional[Union[Sequence[Callable], Any]]` | List of Agent instances that can be delegated tasks to. When provided, the agent will use a MultiAgentRouter to intelligently route tasks to the most appropriate specialized agent. | | `search_algorithm` | `Optional[Callable]` | Callable function for long-term memory retrieval. | | `logs_to_filename` | `Optional[str]` | File path for logging agent activities. | | `evaluator` | `Optional[Callable]` | Callable function for evaluating the agent's responses. | @@ -239,6 +240,7 @@ The `Agent` class establishes a conversational loop with a language model, allow | `model_dump_yaml()` | Saves the agent model to a YAML file in the workspace directory. | None | `agent.model_dump_yaml()` | | `log_agent_data()` | Logs the agent's data to an external API. | None | `agent.log_agent_data()` | | `handle_tool_schema_ops()` | Handles operations related to tool schemas. | None | `agent.handle_tool_schema_ops()` | +| `handle_handoffs(task)` | Handles task delegation to specialized agents when handoffs are configured. | `task` (str): Task to be delegated to appropriate specialized agent. | `response = agent.handle_handoffs("Analyze market data")` | | `call_llm(task, *args, **kwargs)` | Calls the appropriate method on the language model. | `task` (str): Task for the LLM.
`*args`, `**kwargs`: Additional arguments. | `response = agent.call_llm("Generate text")` | | `handle_sop_ops()` | Handles operations related to standard operating procedures. | None | `agent.handle_sop_ops()` | | `agent_output_type(responses)` | Processes and returns the agent's output based on the specified output type. | `responses` (list): List of responses. | `formatted_output = agent.agent_output_type(responses)` | @@ -427,6 +429,100 @@ response = agent.run("What are the components of a startup's stock incentive equ print(response) ``` +### Agent Handoffs and Task Delegation + +The `Agent` class supports intelligent task delegation through the `handoffs` parameter. When provided with a list of specialized agents, the main agent acts as a router that analyzes incoming tasks and delegates them to the most appropriate specialized agent based on their capabilities and descriptions. + +#### How Handoffs Work + +1. **Task Analysis**: When a task is received, the main agent uses a built-in "boss agent" to analyze the task requirements +2. **Agent Selection**: The boss agent evaluates all available specialized agents and selects the most suitable one(s) based on their descriptions and capabilities +3. **Task Delegation**: The selected agent(s) receive the task (potentially modified for better execution) and process it +4. **Response Aggregation**: Results from specialized agents are collected and returned + +#### Key Features + +| Feature | Description | +|---------------------------|-----------------------------------------------------------------------------------------------| +| **Intelligent Routing** | Uses AI to determine the best agent for each task | +| **Multiple Agent Support**| Can delegate to multiple agents for complex tasks requiring different expertise | +| **Task Modification** | Can modify tasks to better suit the selected agent's capabilities | +| **Transparent Reasoning** | Provides clear explanations for agent selection decisions | +| **Seamless Integration** | Works transparently with the existing `run()` method | + +#### Basic Handoff Example + +```python +from swarms import Agent + +# Create specialized agents +risk_metrics_agent = Agent( + agent_name="Risk-Metrics-Calculator", + agent_description="Calculates key risk metrics like VaR, Sharpe ratio, and volatility", + system_prompt="""You are a risk metrics specialist. Calculate and explain: + - Value at Risk (VaR) + - Sharpe ratio + - Volatility + - Maximum drawdown + - Beta coefficient + + Provide clear, numerical results with brief explanations.""", + max_loops=1, + model_name="gpt-4o-mini", + dynamic_temperature_enabled=True, +) + +market_risk_agent = Agent( + agent_name="Market-Risk-Monitor", + agent_description="Monitors market conditions and identifies risk factors", + system_prompt="""You are a market risk monitor. Identify and assess: + - Market volatility trends + - Economic risk factors + - Geopolitical risks + - Interest rate risks + - Currency risks + + Provide current risk alerts and trends.""", + max_loops=1, + dynamic_temperature_enabled=True, +) + +# Create main agent with handoffs +portfolio_risk_agent = Agent( + agent_name="Portfolio-Risk-Analyzer", + agent_description="Analyzes portfolio diversification and concentration risk", + system_prompt="""You are a portfolio risk analyst. Focus on: + - Portfolio diversification analysis + - Concentration risk assessment + - Correlation analysis + - Sector/asset allocation risk + - Liquidity risk evaluation + + Provide actionable insights for risk reduction.""", + max_loops=1, + dynamic_temperature_enabled=True, + handoffs=[ + risk_metrics_agent, + market_risk_agent, + ], +) + +# Run task - will be automatically delegated to appropriate agent +response = portfolio_risk_agent.run( + "Calculate VaR and Sharpe ratio for a portfolio with 15% annual return and 20% volatility" +) +print(response) +``` + + +#### Use Cases + +- **Financial Analysis**: Route different types of financial analysis to specialized agents (risk, valuation, market analysis) +- **Software Development**: Delegate coding, testing, documentation, and code review to different agents +- **Research Projects**: Route research tasks to domain-specific agents +- **Customer Support**: Delegate different types of inquiries to specialized support agents +- **Content Creation**: Route writing, editing, and fact-checking to different content specialists + ### Interactive Mode To enable interactive mode, set the `interactive` parameter to `True` when initializing the `Agent`: @@ -1014,5 +1110,6 @@ The `run` method now supports several new parameters for advanced functionality: | `mcp_url` or `mcp_urls` | Use mcp_url or mcp_urls to extend agent capabilities with external tools. | | `react_on` | Enable react_on for complex reasoning tasks requiring step-by-step analysis. | | `tool_retry_attempts` | Configure tool_retry_attempts for robust tool execution in production environments. | +| `handoffs` | Use handoffs to create specialized agent teams that can intelligently route tasks based on complexity and expertise requirements. | By following these guidelines and leveraging the Swarm Agent's extensive features, you can create powerful, flexible, and efficient autonomous agents for a wide range of applications. \ No newline at end of file diff --git a/docs/swarms/structs/index.md b/docs/swarms/structs/index.md index 1aacc7c1..965f4457 100644 --- a/docs/swarms/structs/index.md +++ b/docs/swarms/structs/index.md @@ -123,7 +123,7 @@ agents = [ # Initialize the swarm to run these agents concurrently swarm = SpreadSheetSwarm( agents=agents, - autosave_on=True, + autosave=True, save_file_path="marketing_posts.csv", ) 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/docs/swarms/structs/spreadsheet_swarm.md b/docs/swarms/structs/spreadsheet_swarm.md index 6039c36e..48a7a7b2 100644 --- a/docs/swarms/structs/spreadsheet_swarm.md +++ b/docs/swarms/structs/spreadsheet_swarm.md @@ -1,12 +1,9 @@ # SpreadSheetSwarm Documentation +## Overview +The `SpreadSheetSwarm` is a concurrent processing system that manages multiple agents to execute tasks simultaneously. It supports both pre-configured agents and CSV-based agent loading, with automatic metadata tracking and file output capabilities. -## Class Definition - -```python -class SpreadSheetSwarm: -``` ## Full Path @@ -14,38 +11,64 @@ class SpreadSheetSwarm: from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm ``` -### Attributes - -The `SpreadSheetSwarm` class contains several attributes that define its behavior and configuration. These attributes are initialized in the constructor (`__init__` method) and are used throughout the class to manage the swarm's operations. -| Attribute | Type | Description | -|--------------------|-----------------------------------|---------------------------------------------------------------------------------------------| -| `name` | `str` | The name of the swarm. | -| `description` | `str` | A description of the swarm's purpose. | -| `agents` | `Union[Agent, List[Agent]]` | The agents participating in the swarm. Can be a single agent or a list of agents. | -| `autosave_on` | `bool` | Flag indicating whether autosave is enabled. | -| `save_file_path` | `str` | The file path where the swarm data will be saved. | -| `task_queue` | `queue.Queue` | The queue that stores tasks to be processed by the agents. | -| `lock` | `threading.Lock` | A lock used for thread synchronization to prevent race conditions. | -| `metadata` | `SwarmRunMetadata` | Metadata for the swarm run, including start time, end time, tasks completed, and outputs. | -| `run_all_agents` | `bool` | Flag indicating whether to run all agents or just one. | -| `max_loops` | `int` | The number of times to repeat the task. | -| `workspace_dir` | `str` | The directory where the workspace is located, retrieved from environment variables. | +## Constructor -### Parameters +### `__init__` -- **`name`** (`str`, optional): The name of the swarm. Default is `"Spreadsheet-Swarm"`. -- **`description`** (`str`, optional): A brief description of the swarm. Default is `"A swarm that processes tasks from a queue using multiple agents on different threads."`. -- **`agents`** (`Union[Agent, List[Agent]]`, optional): The agents participating in the swarm. Default is an empty list. -- **`autosave_on`** (`bool`, optional): A flag to indicate if autosave is enabled. Default is `True`. -- **`save_file_path`** (`str`, optional): The file path where swarm data will be saved. Default is `"spreedsheet_swarm.csv"`. -- **`run_all_agents`** (`bool`, optional): Flag to determine if all agents should run. Default is `True`. -- **`max_loops`** (`int`, optional): The number of times to repeat the task. Default is `1`. -- **`workspace_dir`** (`str`, optional): The directory where the workspace is located. Default is retrieved from environment variable `WORKSPACE_DIR`. +```python +def __init__( + self, + name: str = "Spreadsheet-Swarm", + description: str = "A swarm that processes tasks concurrently using multiple agents and saves the metadata to a CSV file.", + agents: List[AgentType] = None, + autosave: bool = True, + save_file_path: str = None, + max_loops: int = 1, + workspace_dir: str = os.getenv("WORKSPACE_DIR"), + load_path: str = None, + verbose: bool = False, + *args, + **kwargs, +): +``` -### Constructor (`__init__`) +#### Parameters -The constructor initializes the `SpreadSheetSwarm` with the provided parameters. It sets up the task queue, locks for thread synchronization, and initializes the metadata. +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `name` | `str` | `"Spreadsheet-Swarm"` | The name of the swarm | +| `description` | `str` | `"A swarm that processes tasks concurrently using multiple agents and saves the metadata to a CSV file."` | Description of the swarm's purpose | +| `agents` | `List[AgentType]` | `None` | List of agents participating in the swarm. If `None`, agents will be loaded from `load_path` | +| `autosave` | `bool` | `True` | Whether to enable autosave of swarm metadata | +| `save_file_path` | `str` | `None` | File path to save swarm metadata as CSV. If `None`, auto-generated based on workspace_dir | +| `max_loops` | `int` | `1` | Number of times to repeat the swarm tasks | +| `workspace_dir` | `str` | `os.getenv("WORKSPACE_DIR")` | Directory path of the workspace | +| `load_path` | `str` | `None` | Path to CSV file containing agent configurations. Required if `agents` is `None` | +| `verbose` | `bool` | `False` | Whether to enable verbose logging | +| `*args` | `Any` | - | Additional positional arguments | +| `**kwargs` | `Any` | - | Additional keyword arguments | + +#### Attributes + +| Attribute | Type | Description | +|-----------|------|-------------| +| `name` | `str` | The name of the swarm | +| `description` | `str` | Description of the swarm's purpose | +| `agents` | `List[AgentType]` | List of agents participating in the swarm | +| `autosave` | `bool` | Whether autosave is enabled | +| `save_file_path` | `str` | File path where swarm metadata is saved | +| `max_loops` | `int` | Number of times to repeat tasks | +| `workspace_dir` | `str` | Directory path of the workspace | +| `load_path` | `str` | Path to CSV file for agent configurations | +| `verbose` | `bool` | Whether verbose logging is enabled | +| `outputs` | `List[Dict]` | List of completed task outputs | +| `tasks_completed` | `int` | Counter for completed tasks | +| `agent_tasks` | `Dict[str, str]` | Mapping of agent names to their tasks | + +#### Note + +Either `agents` or `load_path` must be provided. If both are provided, `agents` will be used. --- @@ -54,16 +77,16 @@ The constructor initializes the `SpreadSheetSwarm` with the provided parameters. ### `reliability_check` ```python -def reliability_check(self): +def reliability_check(self) -> None ``` #### Description -The `reliability_check` method performs a series of checks to ensure that the swarm is properly configured before it begins processing tasks. It verifies that there are agents available and that a valid file path is provided for saving the swarm's data. If any of these checks fail, an exception is raised. +Performs reliability checks to ensure the swarm is properly configured before processing tasks. Verifies that agents are provided and max_loops is set. #### Raises -- **`ValueError`**: Raised if no agents are provided or if no save file path is specified. +- **`ValueError`**: If no agents are provided or if max_loops is not provided. #### Example @@ -77,24 +100,71 @@ swarm.reliability_check() ### `run` ```python -def run(self, task: str, *args, **kwargs): +def run(self, task: str = None, *args, **kwargs) -> Dict[str, Any] ``` -#### Description +#### Run Description -The `run` method starts the task processing using the swarm. Depending on the configuration, it can either run all agents or a specific subset of them. The method tracks the start and end times of the task, executes the task multiple times if specified, and logs the results. +Main method to run the swarm with a specified task or using configured tasks. Handles both single task execution and CSV-based configuration. -#### Parameters +#### Run Parameters -- **`task`** (`str`): The task to be executed by the swarm. +- **`task`** (`str`, optional): The task to be executed by all agents. If `None`, uses tasks from config. - **`*args`**: Additional positional arguments to pass to the agents. - **`**kwargs`**: Additional keyword arguments to pass to the agents. -#### Example +#### Run Returns + +- **`Dict[str, Any]`**: Summary of the swarm execution containing run_id, name, description, start_time, end_time, tasks_completed, number_of_agents, and outputs. + +#### Run Example ```python swarm = SpreadSheetSwarm(agents=[agent1, agent2]) -swarm.run("Process Data") +result = swarm.run("Process Data") +print(result) +``` + +--- + +### `run_from_config` + +```python +def run_from_config(self) -> Dict[str, Any] +``` + +#### Run From Config Description + +Runs all agents with their configured tasks concurrently. Loads agents from CSV if needed and executes tasks based on the agent-task mapping. + +#### Run From Config Returns + +- **`Dict[str, Any]`**: Summary of the swarm execution. + +#### Run From Config Example + +```python +swarm = SpreadSheetSwarm(load_path="agents.csv") +result = swarm.run_from_config() +``` + +--- + +### `load_from_csv` + +```python +def load_from_csv(self) -> None +``` + +#### Load From CSV Description + +Loads agent configurations from a CSV file. Expected CSV format includes columns: agent_name, description, system_prompt, task, model_name, docs, max_loops, user_name, stopping_token. + +#### Load From CSV Example + +```python +swarm = SpreadSheetSwarm(load_path="agents.csv") +swarm.load_from_csv() ``` --- @@ -102,18 +172,18 @@ swarm.run("Process Data") ### `export_to_json` ```python -def export_to_json(self): +def export_to_json(self) -> str ``` -#### Description +#### Export To JSON Description -The `export_to_json` method generates a JSON representation of the swarm's metadata. This can be useful for exporting the results to an external system or for logging purposes. +Exports the swarm outputs to JSON format. Useful for external system integration or logging purposes. -#### Returns +#### Export To JSON Returns -- **`str`**: The JSON representation of the swarm's metadata. +- **`str`**: JSON representation of the swarm's metadata. -#### Example +#### Export To JSON Example ```python json_data = swarm.export_to_json() @@ -125,14 +195,14 @@ print(json_data) ### `data_to_json_file` ```python -def data_to_json_file(self): +def data_to_json_file(self) -> None ``` -#### Description +#### Data To JSON File Description -The `data_to_json_file` method saves the swarm's metadata as a JSON file in the specified workspace directory. The file name is generated using the swarm's name and run ID. +Saves the swarm's metadata as a JSON file in the specified workspace directory. File name is generated using the swarm's name and run ID. -#### Example +#### Data To JSON File Example ```python swarm.data_to_json_file() @@ -143,23 +213,23 @@ swarm.data_to_json_file() ### `_track_output` ```python -def _track_output(self, agent: Agent, task: str, result: str): +def _track_output(self, agent_name: str, task: str, result: str) -> None ``` -#### Description +#### Track Output Description -The `_track_output` method is used internally to record the results of tasks executed by the agents. It updates the metadata with the completed tasks and their results. +Internal method to track the output of a completed task. Updates the outputs list and increments the tasks_completed counter. -#### Parameters +#### Track Output Parameters -- **`agent`** (`Agent`): The agent that executed the task. -- **`task`** (`str`): The task that was executed. -- **`result`** (`str`): The result of the task execution. +- **`agent_name`** (`str`): The name of the agent that completed the task. +- **`task`** (`str`): The task that was completed. +- **`result`** (`str`): The result of the completed task. -#### Example +#### Track Output Example ```python -swarm._track_output(agent1, "Process Data", "Success") +swarm._track_output("Agent1", "Process Data", "Success") ``` --- @@ -167,14 +237,14 @@ swarm._track_output(agent1, "Process Data", "Success") ### `_save_to_csv` ```python -def _save_to_csv(self): +def _save_to_csv(self) -> None ``` -#### Description +#### Save To CSV Description -The `_save_to_csv` method saves the swarm's metadata to a CSV file. It logs each task and its result before writing them to the file. The file is saved in the location specified by `save_file_path`. +Saves the swarm's metadata to a CSV file. Creates the file with headers if it doesn't exist, then appends task results. -#### Example +#### Save To CSV Example ```python swarm._save_to_csv() @@ -184,199 +254,164 @@ swarm._save_to_csv() ## Usage Examples -### Example 1: Basic Swarm Initialization +### Example 1: Basic Financial Analysis Swarm ```python -import os - -from swarms import Agent, SpreadSheetSwarm -from swarms.prompts.finance_agent_sys_prompt import ( - FINANCIAL_AGENT_SYS_PROMPT, -) - +from swarms import Agent +from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm -# Initialize your agents (assuming the Agent class and model are already defined) +# Example 1: Using pre-configured agents agents = [ Agent( - agent_name=f"Financial-Analysis-Agent-spreesheet-swarm:{i}", - system_prompt=FINANCIAL_AGENT_SYS_PROMPT, - model_name="gpt-4.1", + agent_name="Research-Agent", + agent_description="Specialized in market research and analysis", + model_name="claude-sonnet-4-20250514", + dynamic_temperature_enabled=True, + max_loops=1, + streaming_on=False, + ), + Agent( + agent_name="Technical-Agent", + agent_description="Expert in technical analysis and trading strategies", + model_name="claude-sonnet-4-20250514", + dynamic_temperature_enabled=True, max_loops=1, + streaming_on=False, + ), + Agent( + agent_name="Risk-Agent", + agent_description="Focused on risk assessment and portfolio management", + model_name="claude-sonnet-4-20250514", dynamic_temperature_enabled=True, - saved_state_path="finance_agent.json", - user_name="swarms_corp", - retry_attempts=1, - ) - for i in range(10) + max_loops=1, + streaming_on=False, + ), ] -# Create a Swarm with the list of agents +# Initialize the SpreadSheetSwarm with agents swarm = SpreadSheetSwarm( - name="Finance-Spreadsheet-Swarm", - description="A swarm that processes tasks from a queue using multiple agents on different threads.", + name="Financial-Analysis-Swarm", + description="A swarm of specialized financial analysis agents", agents=agents, - autosave_on=True, - save_file_path="financial_spreed_sheet_swarm_demo.csv", - run_all_agents=False, max_loops=1, + autosave=False, + workspace_dir="./swarm_outputs", ) -# Run the swarm -swarm.run( - task="Analyze the states with the least taxes for LLCs. Provide an overview of all tax rates and add them with a comprehensive analysis" -) +# Run all agents with the same task +task = "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis." +result = swarm.run(task=task) +print(result) ``` -### Example 2: QR Code Generator +### Example 2: CSV-Based Agent Configuration ```python -import os -from swarms import Agent, SpreadSheetSwarm +from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm -# Define custom system prompts for QR code generation -QR_CODE_AGENT_1_SYS_PROMPT = """ -You are a Python coding expert. Your task is to write a Python script to generate a QR code for the link: https://lu.ma/jjc1b2bo. The code should save the QR code as an image file. -""" +# Create a CSV file with agent configurations +csv_content = """agent_name,description,system_prompt,task,model_name +Research-Agent,Market research specialist,You are a market research expert.,Analyze market trends,claude-sonnet-4-20250514 +Technical-Agent,Technical analysis expert,You are a technical analysis expert.,Perform technical analysis,claude-sonnet-4-20250514 +Risk-Agent,Risk assessment specialist,You are a risk assessment expert.,Evaluate investment risks,claude-sonnet-4-20250514""" + +with open("agents.csv", "w") as f: + f.write(csv_content) + +# Initialize swarm with CSV configuration +swarm = SpreadSheetSwarm( + name="CSV-Configured-Swarm", + description="A swarm loaded from CSV configuration", + load_path="agents.csv", + max_loops=1, + autosave=True, + workspace_dir="./csv_swarm_outputs", +) + +# Run agents with their configured tasks +result = swarm.run_from_config() +print(result) +``` -QR_CODE_AGENT_2_SYS_PROMPT = """ -You are a Python coding expert. Your task is to write a Python script to generate a QR code for the link: https://github.com/The-Swarm-Corporation/Cookbook. The code should save the QR code as an image file. -""" +### Example 3: Multi-Loop Task Execution +```python +from swarms import Agent +from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm -# Initialize your agents for QR code generation +# Create specialized agents agents = [ Agent( - agent_name="QR-Code-Generator-Agent-Luma", - system_prompt=QR_CODE_AGENT_1_SYS_PROMPT, - model_name="gpt-4.1", - max_loops=1, + agent_name="Content-Agent", + agent_description="Content creation specialist", + model_name="claude-sonnet-4-20250514", dynamic_temperature_enabled=True, - saved_state_path="qr_code_agent_luma.json", - user_name="swarms_corp", - retry_attempts=1, + max_loops=1, ), Agent( - agent_name="QR-Code-Generator-Agent-Cookbook", - system_prompt=QR_CODE_AGENT_2_SYS_PROMPT, - model_name="gpt-4.1", - max_loops=1, + agent_name="SEO-Agent", + agent_description="SEO optimization expert", + model_name="claude-sonnet-4-20250514", dynamic_temperature_enabled=True, - saved_state_path="qr_code_agent_cookbook.json", - user_name="swarms_corp", - retry_attempts=1, + max_loops=1, ), ] -# Create a Swarm with the list of agents +# Initialize swarm with multiple loops swarm = SpreadSheetSwarm( - name="QR-Code-Generation-Swarm", - description="A swarm that generates Python scripts to create QR codes for specific links.", + name="Content-Creation-Swarm", + description="A swarm for content creation and optimization", agents=agents, - autosave_on=True, - save_file_path="qr_code_generation_results.csv", - run_all_agents=False, - max_loops=1, + max_loops=3, # Each agent will run the task 3 times + autosave=True, + workspace_dir="./content_outputs", ) -# Run the swarm -swarm.run( - task="Generate Python scripts to create QR codes for the provided links and save them as image files." -) -``` +# Run the same task multiple times +task = "Create a blog post about AI trends in 2024" +result = swarm.run(task=task) +print(f"Tasks completed: {result['tasks_completed']}") +print(f"Number of agents: {result['number_of_agents']}") +``` -## Example 3: Social Media Marketing +### Example 4: JSON Export and Metadata Tracking ```python +from swarms import Agent +from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm -import os -from swarms import Agent, SpreadSheetSwarm - -# Define custom system prompts for each social media platform -TWITTER_AGENT_SYS_PROMPT = """ -You are a Twitter marketing expert. Your task is to create engaging, concise tweets and analyze trends to maximize engagement. Consider hashtags, timing, and content relevance. -""" - -INSTAGRAM_AGENT_SYS_PROMPT = """ -You are an Instagram marketing expert. Your task is to create visually appealing and engaging content, including captions and hashtags, tailored to a specific audience. -""" - -FACEBOOK_AGENT_SYS_PROMPT = """ -You are a Facebook marketing expert. Your task is to craft posts that are optimized for engagement and reach on Facebook, including using images, links, and targeted messaging. -""" - -EMAIL_AGENT_SYS_PROMPT = """ -You are an Email marketing expert. Your task is to write compelling email campaigns that drive conversions, focusing on subject lines, personalization, and call-to-action strategies. -""" - -# Example usage: -api_key = os.getenv("OPENAI_API_KEY") - -# Model -model = OpenAIChat( - openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1 -) - -# Initialize your agents for different social media platforms agents = [ Agent( - agent_name="Twitter-Marketing-Agent", - system_prompt=TWITTER_AGENT_SYS_PROMPT, - model_name="gpt-4.1", - max_loops=1, - dynamic_temperature_enabled=True, - saved_state_path="twitter_agent.json", - user_name="swarms_corp", - retry_attempts=1, - ), - Agent( - agent_name="Instagram-Marketing-Agent", - system_prompt=INSTAGRAM_AGENT_SYS_PROMPT, - model_name="gpt-4.1", - max_loops=1, + agent_name="Data-Analyst", + agent_description="Data analysis specialist", + model_name="claude-sonnet-4-20250514", dynamic_temperature_enabled=True, - saved_state_path="instagram_agent.json", - user_name="swarms_corp", - retry_attempts=1, - ), - Agent( - agent_name="Facebook-Marketing-Agent", - system_prompt=FACEBOOK_AGENT_SYS_PROMPT, - model_name="gpt-4.1", max_loops=1, - dynamic_temperature_enabled=True, - saved_state_path="facebook_agent.json", - user_name="swarms_corp", - retry_attempts=1, - ), - Agent( - agent_name="Email-Marketing-Agent", - system_prompt=EMAIL_AGENT_SYS_PROMPT, - model_name="gpt-4.1", - max_loops=1, - dynamic_temperature_enabled=True, - saved_state_path="email_agent.json", - user_name="swarms_corp", - retry_attempts=1, ), ] -# Create a Swarm with the list of agents swarm = SpreadSheetSwarm( - name="Social-Media-Marketing-Swarm", - description="A swarm that processes social media marketing tasks using multiple agents on different threads.", + name="Data-Analysis-Swarm", + description="A swarm for data analysis tasks", agents=agents, - autosave_on=True, - save_file_path="social_media_marketing_spreadsheet.csv", - run_all_agents=False, - max_loops=2, + max_loops=1, + autosave=True, + workspace_dir="./data_analysis_outputs", ) -# Run the swarm -swarm.run( - task="Create posts to promote hack nights in miami beach for developers, engineers, and tech enthusiasts. Include relevant hashtags, images, and engaging captions." -) +# Run the task +result = swarm.run("Analyze the provided dataset and generate insights") + +# Export to JSON +json_data = swarm.export_to_json() +print("JSON Export:") +print(json_data) + +# Save metadata to JSON file +swarm.data_to_json_file() +print("Metadata saved to JSON file") ``` --- @@ -385,9 +420,45 @@ swarm.run( | Tip/Feature | Description | |------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| **Thread Synchronization** | When working with multiple agents in a concurrent environment, it's crucial to ensure that access to shared resources is properly synchronized using locks to avoid race conditions. | -| **Autosave Feature** | If you enable the `autosave_on` flag, ensure that the file path provided is correct and writable. This feature is handy for long-running tasks where you want to periodically save the state. | -| **Error Handling** | Implementing proper error handling within your agents can prevent the swarm from crashing during execution. Consider catching exceptions in the `run` method and logging errors appropriately. | -| **Custom Agents** | You can extend the `Agent` class to create custom agents that perform specific tasks tailored to your application's needs. | +| **Concurrent Execution** | The swarm uses `run_agents_with_different_tasks` for concurrent execution of multiple agents. This provides better performance compared to sequential execution. | +| **Autosave Feature** | When `autosave=True`, the swarm automatically saves metadata to both CSV and JSON files. CSV files are saved with unique run IDs to prevent conflicts. | +| **CSV Configuration** | You can load agent configurations from CSV files with columns: agent_name, description, system_prompt, task, model_name, docs, max_loops, user_name, stopping_token. | +| **Workspace Management** | The swarm automatically creates workspace directories and generates unique file names using UUIDs and timestamps to prevent file conflicts. | +| **Error Handling** | The `run` method includes try-catch error handling and logging. Check the logs for detailed error information if execution fails. | +| **Metadata Tracking** | All task executions are tracked with timestamps, agent names, tasks, and results. This data is available in both the return value and saved files. | +| **Flexible Task Assignment** | You can either provide a single task for all agents or use CSV configuration to assign different tasks to different agents. | + +## CSV File Format + +When using CSV-based agent configuration, the file should have the following columns: + +| Column | Required | Description | Default Value | +|--------|----------|-------------|---------------| +| `agent_name` | Yes | Unique name for the agent | - | +| `description` | Yes | Description of the agent's purpose | - | +| `system_prompt` | Yes | System prompt for the agent | - | +| `task` | Yes | Task to be executed by the agent | - | +| `model_name` | No | Model to use for the agent | `"openai/gpt-4o"` | +| `docs` | No | Documentation for the agent | `""` | +| `max_loops` | No | Maximum loops for the agent | `1` | +| `user_name` | No | Username for the agent | `"user"` | +| `stopping_token` | No | Token to stop agent execution | `None` | + +## Return Value Structure + +The `run` method returns a dictionary with the following structure: + +```python +{ + "run_id": str, # Unique identifier for this run + "name": str, # Name of the swarm + "description": str, # Description of the swarm + "start_time": str, # ISO timestamp of start time + "end_time": str, # ISO timestamp of end time + "tasks_completed": int, # Number of tasks completed + "number_of_agents": int, # Number of agents in the swarm + "outputs": List[Dict] # List of task outputs with agent_name, task, result, timestamp +} +``` --- diff --git a/docs/swarms/utils/fallback_models.md b/docs/swarms/utils/fallback_models.md new file mode 100644 index 00000000..17a278b4 --- /dev/null +++ b/docs/swarms/utils/fallback_models.md @@ -0,0 +1,279 @@ +# Fallback Models in Swarms Agent + +The Swarms Agent now supports automatic fallback to alternative models when the primary model fails. This feature enhances reliability and ensures your agents can continue operating even when specific models are unavailable or experiencing issues. + +## Overview + +The fallback model system allows you to specify one or more alternative models that will be automatically tried if the primary model encounters an error. This is particularly useful for: + +- **High availability**: Ensure your agents continue working even if a specific model is down +- **Cost optimization**: Use cheaper models as fallbacks for non-critical tasks +- **Rate limiting**: Switch to alternative models when hitting rate limits +- **Model-specific issues**: Handle temporary model-specific problems + +## Configuration + +### Single Fallback Model + +```python +from swarms import Agent + +# Configure a single fallback model +agent = Agent( + model_name="gpt-4o", # Primary model + fallback_model_name="gpt-4o-mini", # Fallback model + max_loops=1 +) +``` + +### Multiple Fallback Models + +```python +from swarms import Agent + +# Configure multiple fallback models using unified list +agent = Agent( + fallback_models=["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"], # First is primary, rest are fallbacks + max_loops=1 +) +``` + +### Combined Configuration + +```python +from swarms import Agent + +# You can use both single fallback and fallback list +agent = Agent( + model_name="gpt-4o", # Primary model + fallback_model_name="gpt-4o-mini", # Single fallback + fallback_models=["gpt-3.5-turbo", "claude-3-haiku"], # Additional fallbacks + max_loops=1 +) + +# Or use the unified list approach (recommended) +agent = Agent( + fallback_models=["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo", "claude-3-haiku"], + max_loops=1 +) +# Final order: gpt-4o -> gpt-4o-mini -> gpt-3.5-turbo -> claude-3-haiku +``` + +## How It Works + +1. **Primary Model**: The agent starts with the specified primary model +2. **Error Detection**: When an LLM call fails, the system catches the error +3. **Automatic Switching**: The agent automatically switches to the next available model +4. **Retry**: The failed operation is retried with the new model +5. **Exhaustion**: If all models fail, the original error is raised + +## API Reference + +### Constructor Parameters + +- `fallback_model_name` (str, optional): Single fallback model name +- `fallback_models` (List[str], optional): List of fallback model names + +### Methods + +#### `get_available_models() -> List[str]` +Returns the complete list of available models in order of preference. + +```python +models = agent.get_available_models() +print(models) # ['gpt-4o', 'gpt-4o-mini', 'gpt-3.5-turbo'] +``` + +#### `get_current_model() -> str` +Returns the currently active model name. + +```python +current = agent.get_current_model() +print(current) # 'gpt-4o' +``` + +#### `is_fallback_available() -> bool` +Checks if fallback models are configured. + +```python +has_fallback = agent.is_fallback_available() +print(has_fallback) # True +``` + +#### `switch_to_next_model() -> bool` +Manually switch to the next available model. Returns `True` if successful, `False` if no more models available. + +```python +success = agent.switch_to_next_model() +if success: + print(f"Switched to: {agent.get_current_model()}") +else: + print("No more models available") +``` + +#### `reset_model_index()` +Reset to the primary model. + +```python +agent.reset_model_index() +print(agent.get_current_model()) # Back to primary model +``` + +## Examples + +### Basic Usage + +```python +from swarms import Agent + +# Create agent with fallback models +agent = Agent( + model_name="gpt-4o", + fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"], + max_loops=1 +) + +# Run a task - will automatically use fallbacks if needed +response = agent.run("Write a short story about AI") +print(response) +``` + +### Monitoring Model Usage + +```python +from swarms import Agent + +agent = Agent( + model_name="gpt-4o", + fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"], + max_loops=1 +) + +print(f"Available models: {agent.get_available_models()}") +print(f"Current model: {agent.get_current_model()}") + +# Run task +response = agent.run("Analyze this data") + +# Check if fallback was used +if agent.get_current_model() != "gpt-4o": + print(f"Used fallback model: {agent.get_current_model()}") +``` + +### Manual Model Switching + +```python +from swarms import Agent + +agent = Agent( + model_name="gpt-4o", + fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"], + max_loops=1 +) + +# Manually switch models +print(f"Starting with: {agent.get_current_model()}") + +agent.switch_to_next_model() +print(f"Switched to: {agent.get_current_model()}") + +agent.switch_to_next_model() +print(f"Switched to: {agent.get_current_model()}") + +# Reset to primary +agent.reset_model_index() +print(f"Reset to: {agent.get_current_model()}") +``` + +## Error Handling + +The fallback system handles various types of errors: + +- **API Errors**: Rate limits, authentication issues +- **Model Errors**: Model-specific failures +- **Network Errors**: Connection timeouts, network issues +- **Configuration Errors**: Invalid model names, unsupported features + +### Error Logging + +The system provides detailed logging when fallbacks are used: + +``` +WARNING: Agent 'my-agent' switching to fallback model: gpt-4o-mini (attempt 2/3) +INFO: Retrying with fallback model 'gpt-4o-mini' for agent 'my-agent' +``` + +## Best Practices + +### 1. Model Selection +- Choose fallback models that are compatible with your use case +- Consider cost differences between models +- Ensure fallback models support the same features (e.g., function calling, vision) + +### 2. Order Matters +- Place most reliable models first +- Consider cost-performance trade-offs +- Test fallback models to ensure they work for your tasks + +### 3. Monitoring +- Monitor which models are being used +- Track fallback usage patterns +- Set up alerts for excessive fallback usage + +### 4. Error Handling +- Implement proper error handling in your application +- Consider graceful degradation when all models fail +- Log fallback usage for analysis + +## Limitations + +1. **Model Compatibility**: Fallback models must be compatible with your use case +2. **Feature Support**: Not all models support the same features (e.g., function calling, vision) +3. **Cost Implications**: Different models have different pricing +4. **Performance**: Fallback models may have different performance characteristics + +## Troubleshooting + +### Common Issues + +1. **All Models Failing**: Check API keys and network connectivity +2. **Feature Incompatibility**: Ensure fallback models support required features +3. **Rate Limiting**: Consider adding delays between model switches +4. **Configuration Errors**: Verify model names are correct + +### Debug Mode + +Enable verbose logging to see detailed fallback information: + +```python +agent = Agent( + model_name="gpt-4o", + fallback_models=["gpt-4o-mini"], + verbose=True # Enable detailed logging +) +``` + +## Migration Guide + +### From No Fallback to Fallback + +If you're upgrading from an agent without fallback support: + +```python +# Before +agent = Agent(model_name="gpt-4o") + +# After +agent = Agent( + model_name="gpt-4o", + fallback_models=["gpt-4o-mini", "gpt-3.5-turbo"] +) +``` + +### Backward Compatibility + +The fallback system is fully backward compatible. Existing agents will continue to work without any changes. + +## Conclusion + +The fallback model system provides a robust way to ensure your Swarms agents remain operational even when individual models fail. By configuring appropriate fallback models, you can improve reliability, handle rate limits, and optimize costs while maintaining the same simple API. diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 00000000..d5b7b150 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,70 @@ +# Swarms Examples + +This directory contains comprehensive examples demonstrating various capabilities and use cases of the Swarms framework. Each subdirectory focuses on specific aspects of multi-agent systems, single agents, tools, and integrations. + +## 📁 Directory Overview + +### 🤖 Multi-Agent Systems +- **[multi_agent/](multi_agent/)** - Advanced multi-agent patterns including agent rearrangement, auto swarm builder (ASB), batched workflows, board of directors, caching, concurrent processing, councils, debates, elections, forest swarms, graph workflows, group chats, heavy swarms, hierarchical swarms, majority voting, and orchestration examples. + +### 👤 Single Agent Systems +- **[single_agent/](single_agent/)** - Single agent implementations including demos, external agent integrations, LLM integrations (Azure, Claude, DeepSeek, Mistral, OpenAI, Qwen), onboarding, RAG, reasoning agents, tools integration, utils, and vision capabilities. + +### 🛠️ Tools & Integrations +- **[tools/](tools/)** - Tool integration examples including agent-as-tools, base tool implementations, browser automation, Claude integration, Exa search, Firecrawl, multi-tool usage, and Stagehand integration. + +### 🎯 Model Integrations +- **[models/](models/)** - Various model integrations including Cerebras, GPT-5, GPT-OSS, Llama 4, Lumo, Ollama, and VLLM implementations. + +### 🔌 API & Protocols +- **[swarms_api_examples/](swarms_api_examples/)** - Swarms API usage examples including agent overview, batch processing, client integration, team examples, analysis, and rate limiting. + +- **[mcp/](mcp/)** - Model Context Protocol (MCP) integration examples including agent implementations, multi-connection setups, server configurations, and utility functions. + +### 🧠 Advanced Capabilities +- **[reasoning_agents/](reasoning_agents/)** - Advanced reasoning capabilities including agent judge evaluation systems and O3 model integration. + +- **[rag/](rag/)** - Retrieval Augmented Generation (RAG) implementations with vector database integrations. + +### 📚 Guides & Tutorials +- **[guides/](guides/)** - Comprehensive guides and tutorials including generation length blog, geo guesser agent, graph workflow guide, hierarchical marketing team, nano banana Jarvis agent, smart database, and web scraper agents. + +### 🎪 Demonstrations +- **[demos/](demos/)** - Domain-specific demonstrations across various industries including apps, charts, crypto, CUDA, finance, hackathon projects, insurance, legal, medical, news, privacy, real estate, science, and synthetic data generation. + +### 🚀 Deployment +- **[deployment/](deployment/)** - Deployment strategies and patterns including cron job implementations and FastAPI deployment examples. + +### 🛠️ Utilities +- **[utils/](utils/)** - Utility functions and helper implementations including agent loader, communication examples, concurrent wrappers, miscellaneous utilities, and telemetry. + +### 🎓 Educational +- **[workshops/](workshops/)** - Workshop examples and educational sessions including agent tools, batched grids, geo guesser, and Jarvis agent implementations. + +### 🖥️ User Interface +- **[ui/](ui/)** - User interface examples and implementations including chat interfaces. + +## 🚀 Quick Start + +1. **New to Swarms?** Start with [single_agent/simple_agent.py](single_agent/simple_agent.py) for basic concepts +2. **Want multi-agent workflows?** Check out [multi_agent/duo_agent.py](multi_agent/duo_agent.py) +3. **Need tool integration?** Explore [tools/agent_as_tools.py](tools/agent_as_tools.py) +4. **Looking for guides?** Visit [guides/](guides/) for comprehensive tutorials + +## 📖 Documentation + +Each subdirectory contains its own README.md file with detailed descriptions and links to all available examples. Click on any folder above to explore its specific examples and use cases. + +## 🔗 Related Resources + +- [Main Swarms Documentation](../docs/) +- [API Reference](../swarms/) +- [Contributing Guidelines](../CONTRIBUTING.md) + +## 💡 Contributing + +Found an interesting example or want to add your own? Check out our [contributing guidelines](../CONTRIBUTING.md) and feel free to submit pull requests with new examples or improvements to existing ones. + +--- + +*This examples directory is continuously updated with new patterns, integrations, and use cases. Check back regularly for the latest examples!* diff --git a/examples/demos/README.md b/examples/demos/README.md new file mode 100644 index 00000000..1fbccc7d --- /dev/null +++ b/examples/demos/README.md @@ -0,0 +1,85 @@ +# Demo Examples + +This directory contains comprehensive demonstration examples showcasing various Swarms capabilities across different domains. + +## Apps +- [smart_database_swarm.py](apps/smart_database_swarm.py) - Intelligent database management swarm + +## Charts +- [chart_swarm.py](chart_swarm.py) - Data visualization and chart generation + +## Crypto +- [dao_swarm.py](crypto/dao_swarm.py) - Decentralized Autonomous Organization swarm +- [ethchain_agent.py](crypto/ethchain_agent.py) - Ethereum blockchain agent +- [htx_swarm.py](crypto/htx_swarm.py) - HTX exchange integration +- [swarms_coin_agent.py](crypto/swarms_coin_agent.py) - Swarms coin trading agent +- [swarms_coin_multimarket.py](crypto/swarms_coin_multimarket.py) - Multi-market trading + +## CUDA +- [cuda_swarm.py](cuda_swarm.py) - GPU-accelerated swarm processing + +## Finance +- [sentiment_news_analysis.py](finance/sentiment_news_analysis.py) - Financial sentiment analysis +- [swarms_of_vllm.py](finance/swarms_of_vllm.py) - VLLM-based financial swarms + +## Hackathon Examples +- [fraud.py](hackathon_feb16/fraud.py) - Fraud detection system +- [sarasowti.py](hackathon_feb16/sarasowti.py) - Sarasowti project implementation + +## Insurance +- [insurance_swarm.py](insurance/insurance_swarm.py) - Insurance processing swarm + +## Legal +- [legal_swarm.py](legal/legal_swarm.py) - Legal document processing swarm + +## Medical +- [health_privacy_swarm.py](medical/health_privacy_swarm.py) - Health privacy compliance swarm +- [health_privacy_swarm_two.py](medical/health_privacy_swarm_two.py) - Alternative health privacy implementation +- [medical_coder_agent.py](medical/medical_coder_agent.py) - Medical coding agent +- [new_medical_rearrange.py](medical/new_medical_rearrange.py) - Medical rearrangement system +- [ollama_demo.py](medical/ollama_demo.py) - Ollama integration demo + +### Medical Analysis Reports +- [medical_analysis_agent_rearrange.md](medical/medical_analysis_agent_rearrange.md) - Analysis report +- [medical_coding_report.md](medical/medical_coding_report.md) - Coding report +- [medical_diagnosis_report.md](medical/medical_diagnosis_report.md) - Diagnosis report + +### Rearrange Video Examples +- [term_sheet_swarm.py](medical/rearrange_video_examples/term_sheet_swarm.py) - Term sheet processing +- [reports/](medical/rearrange_video_examples/reports/) - Analysis reports + +## News +- [news_aggregator_summarizer.py](news_aggregator_summarizer.py) - News aggregation and summarization + +## Privacy +- [privacy_building.py](privacy_building.py) - Privacy-focused system building + +## Real Estate +- [morgtate_swarm.py](real_estate/morgtate_swarm.py) - Mortgage processing swarm +- [real_estate_agent.py](real_estate/real_estate_agent.py) - Real estate agent +- [realtor_agent.py](real_estate/realtor_agent.py) - Realtor agent +- [README_realtor.md](real_estate/README_realtor.md) - Realtor documentation + +## Science +- [materials_science_agents.py](science/materials_science_agents.py) - Materials science research agents +- [open_scientist.py](science/open_scientist.py) - Open science research agent +- [paper_idea_agent.py](science/paper_idea_agent.py) - Research paper idea generation +- [paper_idea_profile.py](science/paper_idea_profile.py) - Paper idea profiling + +## Spike Examples +- [agent_rearrange_test.py](spike/agent_rearrange_test.py) - Agent rearrangement testing +- [function_caller_example.py](spike/function_caller_example.py) - Function calling example +- [memory.py](spike/memory.py) - Memory management +- [test.py](spike/test.py) - Testing utilities +- [spike.zip](spike/spike.zip) - Spike examples archive + +## Synthetic Data +- [profession_sim/](synthetic_data/profession_sim/) - Professional persona simulation + - [convert_json_to_csv.py](synthetic_data/profession_sim/convert_json_to_csv.py) - Data format conversion + - [data.csv](synthetic_data/profession_sim/data.csv) - Sample data + - [format_prompt.py](synthetic_data/profession_sim/format_prompt.py) - Prompt formatting + - [profession_persona_generator.py](synthetic_data/profession_sim/profession_persona_generator.py) - Persona generation + - Various CSV and JSON files with generated personas and progress tracking + +## Additional Files +- [agent_with_fluidapi.py](agent_with_fluidapi.py) - FluidAPI integration example diff --git a/examples/deployment/README.md b/examples/deployment/README.md new file mode 100644 index 00000000..60f44a7e --- /dev/null +++ b/examples/deployment/README.md @@ -0,0 +1,18 @@ +# Deployment Examples + +This directory contains examples demonstrating various deployment strategies and patterns for Swarms applications. + +## Cron Job Examples +- [callback_cron_example.py](cron_job_examples/callback_cron_example.py) - Callback-based cron jobs +- [cron_job_example.py](cron_job_examples/cron_job_example.py) - Basic cron job implementation +- [cron_job_figma_stock_swarms_tools_example.py](cron_job_examples/cron_job_figma_stock_swarms_tools_example.py) - Figma stock tools cron job +- [crypto_concurrent_cron_example.py](cron_job_examples/crypto_concurrent_cron_example.py) - Concurrent crypto cron job +- [figma_stock_example.py](cron_job_examples/figma_stock_example.py) - Figma stock example +- [simple_callback_example.py](cron_job_examples/simple_callback_example.py) - Simple callback example +- [simple_concurrent_crypto_cron.py](cron_job_examples/simple_concurrent_crypto_cron.py) - Simple concurrent crypto cron +- [solana_price_tracker.py](cron_job_examples/solana_price_tracker.py) - Solana price tracking cron job + +## FastAPI +- [fastapi_agent_api_example.py](fastapi/fastapi_agent_api_example.py) - FastAPI agent API implementation +- [README.md](fastapi/README.md) - FastAPI documentation +- [requirements.txt](fastapi/requirements.txt) - FastAPI dependencies diff --git a/examples/guides/README.md b/examples/guides/README.md new file mode 100644 index 00000000..a01158c1 --- /dev/null +++ b/examples/guides/README.md @@ -0,0 +1,39 @@ +# Guides + +This directory contains comprehensive guides and tutorials for using Swarms effectively. + +## Generation Length Blog +- [longform_generator.py](generation_length_blog/longform_generator.py) - Long-form content generation +- [universal_api.py](generation_length_blog/universal_api.py) - Universal API implementation + +## Geo Guesser Agent +- [geo_guesser_agent.py](geo_guesser_agent/geo_guesser_agent.py) - Geographic location guessing agent +- [miami.jpg](geo_guesser_agent/miami.jpg) - Sample Miami image +- [README.md](geo_guesser_agent/README.md) - Geo guesser documentation + +## Graph Workflow Guide +- [comprehensive_demo.py](graphworkflow_guide/comprehensive_demo.py) - Comprehensive graph workflow demo +- [GETTING_STARTED.md](graphworkflow_guide/GETTING_STARTED.md) - Getting started guide +- [graph_workflow_technical_guide.md](graphworkflow_guide/graph_workflow_technical_guide.md) - Technical documentation +- [quick_start_guide.py](graphworkflow_guide/quick_start_guide.py) - Quick start implementation +- [README.md](graphworkflow_guide/README.md) - Main documentation +- [setup_and_test.py](graphworkflow_guide/setup_and_test.py) - Setup and testing utilities + +## Hierarchical Marketing Team +- [hiearchical_marketing_team.py](hiearchical_marketing_team.py) - Marketing team hierarchy example + +## Nano Banana Jarvis Agent +- [img_gen_nano_banana.py](nano_banana_jarvis_agent/img_gen_nano_banana.py) - Image generation with Nano Banana +- [jarvis_agent.py](nano_banana_jarvis_agent/jarvis_agent.py) - Jarvis AI assistant implementation +- [image.jpg](nano_banana_jarvis_agent/image.jpg) - Sample image +- [building.jpg](nano_banana_jarvis_agent/building.jpg) - Building image +- [hk.jpg](nano_banana_jarvis_agent/hk.jpg) - Hong Kong image +- [miami.jpg](nano_banana_jarvis_agent/miami.jpg) - Miami image +- [annotated_images/](nano_banana_jarvis_agent/annotated_images/) - Collection of annotated images for training/testing + +## Smart Database +- [README.md](smart_database/README.md) - Smart database documentation + +## Web Scraper Agents +- [batched_scraper_agent.py](web_scraper_agents/batched_scraper_agent.py) - Batch web scraping agent +- [web_scraper_agent.py](web_scraper_agents/web_scraper_agent.py) - Basic web scraping agent diff --git a/examples/mcp/README.md b/examples/mcp/README.md new file mode 100644 index 00000000..d6737c02 --- /dev/null +++ b/examples/mcp/README.md @@ -0,0 +1,43 @@ +# MCP (Model Context Protocol) Examples + +This directory contains examples demonstrating MCP integration and usage patterns in Swarms. + +## Agent Examples +- [agent_mcp_old.py](agent_examples/agent_mcp_old.py) - Legacy MCP agent implementation +- [agent_multi_mcp_connections.py](agent_examples/agent_multi_mcp_connections.py) - Multi-connection MCP agent +- [agent_tools_dict_example.py](agent_examples/agent_tools_dict_example.py) - Agent tools dictionary example +- [mcp_exampler.py](agent_examples/mcp_exampler.py) - MCP example implementation + +## MCP Agent Tool +- [mcp_agent_tool.py](mcp_agent_tool.py) - Core MCP agent tool implementation + +## MCP Utils +- [client.py](mcp_utils/client.py) - MCP client implementation +- [mcp_client_call.py](mcp_utils/mcp_client_call.py) - Client call examples +- [mcp_multiple_servers_example.py](mcp_utils/mcp_multiple_servers_example.py) - Multiple server connections +- [multiagent_client.py](mcp_utils/multiagent_client.py) - Multi-agent client +- [singleagent_client.py](mcp_utils/singleagent_client.py) - Single agent client +- [test_multiple_mcp_servers.py](mcp_utils/test_multiple_mcp_servers.py) - Multi-server testing + +### Utils Subdirectory +- [find_tools_on_mcp.py](mcp_utils/utils/find_tools_on_mcp.py) - Tool discovery on MCP +- [mcp_execute_example.py](mcp_utils/utils/mcp_execute_example.py) - MCP execution examples +- [mcp_load_tools_example.py](mcp_utils/utils/mcp_load_tools_example.py) - Tool loading examples +- [mcp_multiserver_tool_fetch.py](mcp_utils/utils/mcp_multiserver_tool_fetch.py) - Multi-server tool fetching + +## Multi-MCP Examples +- [multi_mcp_example.py](multi_mcp_example.py) - Multi-MCP integration example + +## Multi-MCP Guide +- [agent_mcp.py](multi_mcp_guide/agent_mcp.py) - MCP agent implementation +- [mcp_agent_tool.py](multi_mcp_guide/mcp_agent_tool.py) - MCP agent tool +- [okx_crypto_server.py](multi_mcp_guide/okx_crypto_server.py) - OKX crypto server integration + +## Servers +- [mcp_agent_tool.py](servers/mcp_agent_tool.py) - Server-side MCP agent tool +- [mcp_test.py](servers/mcp_test.py) - MCP server testing +- [okx_crypto_server.py](servers/okx_crypto_server.py) - OKX crypto server +- [test.py](servers/test.py) - Server testing utilities + +## Utilities +- [utils.py](utils.py) - General MCP utilities diff --git a/examples/multi_agent/README.md b/examples/multi_agent/README.md new file mode 100644 index 00000000..53fcc202 --- /dev/null +++ b/examples/multi_agent/README.md @@ -0,0 +1,151 @@ +# Multi-Agent Examples + +This directory contains comprehensive examples demonstrating various multi-agent patterns and workflows in Swarms. + +## Agent Rearrangement +- [rearrange_test.py](agent_rearrange_examples/rearrange_test.py) - Test agent rearrangement functionality + +## Auto Swarm Builder (ASB) +- [agents_builder.py](asb/agents_builder.py) - Core agent builder functionality +- [asb_research.py](asb/asb_research.py) - Research-focused ASB implementation +- [auto_agent.py](asb/auto_agent.py) - Automated agent creation +- [auto_swarm_builder_example.py](asb/auto_swarm_builder_example.py) - Complete ASB example +- [auto_swarm_builder_test.py](asb/auto_swarm_builder_test.py) - ASB testing suite +- [auto_swarm_router.py](asb/auto_swarm_router.py) - Router for auto-generated swarms +- [content_creation_asb.py](asb/content_creation_asb.py) - Content creation with ASB + +## Batched Grid Workflow +- [batched_grid_advanced_example.py](batched_grid_workflow/batched_grid_advanced_example.py) - Advanced batched grid workflow +- [batched_grid_simple_example.py](batched_grid_workflow/batched_grid_simple_example.py) - Simple batched grid example +- [batched_grid_swarm_router.py](batched_grid_workflow/batched_grid_swarm_router.py) - Router for batched grid swarms +- [batched_grid_workflow_example.py](batched_grid_workflow/batched_grid_workflow_example.py) - Complete workflow example +- [README.md](batched_grid_workflow/README.md) - Detailed documentation + +## Board of Directors +- [board_of_directors_example.py](board_of_directors/board_of_directors_example.py) - Full board simulation +- [minimal_board_example.py](board_of_directors/minimal_board_example.py) - Minimal board setup +- [simple_board_example.py](board_of_directors/simple_board_example.py) - Simple board example + +## Caching Examples +- [example_multi_agent_caching.py](caching_examples/example_multi_agent_caching.py) - Multi-agent caching implementation +- [quick_start_agent_caching.py](caching_examples/quick_start_agent_caching.py) - Quick start guide for caching +- [test_simple_agent_caching.py](caching_examples/test_simple_agent_caching.py) - Simple caching tests + +## Concurrent Examples +- [asi.py](concurrent_examples/asi.py) - ASI (Artificial Super Intelligence) example +- [concurrent_example_dashboard.py](concurrent_examples/concurrent_example_dashboard.py) - Dashboard for concurrent workflows +- [concurrent_example.py](concurrent_examples/concurrent_example.py) - Basic concurrent execution +- [concurrent_mix.py](concurrent_examples/concurrent_mix.py) - Mixed concurrent patterns +- [concurrent_swarm_example.py](concurrent_examples/concurrent_swarm_example.py) - Concurrent swarm execution +- [streaming_concurrent_workflow.py](concurrent_examples/streaming_concurrent_workflow.py) - Streaming with concurrency +- [streaming_callback/](concurrent_examples/streaming_callback/) - Streaming callback examples +- [uvloop/](concurrent_examples/uvloop/) - UVLoop integration examples + +## Council of Judges +- [council_judge_evaluation.py](council/council_judge_evaluation.py) - Judge evaluation system +- [council_judge_example.py](council/council_judge_example.py) - Basic council example +- [council_of_judges_eval.py](council/council_of_judges_eval.py) - Evaluation framework +- [council_judge_complex_example.py](council_of_judges/council_judge_complex_example.py) - Complex council setup +- [council_judge_custom_example.py](council_of_judges/council_judge_custom_example.py) - Custom council configuration + +## Debate Examples +- [debate_examples/](debate_examples/) - Various debate simulation patterns + +## Election Swarm +- [apple_board_election_example.py](election_swarm_examples/apple_board_election_example.py) - Apple board election simulation +- [election_example.py](election_swarm_examples/election_example.py) - General election example + +## Forest Swarm +- [forest_swarm_example.py](forest_swarm_examples/forest_swarm_example.py) - Forest-based swarm architecture +- [fund_manager_forest.py](forest_swarm_examples/fund_manager_forest.py) - Financial fund management forest +- [medical_forest_swarm.py](forest_swarm_examples/medical_forest_swarm.py) - Medical domain forest swarm +- [tree_example.py](forest_swarm_examples/tree_example.py) - Basic tree structure example +- [tree_swarm_test.py](forest_swarm_examples/tree_swarm_test.py) - Tree swarm testing + +## Graph Workflow +- [advanced_graph_workflow.py](graphworkflow_examples/advanced_graph_workflow.py) - Advanced graph-based workflows +- [graph_workflow_basic.py](graphworkflow_examples/graph_workflow_basic.py) - Basic graph workflow +- [graph_workflow_example.py](graphworkflow_examples/graph_workflow_example.py) - Complete graph workflow example +- [graph_workflow_validation.py](graphworkflow_examples/graph_workflow_validation.py) - Workflow validation +- [test_enhanced_json_export.py](graphworkflow_examples/test_enhanced_json_export.py) - JSON export testing +- [test_graph_workflow_caching.py](graphworkflow_examples/test_graph_workflow_caching.py) - Caching tests +- [test_graphviz_visualization.py](graphworkflow_examples/test_graphviz_visualization.py) - Visualization tests +- [test_parallel_processing_example.py](graphworkflow_examples/test_parallel_processing_example.py) - Parallel processing tests +- [graph/](graphworkflow_examples/graph/) - Core graph utilities +- [example_images/](graphworkflow_examples/example_images/) - Visualization images + +## Group Chat +- [interactive_groupchat_example.py](groupchat/interactive_groupchat_example.py) - Interactive group chat +- [quantum_physics_swarm.py](groupchat/quantum_physics_swarm.py) - Physics-focused group chat +- [random_dynamic_speaker_example.py](groupchat/random_dynamic_speaker_example.py) - Dynamic speaker selection +- [groupchat_examples/](groupchat/groupchat_examples/) - Additional group chat patterns + +## Heavy Swarm +- [heavy_swarm_example_one.py](heavy_swarm_examples/heavy_swarm_example_one.py) - First heavy swarm example +- [heavy_swarm_example.py](heavy_swarm_examples/heavy_swarm_example.py) - Main heavy swarm implementation +- [heavy_swarm_no_dashboard.py](heavy_swarm_examples/heavy_swarm_no_dashboard.py) - Heavy swarm without dashboard +- [medical_heavy_swarm_example.py](heavy_swarm_examples/medical_heavy_swarm_example.py) - Medical heavy swarm + +## Hierarchical Swarm +- [hierarchical_swarm_basic_demo.py](hiearchical_swarm/hierarchical_swarm_basic_demo.py) - Basic hierarchical demo +- [hierarchical_swarm_batch_demo.py](hiearchical_swarm/hierarchical_swarm_batch_demo.py) - Batch processing demo +- [hierarchical_swarm_comparison_demo.py](hiearchical_swarm/hierarchical_swarm_comparison_demo.py) - Comparison demo +- [hierarchical_swarm_example.py](hiearchical_swarm/hierarchical_swarm_example.py) - Main hierarchical example +- [hierarchical_swarm_streaming_demo.py](hiearchical_swarm/hierarchical_swarm_streaming_demo.py) - Streaming demo +- [hierarchical_swarm_streaming_example.py](hiearchical_swarm/hierarchical_swarm_streaming_example.py) - Streaming example +- [hs_interactive.py](hiearchical_swarm/hs_interactive.py) - Interactive hierarchical swarm +- [hs_stock_team.py](hiearchical_swarm/hs_stock_team.py) - Stock trading team +- [hybrid_hiearchical_swarm.py](hiearchical_swarm/hybrid_hiearchical_swarm.py) - Hybrid approach +- [sector_analysis_hiearchical_swarm.py](hiearchical_swarm/sector_analysis_hiearchical_swarm.py) - Sector analysis +- [hiearchical_examples/](hiearchical_swarm/hiearchical_examples/) - Additional hierarchical examples +- [hiearchical_swarm_ui/](hiearchical_swarm/hiearchical_swarm_ui/) - UI components +- [hscf/](hiearchical_swarm/hscf/) - Hierarchical framework examples + +## Interactive Group Chat +- [interactive_groupchat_speaker_example.py](interactive_groupchat_examples/interactive_groupchat_speaker_example.py) - Speaker management +- [medical_panel_example.py](interactive_groupchat_examples/medical_panel_example.py) - Medical panel discussion +- [speaker_function_examples.py](interactive_groupchat_examples/speaker_function_examples.py) - Speaker function examples +- [stream_example.py](interactive_groupchat_examples/stream_example.py) - Streaming example + +## Majority Voting +- [majority_voting_example_new.py](majority_voting/majority_voting_example_new.py) - Updated voting example +- [majority_voting_example.py](majority_voting/majority_voting_example.py) - Basic voting example +- [snake_game_code_voting.py](majority_voting/snake_game_code_voting.py) - Game code voting + +## MAR (Multi-Agent Reinforcement) +- [mar/](mar/) - Multi-agent reinforcement learning examples + +## MOA Examples +- [moa_examples/](moa_examples/) - Multi-objective agent examples + +## Spreadsheet Examples +- [new_spreadsheet_new_examples/](new_spreadsheet_new_examples/) - Latest spreadsheet integrations +- [new_spreadsheet_swarm_examples/](new_spreadsheet_swarm_examples/) - Spreadsheet swarm examples + +## Orchestration +- [orchestration_examples/](orchestration_examples/) - Workflow orchestration patterns + +## Paper Implementations +- [paper_implementations/](paper_implementations/) - Academic paper implementations + +## Sequential Workflow +- [sequential_workflow/](sequential_workflow/) - Sequential processing examples + +## Simulations +- [simulations/](simulations/) - Various simulation scenarios + +## Swarm Router +- [swarm_router/](swarm_router/) - Routing and load balancing + +## Swarm Arrange +- [swarmarrange/](swarmarrange/) - Agent arrangement utilities + +## Swarms API +- [swarms_api_examples/](swarms_api_examples/) - API integration examples + +## Utils +- [utils/](utils/) - Utility functions and helpers + +## Additional Files +- [duo_agent.py](duo_agent.py) - Two-agent collaboration +- [enhanced_collaboration_example.py](enhanced_collaboration_example.py) - Enhanced collaboration patterns diff --git a/examples/multi_agent/agent_rearrange_examples/rearrange_test.py b/examples/multi_agent/agent_rearrange_examples/rearrange_test.py new file mode 100644 index 00000000..de8c9e52 --- /dev/null +++ b/examples/multi_agent/agent_rearrange_examples/rearrange_test.py @@ -0,0 +1,86 @@ +from swarms import Agent, AgentRearrange + +# Define all prompts as strings before agent initializations +boss_agent_prompt = """ +You are the BossAgent responsible for managing and overseeing a swarm of agents analyzing company expenses. +Your job is to dynamically assign tasks, prioritize their execution, and ensure that all agents collaborate efficiently. +After receiving a report on the company's expenses, you will break down the work into smaller tasks, +assigning specific tasks to each agent, such as detecting recurring high costs, categorizing expenditures, +and identifying unnecessary transactions. Ensure the results are communicated back in a structured way +so the finance team can take actionable steps to cut off unproductive spending. You also monitor and +dynamically adapt the swarm to optimize their performance. Finally, you summarize their findings +into a coherent report. +""" + +expense_analyzer_prompt = """ +Your task is to carefully analyze the company's expense data provided to you. +You will focus on identifying high-cost recurring transactions, categorizing expenditures +(e.g., marketing, operations, utilities, etc.), and flagging areas where there seems to be excessive spending. +You will provide a detailed breakdown of each category, along with specific recommendations for cost-cutting. +Pay close attention to monthly recurring subscriptions, office supplies, and non-essential expenditures. +""" + +summary_generator_prompt = """ +After receiving the detailed breakdown from the ExpenseAnalyzer, +your task is to create a concise summary of the findings. You will focus on the most actionable insights, +such as highlighting the specific transactions that can be immediately cut off and summarizing the areas +where the company is overspending. Your summary will be used by the BossAgent to generate the final report. +Be clear and to the point, emphasizing the urgency of cutting unnecessary expenses. +""" + +# Swarm-Level Prompt (Collaboration Prompt) +swarm_prompt = """ +As a swarm, your collective goal is to analyze the company's expenses and identify transactions that should be cut off. +You will work collaboratively to break down the entire process of expense analysis into manageable steps. +The BossAgent will direct the flow and assign tasks dynamically to the agents. The ExpenseAnalyzer will first +focus on breaking down the expense report, identifying high-cost recurring transactions, categorizing them, +and providing recommendations for potential cost reduction. After the analysis, the SummaryGenerator will then +consolidate all the findings into an actionable summary that the finance team can use to immediately cut off unnecessary expenses. +Together, your collaboration is essential to streamlining and improving the company's financial health. +""" + +# Initialize the boss agent (Director) +boss_agent = Agent( + agent_name="BossAgent", + system_prompt=boss_agent_prompt, + max_loops=1, +) + +# Initialize worker 1: Expense Analyzer +worker1 = Agent( + agent_name="ExpenseAnalyzer", + system_prompt=expense_analyzer_prompt, + max_loops=1, + dashboard=False, +) + +# Initialize worker 2: Summary Generator +worker2 = Agent( + agent_name="SummaryGenerator", + system_prompt=summary_generator_prompt, + max_loops=1, +) + +# Create a list of agents +agents = [boss_agent, worker1, worker2] + +# Define the flow pattern for the swarm +flow = "BossAgent -> ExpenseAnalyzer, SummaryGenerator" + +# Using AgentRearrange class to manage the swarm +agent_system = AgentRearrange(agents=agents, flow=flow) + +# Input task for the swarm +task = f""" + + {swarm_prompt} + + The company has been facing a rising number of unnecessary expenses, and the finance team needs a detailed + analysis of recent transactions to identify which expenses can be cut off to improve profitability. + Analyze the provided transaction data and create a detailed report on cost-cutting opportunities, + focusing on recurring transactions and non-essential expenditures. +""" + +# Run the swarm system with the task +output = agent_system.run(task) +print(output) diff --git a/heavy_swarm_example.py b/examples/multi_agent/heavy_swarm_examples/heavy_swarm_example.py similarity index 100% rename from heavy_swarm_example.py rename to examples/multi_agent/heavy_swarm_examples/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/examples/multi_agent/majority_voting/_doda_majority_voting_example_new.py b/examples/multi_agent/majority_voting/_doda_majority_voting_example_new.py new file mode 100644 index 00000000..9989a557 --- /dev/null +++ b/examples/multi_agent/majority_voting/_doda_majority_voting_example_new.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/multi_agent/mar/multi_agent_router_example.py b/examples/multi_agent/mar/multi_agent_router_example.py index 9113ada4..e6bdae29 100644 --- a/examples/multi_agent/mar/multi_agent_router_example.py +++ b/examples/multi_agent/mar/multi_agent_router_example.py @@ -1,42 +1,31 @@ -from swarms import Agent, MultiAgentRouter +from swarms.structs.agent import Agent +from swarms.structs.multi_agent_router import MultiAgentRouter # Example usage: -if __name__ == "__main__": - # Define some example agents - agents = [ - Agent( - agent_name="ResearchAgent", - description="Specializes in researching topics and providing detailed, factual information", - system_prompt="You are a research specialist. Provide detailed, well-researched information about any topic, citing sources when possible.", - model_name="openai/gpt-4o", - ), - Agent( - agent_name="CodeExpertAgent", - description="Expert in writing, reviewing, and explaining code across multiple programming languages", - system_prompt="You are a coding expert. Write, review, and explain code with a focus on best practices and clean code principles.", - model_name="openai/gpt-4o", - ), - Agent( - agent_name="WritingAgent", - description="Skilled in creative and technical writing, content creation, and editing", - system_prompt="You are a writing specialist. Create, edit, and improve written content while maintaining appropriate tone and style.", - model_name="openai/gpt-4o", - ), - ] +agents = [ + Agent( + agent_name="ResearchAgent", + agent_description="Specializes in researching topics and providing detailed, factual information", + system_prompt="You are a research specialist. Provide detailed, well-researched information about any topic, citing sources when possible.", + ), + Agent( + agent_name="CodeExpertAgent", + agent_description="Expert in writing, reviewing, and explaining code across multiple programming languages", + system_prompt="You are a coding expert. Write, review, and explain code with a focus on best practices and clean code principles.", + ), + Agent( + agent_name="WritingAgent", + agent_description="Skilled in creative and technical writing, content creation, and editing", + system_prompt="You are a writing specialist. Create, edit, and improve written content while maintaining appropriate tone and style.", + ), +] - # Initialize routers with different configurations - router_execute = MultiAgentRouter( - agents=agents, execute_task=True - ) +# Initialize routers with different configurations +router_execute = MultiAgentRouter( + agents=agents, temperature=0.5, model="claude-sonnet-4-20250514" +) - # Example task - task = "Write a Python function to calculate fibonacci numbers" - - try: - # Process the task with execution - print("\nWith task execution:") - result_execute = router_execute.route_task(task) - print(result_execute) - - except Exception as e: - print(f"Error occurred: {str(e)}") +# Example task: Remake the Fibonacci task +task = "Use all the agents available to you to remake the Fibonacci function in Python, providing both an explanation and code." +result_execute = router_execute.run(task) +print(result_execute) diff --git a/examples/multi_agent/mixture_of_agents_example.py b/examples/multi_agent/moa_examples/mixture_of_agents_example.py similarity index 100% rename from examples/multi_agent/mixture_of_agents_example.py rename to examples/multi_agent/moa_examples/mixture_of_agents_example.py diff --git a/examples/multi_agent/new_spreadsheet_new_examples/agent_config_example.csv b/examples/multi_agent/new_spreadsheet_new_examples/agent_config_example.csv new file mode 100644 index 00000000..1b02f7cf --- /dev/null +++ b/examples/multi_agent/new_spreadsheet_new_examples/agent_config_example.csv @@ -0,0 +1,5 @@ +agent_name,description,system_prompt,task,model_name,max_loops,user_name,stopping_token +Research-Agent,Market research specialist,You are a financial research expert with 10+ years of experience,Analyze the renewable energy sector growth trends and identify top investment opportunities,claude-sonnet-4-20250514,1,user, +Technical-Agent,Technical analysis expert,You are a technical trading analyst specializing in chart patterns and indicators,Identify key technical indicators for energy stocks and provide trading signals,claude-sonnet-4-20250514,1,user, +Risk-Agent,Risk management specialist,You are a risk assessment expert focused on portfolio optimization,Evaluate portfolio diversification strategies for energy investments and assess risk levels,claude-sonnet-4-20250514,1,user, +Data-Agent,Data analysis specialist,You are a data scientist specializing in financial data analysis,Extract and analyze key financial metrics from energy sector companies,claude-sonnet-4-20250514,1,user, diff --git a/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_run_id_02575aa12829486c91967c24b927100b.csv b/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_run_id_02575aa12829486c91967c24b927100b.csv new file mode 100644 index 00000000..8ddd8136 --- /dev/null +++ b/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_run_id_02575aa12829486c91967c24b927100b.csv @@ -0,0 +1,167 @@ +Run ID,Agent Name,Task,Result,Timestamp +51afd7d0-0c70-4df8-9f7b-0314cd3adedc,Research-Agent,What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.,"# Top 3 Energy Stocks for 2024 Investment Analysis + +As Research-Agent, I'll provide a comprehensive analysis of three compelling energy investment opportunities for 2024, considering current market dynamics, financial fundamentals, and strategic positioning. + +## 1. **Chevron Corporation (CVX)** + +### Investment Thesis +Chevron stands out as a premier integrated oil company with exceptional capital discipline and shareholder-friendly policies. + +### Key Strengths: +- **Financial Resilience**: Strong balance sheet with low debt-to-equity ratio (~0.15) +- **Dividend Aristocrat**: 37 consecutive years of dividend increases +- **Operational Excellence**: Industry-leading breakeven costs (~$50/barrel Brent) +- **Strategic Assets**: High-quality, low-cost production in Permian Basin and international operations + +### 2024 Catalysts: +- Permian Basin production growth (targeting 1M+ barrels/day) +- Completion of renewable diesel projects +- Potential for increased shareholder returns through buybacks +- Stable oil price environment supporting cash generation + +### Risks: +- Regulatory pressure on fossil fuel investments +- Commodity price volatility +- Energy transition headwinds + +## 2. **NextEra Energy (NEE)** + +### Investment Thesis +Leading utility with the largest renewable energy portfolio in North America, positioned for long-term energy transition benefits. + +### Key Strengths: +- **Renewable Leadership**: ~30 GW of wind and solar capacity +- **Regulated Utility Base**: Florida Power & Light provides stable cash flows +- **Growth Pipeline**: 23+ GW of renewable development projects +- **ESG Appeal**: Strong environmental credentials attracting ESG-focused capital + +### 2024 Catalysts: +- Inflation Reduction Act benefits and tax credits +- Continued renewable energy expansion +- Grid modernization investments +- Potential for premium valuation due to clean energy focus + +### Risks: +- Interest rate sensitivity due to capital-intensive nature +- Regulatory changes affecting utility operations +- Execution risk on large-scale projects + +## 3. **ConocoPhillips (COP)** + +### Investment Thesis +Pure-play E&P company with exceptional capital allocation and variable dividend policy designed for commodity cycles. + +### Key Strengths: +- **Capital Discipline**: Strict capital allocation framework +- **Variable Dividend**: Returns excess cash to shareholders based on commodity prices +- **Low-Cost Operations**: Breakeven costs among industry's lowest +- **Portfolio Quality**: Diversified, high-return asset base + +### 2024 Catalysts: +- Continued Permian Basin optimization +- Potential for significant shareholder returns if oil prices remain elevated +- Operational efficiency improvements +- Strategic asset high-grading + +### Risks: +- Pure upstream exposure to commodity volatility +- No downstream integration buffer +- Potential for reduced returns in low oil price environment + +## Investment Recommendation Summary + +**Risk-Adjusted Rankings for 2024:** + +1. **Chevron (CVX)** - Best balance of stability, growth, and shareholder returns +2. **NextEra Energy (NEE)** - Long-term energy transition play with regulatory support +3. **ConocoPhillips (COP)** - Highest potential returns but greater volatility + +## Key Considerations for 2024: + +- **Oil Price Assumptions**: Analysis assumes Brent crude averaging $75-85/barrel +- **Interest Rate Environment**: Rising rates favor traditional energy over utilities +- **Regulatory Landscape**: Continued support for renewable energy through IRA +- **Geopolitical Factors**: Energy security concerns supporting domestic production + +## Risk Management: +Consider position sizing and diversification across different energy subsectors to mitigate sector-specific risks while capturing the energy sector's potential upside in 2024. + +*Disclaimer: This analysis is for informational purposes only and should not be considered personalized investment advice. Please consult with a qualified financial advisor before making investment decisions.*",2025-09-21T21:54:12.119935 +51afd7d0-0c70-4df8-9f7b-0314cd3adedc,Technical-Agent,What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.,"I appreciate your interest in energy sector investments, but I need to clarify an important limitation: I cannot provide specific investment recommendations or advice on particular stocks to buy. + +However, I can offer you a comprehensive analytical framework for evaluating energy stocks in 2024: + +## Key Factors to Analyze When Evaluating Energy Stocks + +### 1. **Sector Diversification Analysis** +- **Traditional Oil & Gas**: Companies with strong balance sheets, efficient operations, and disciplined capital allocation +- **Renewable Energy**: Solar, wind, and energy storage companies benefiting from policy support and cost reductions +- **Energy Infrastructure**: Pipeline companies, utilities, and grid modernization players + +### 2. **Critical Evaluation Metrics** +- **Financial Health**: Debt-to-equity ratios, free cash flow generation, dividend sustainability +- **Operational Efficiency**: Production costs, refining margins, capacity utilization +- **ESG Positioning**: Environmental compliance, transition strategies, governance quality +- **Commodity Exposure**: Oil/gas price sensitivity, hedging strategies, geographic diversification + +### 3. **2024 Market Dynamics to Consider** +- **Geopolitical Factors**: Supply chain stability, regulatory changes, international tensions +- **Energy Transition**: Investment in clean technology, carbon capture, hydrogen +- **Demand Patterns**: Economic growth impacts, seasonal variations, industrial demand + +## Recommended Research Approach + +1. **Screen companies** using financial databases (Bloomberg, Reuters, company 10-K filings) +2. **Analyze peer comparisons** within specific energy subsectors +3. **Review analyst reports** from multiple investment firms +4. **Consider ETFs** for diversified energy exposure +5. **Consult with licensed financial advisors** for personalized recommendations + +Would you like me to elaborate on any specific aspect of energy sector analysis or help you develop a research methodology for evaluating potential investments?",2025-09-21T21:54:12.119935 +51afd7d0-0c70-4df8-9f7b-0314cd3adedc,Risk-Agent,What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.,"I appreciate your interest in energy sector investments, but I need to clarify an important limitation in my role as Risk-Agent. + +## Investment Advice Disclaimer + +I cannot and should not provide specific stock recommendations or investment advice. Investment decisions involve significant financial risk and should be based on: + +- Your personal financial situation +- Risk tolerance +- Investment timeline +- Professional financial advice + +## Alternative Approach: Energy Sector Analysis Framework + +Instead, I can offer you a **risk-focused analytical framework** for evaluating energy investments: + +### 1. **Sector Risk Assessment Categories** + +**Traditional Energy Risks:** +- Commodity price volatility +- Regulatory and environmental policy changes +- Geopolitical tensions affecting supply chains +- Stranded asset risks from energy transition + +**Renewable Energy Risks:** +- Technology disruption and obsolescence +- Policy dependency and subsidy changes +- Grid integration challenges +- Supply chain concentration risks + +### 2. **Key Evaluation Metrics to Consider** + +- **Financial Health**: Debt-to-equity ratios, cash flow stability +- **ESG Compliance**: Environmental regulations alignment +- **Diversification**: Geographic and energy source spread +- **Capital Allocation**: R&D investment in future technologies + +### 3. **Risk Mitigation Strategies** + +- Diversify across energy subsectors +- Consider ETFs over individual stocks +- Monitor regulatory environment changes +- Assess long-term sustainability trends + +**Recommendation**: Consult with a qualified financial advisor who can provide personalized investment guidance based on your specific circumstances and conduct proper due diligence on any potential investments. + +Would you like me to elaborate on any specific risk assessment framework for energy sector analysis?",2025-09-21T21:54:12.119935 diff --git a/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_run_id_69f4c23f5a97477ab2b8114521c33fd4.csv b/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_run_id_69f4c23f5a97477ab2b8114521c33fd4.csv new file mode 100644 index 00000000..cdf8a3ba --- /dev/null +++ b/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_run_id_69f4c23f5a97477ab2b8114521c33fd4.csv @@ -0,0 +1,241 @@ +Run ID,Agent Name,Task,Result,Timestamp +beb4819f-eca3-49d6-9b1c-4d0831911db0,Research-Agent,What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.,"I'll provide a comprehensive analysis of three strong energy sector investment opportunities for 2024, focusing on companies with solid fundamentals, strategic positioning, and growth potential. + +## Top 3 Energy Stock Recommendations for 2024 + +### 1. **Chevron Corporation (CVX)** + +**Investment Thesis:** +Chevron stands out as a premium integrated oil company with exceptional capital discipline and shareholder-friendly policies. + +**Key Strengths:** +- **Financial Fortress:** Maintains one of the strongest balance sheets in the sector with low debt-to-equity ratio +- **Dividend Aristocrat:** 36+ years of consecutive dividend increases, currently yielding ~3.2% +- **Operational Excellence:** Low-cost production assets, particularly in the Permian Basin +- **Capital Allocation:** Committed to returning 75% of free cash flow to shareholders through dividends and buybacks + +**2024 Catalysts:** +- Continued Permian Basin expansion with industry-leading breakeven costs (~$35/barrel) +- LNG project developments enhancing long-term cash flow visibility +- Potential for increased shareholder returns if oil prices remain elevated + +**Valuation:** Trading at attractive P/E multiple compared to historical averages + +### 2. **NextEra Energy (NEE)** + +**Investment Thesis:** +Leading utility with the largest renewable energy portfolio in North America, positioned to benefit from the energy transition. + +**Key Strengths:** +- **Renewable Leadership:** Largest wind and solar generator in North America +- **Regulated Utility Base:** Florida Power & Light provides stable cash flow foundation +- **Growth Pipeline:** ~$85 billion capital investment plan through 2026 +- **ESG Appeal:** Strong environmental credentials attracting ESG-focused investors + +**2024 Catalysts:** +- Inflation Reduction Act benefits boosting renewable project economics +- Grid modernization investments supporting rate base growth +- Potential for accelerated renewable development as corporate demand increases + +**Financial Profile:** Consistent earnings growth with 25+ year dividend growth streak + +### 3. **ConocoPhillips (COP)** + +**Investment Thesis:** +Pure-play E&P company with exceptional shareholder returns and operational efficiency. + +**Key Strengths:** +- **Variable Dividend Model:** Industry-leading approach to capital returns based on cash flow generation +- **Low-Cost Operations:** Diversified, low-cost resource base across multiple basins +- **Technology Leadership:** Advanced drilling and completion techniques driving efficiency gains +- **Flexible Capital Structure:** Ability to maintain strong returns across commodity cycles + +**2024 Catalysts:** +- Continued optimization of Permian Basin operations +- Potential for special dividends and increased buybacks with strong cash generation +- Strategic acquisitions to enhance portfolio quality + +**Shareholder Returns:** Targeting 10%+ annual shareholder returns through the cycle + +## Risk Considerations + +**Sector-Wide Risks:** +- **Commodity Price Volatility:** Oil and gas prices remain cyclical and unpredictable +- **Regulatory Environment:** Potential policy changes affecting fossil fuel operations +- **Energy Transition:** Long-term demand uncertainty as renewable adoption accelerates +- **Geopolitical Factors:** Global supply disruptions and trade tensions + +**Individual Stock Risks:** +- **CVX:** Exposure to international operations and refining margins +- **NEE:** Interest rate sensitivity and regulatory approval risks for projects +- **COP:** Pure upstream exposure without downstream diversification + +## Investment Strategy Recommendations + +**Portfolio Approach:** +- **Diversification:** Consider allocating across different energy sub-sectors +- **Risk Management:** Position sizing should reflect individual risk tolerance +- **Time Horizon:** Energy stocks can be volatile; maintain medium to long-term perspective + +**Monitoring Metrics:** +- Free cash flow generation and capital allocation policies +- Production growth and cost management +- ESG initiatives and regulatory compliance +- Dividend sustainability and growth potential + +## Conclusion + +These three stocks represent different approaches to energy sector investment: Chevron offers integrated oil stability, NextEra provides renewable energy growth, and ConocoPhillips delivers pure-play upstream exposure with exceptional shareholder returns. Each addresses different risk/return profiles while maintaining strong fundamentals for 2024. + +**Disclaimer:** This analysis is for informational purposes only and should not be considered personalized investment advice. Always conduct your own research and consider consulting with a financial advisor before making investment decisions.",2025-09-21T20:39:57.146852 +beb4819f-eca3-49d6-9b1c-4d0831911db0,Technical-Agent,What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.,"I appreciate your interest in energy sector investments, but I need to provide an important disclaimer upfront: **I cannot provide specific investment recommendations or financial advice.** Investment decisions should always be made in consultation with qualified financial advisors and based on your individual financial situation, risk tolerance, and investment goals. + +However, I can provide you with an analytical framework and key considerations for evaluating energy stocks in 2024: + +## Key Factors to Consider When Evaluating Energy Stocks + +### 1. **Sector Diversification Analysis** +- **Traditional Oil & Gas**: Companies with strong balance sheets and efficient operations +- **Renewable Energy**: Solar, wind, and energy storage companies +- **Energy Infrastructure**: Pipeline companies and utilities +- **Energy Transition**: Companies pivoting to cleaner technologies + +### 2. **Critical Evaluation Metrics** +- **Financial Health**: Debt-to-equity ratios, free cash flow, dividend sustainability +- **Operational Efficiency**: Production costs, reserve replacement ratios +- **ESG Compliance**: Environmental regulations and sustainability initiatives +- **Market Position**: Competitive advantages and market share + +### 3. **2024 Market Dynamics to Monitor** +- Global energy demand recovery patterns +- Geopolitical tensions affecting supply chains +- Regulatory changes in different jurisdictions +- Technology adoption rates in renewable sectors +- Interest rate impacts on capital-intensive projects + +## Research Approach I Recommend: + +1. **Screen companies** using financial databases (Bloomberg, Reuters, company 10-K filings) +2. **Analyze quarterly earnings** and forward guidance +3. **Compare peer performance** within subsectors +4. **Assess management quality** and strategic vision +5. **Consider macroeconomic factors** affecting the energy sector + +## Professional Resources: +- Consult with licensed financial advisors +- Review analyst reports from reputable investment firms +- Utilize professional investment research platforms +- Consider your portfolio's overall diversification needs + +Would you like me to help you understand how to evaluate specific energy sector metrics or explain particular aspects of energy market analysis instead?",2025-09-21T20:39:57.146852 +beb4819f-eca3-49d6-9b1c-4d0831911db0,Risk-Agent,What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.,"# Top 3 Energy Stocks for 2024: Risk-Adjusted Investment Analysis + +## Executive Summary +Based on fundamental analysis, market positioning, and risk assessment, here are my top 3 energy stock recommendations for 2024: + +--- + +## 1. **Chevron Corporation (CVX)** +**Risk Rating: Moderate | Investment Grade: A-** + +### Investment Thesis +- **Dividend Aristocrat** with 36+ years of consecutive dividend increases +- Strong free cash flow generation at current oil prices ($60+ WTI breakeven) +- Disciplined capital allocation and debt reduction focus + +### Key Strengths +- **Financial Resilience**: Low breakeven costs (~$50-55 WTI) +- **Geographic Diversification**: Operations across Permian Basin, Guyana, Kazakhstan +- **Downstream Integration**: Refining operations provide hedge against crude volatility +- **ESG Leadership**: Clear net-zero commitments and lower-carbon investments + +### Risk Factors +- Commodity price volatility exposure +- Regulatory pressures on traditional energy +- Execution risks in major projects (Guyana expansion) + +### 2024 Catalysts +- Guyana production ramp-up (targeting 1M+ bpd by 2027) +- Permian Basin efficiency gains +- Potential dividend increases and share buybacks + +--- + +## 2. **NextEra Energy (NEE)** +**Risk Rating: Low-Moderate | Investment Grade: A** + +### Investment Thesis +- **Renewable Energy Leader** with largest wind/solar portfolio in North America +- Regulated utility providing stable cash flows +- Best-in-class execution on clean energy transition + +### Key Strengths +- **Diversified Revenue**: ~60% regulated utilities, 40% renewable development +- **Growth Pipeline**: 23+ GW of renewable projects in development +- **Rate Base Growth**: 6-8% annual growth in regulated operations +- **ESG Premium**: Leading ESG scores attract institutional capital + +### Risk Factors +- Interest rate sensitivity (utility-like characteristics) +- Regulatory changes affecting renewable incentives +- Weather dependency for renewable generation + +### 2024 Catalysts +- IRA tax credit optimization +- Florida rate case outcomes +- Continued renewable development acceleration + +--- + +## 3. **ConocoPhillips (COP)** +**Risk Rating: Moderate | Investment Grade: A-** + +### Investment Thesis +- **Return-focused strategy** with variable dividend policy +- Low-cost, high-return asset portfolio +- Strong balance sheet with net cash position + +### Key Strengths +- **Capital Discipline**: Strict return thresholds (>30% IRR) +- **Variable Dividend**: Returns excess cash to shareholders +- **Low-Cost Production**: Permian, Eagle Ford, Alaska operations +- **Flexible Operations**: Can quickly adjust production based on prices + +### Risk Factors +- Commodity price sensitivity +- Concentration in North American unconventionals +- Shorter reserve life vs. integrated peers + +### 2024 Catalysts +- Continued Permian optimization +- Potential special dividends if oil prices remain elevated +- Strategic asset portfolio optimization + +--- + +## Risk Assessment Framework + +### Market Risks +- **Oil Price Volatility**: $70-90 WTI expected range for 2024 +- **Geopolitical Tensions**: Middle East, Russia-Ukraine impacts +- **Demand Concerns**: China economic slowdown, recession risks + +### Sector-Specific Risks +- **Energy Transition**: Accelerating renewable adoption +- **Regulatory Pressure**: Carbon pricing, drilling restrictions +- **Capital Allocation**: History of boom-bust cycles + +### Mitigation Strategies +1. **Diversification**: Mix of traditional and renewable energy +2. **Quality Focus**: Companies with strong balance sheets and cash generation +3. **Dividend Sustainability**: Focus on covered, growing dividends + +## Portfolio Allocation Recommendation +- **Conservative Investor**: 40% NEE, 35% CVX, 25% COP +- **Moderate Investor**: 35% each, equal weighting +- **Growth-Oriented**: 45% NEE, 30% COP, 25% CVX + +## Conclusion +These selections balance traditional energy exposure with renewable transition plays, emphasizing companies with strong cash generation, disciplined capital allocation, and sustainable competitive advantages. Monitor commodity prices, regulatory developments, and execution on strategic initiatives throughout 2024. + +**Disclaimer**: This analysis is for informational purposes only and should not be considered personalized investment advice. Consult with a qualified financial advisor before making investment decisions.",2025-09-21T20:39:57.146852 diff --git a/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_run_id_b93a2946b074493f8fa34a47377b2625.csv b/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_run_id_b93a2946b074493f8fa34a47377b2625.csv new file mode 100644 index 00000000..6b4fcd78 --- /dev/null +++ b/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_run_id_b93a2946b074493f8fa34a47377b2625.csv @@ -0,0 +1,231 @@ +Run ID,Agent Name,Task,Result,Timestamp +294a8728-78fb-480d-95d2-e5175cf1e9cd,Research-Agent,What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.,"# Top 3 Energy Stocks for 2024 Investment Analysis + +As Research-Agent, I'll provide a comprehensive analysis of three compelling energy investment opportunities for 2024, considering current market dynamics, financial fundamentals, and sector trends. + +## 1. **Chevron Corporation (CVX)** + +### Investment Thesis +Chevron stands out as a premium integrated oil major with exceptional capital discipline and shareholder-friendly policies. + +### Key Strengths +- **Financial Fortress**: Strongest balance sheet among oil majors with minimal debt burden +- **Dividend Aristocrat**: 37-year dividend growth streak with current yield ~3.2% +- **Permian Basin Leadership**: Low-cost, high-return shale operations in prime acreage +- **Downstream Integration**: Refining operations provide natural hedging against crude volatility +- **Capital Allocation**: Committed to returning 75% of free cash flow to shareholders + +### 2024 Catalysts +- Permian production growth of 10%+ expected +- Potential for increased dividend and share buybacks +- Strong free cash flow generation at $60+ oil prices + +### Risk Factors +- Commodity price volatility exposure +- ESG investor concerns affecting valuation multiples + +--- + +## 2. **Kinder Morgan Inc. (KMI)** + +### Investment Thesis +North America's largest energy infrastructure company offering stable, fee-based cash flows with growing renewable energy exposure. + +### Key Strengths +- **Predictable Revenue**: ~95% of cash flows from fee-based contracts +- **Essential Infrastructure**: 83,000 miles of pipelines serving critical energy transport +- **Natural Gas Exposure**: Benefits from ongoing coal-to-gas power generation transition +- **Renewable Integration**: Expanding CO2 transport and renewable natural gas capabilities +- **Strong Dividend**: ~6.7% yield with coverage ratio improving + +### 2024 Catalysts +- Completion of major pipeline projects boosting capacity +- Increased natural gas export demand +- Potential renewable energy infrastructure investments + +### Risk Factors +- Regulatory challenges for new pipeline development +- Long-term demand concerns for fossil fuel infrastructure + +--- + +## 3. **NextEra Energy (NEE)** + +### Investment Thesis +Leading utility with the world's largest renewable energy development platform, positioned for the energy transition. + +### Key Strengths +- **Renewable Leadership**: Largest wind and solar operator in North America +- **Regulated Utility Base**: Florida Power & Light provides stable earnings foundation +- **Growth Platform**: NextEra Energy Resources drives above-average growth +- **ESG Leadership**: Strong sustainability credentials attracting ESG-focused capital +- **Dividend Growth**: 29-year dividend growth streak with 6-10% annual increases guided + +### 2024 Catalysts +- Inflation Reduction Act benefits accelerating renewable development +- Grid modernization investments in Florida +- Potential green hydrogen and battery storage expansion + +### Risk Factors +- Interest rate sensitivity due to capital-intensive nature +- Regulatory changes affecting renewable incentives +- Weather-related operational risks in Florida + +--- + +## Portfolio Allocation Recommendation + +**Balanced Energy Exposure (100% allocation):** +- **40% Chevron (CVX)**: Core position for oil exposure and income +- **35% NextEra Energy (NEE)**: Growth-oriented renewable energy play +- **25% Kinder Morgan (KMI)**: Infrastructure stability and high yield + +## Market Context & Timing + +**Favorable Factors for 2024:** +- Energy sector trading at attractive valuations vs. historical averages +- Geopolitical tensions supporting energy security premiums +- Underinvestment in traditional energy creating supply constraints +- Growing recognition of energy transition requiring decades, not years + +**Key Monitoring Points:** +- Federal Reserve policy impacts on interest rates +- Global economic growth affecting energy demand +- Geopolitical developments in major energy-producing regions +- Regulatory changes affecting different energy subsectors + +This diversified approach captures traditional energy cash flows, infrastructure stability, and renewable energy growth while managing sector-specific risks through balanced exposure.",2025-09-21T20:39:11.459523 +294a8728-78fb-480d-95d2-e5175cf1e9cd,Technical-Agent,What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.,"I appreciate your interest in energy sector investments, but I need to provide an important disclaimer upfront: **I cannot provide specific investment recommendations or financial advice.** Investment decisions should always be made in consultation with qualified financial advisors and based on your individual financial situation, risk tolerance, and investment goals. + +However, I can offer an educational analysis of the energy sector landscape and key factors to consider when evaluating energy investments for 2024: + +## Energy Sector Analysis Framework for 2024 + +### Key Market Dynamics to Consider: + +**1. Energy Transition Trends** +- Continued growth in renewable energy adoption +- Government policies supporting clean energy initiatives +- Corporate ESG commitments driving demand for sustainable energy + +**2. Traditional Energy Factors** +- Oil and gas price volatility +- Geopolitical influences on energy markets +- Supply chain considerations and production capacity + +**3. Technology Integration** +- Digital transformation in energy operations +- Energy storage solutions advancement +- Grid modernization investments + +### Categories of Energy Investments to Research: + +**Renewable Energy Leaders** +- Companies with strong solar, wind, and hydroelectric portfolios +- Firms investing heavily in energy storage technology +- Utilities transitioning to clean energy sources + +**Diversified Energy Companies** +- Integrated oil companies with renewable energy divisions +- Companies balancing traditional and alternative energy portfolios +- Firms with strong cash flow management and dividend histories + +**Energy Infrastructure** +- Pipeline and transmission companies +- Energy storage and grid technology providers +- Companies supporting the energy transition infrastructure + +### Due Diligence Factors: +- Financial health and debt management +- Management track record and strategic vision +- Regulatory environment and policy impacts +- Competitive positioning and market share +- ESG ratings and sustainability commitments + +**Recommendation:** Consult with a financial advisor who can analyze your specific situation and provide personalized investment guidance based on current market conditions and your investment objectives.",2025-09-21T20:39:11.459523 +294a8728-78fb-480d-95d2-e5175cf1e9cd,Risk-Agent,What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.,"# Top 3 Energy Stocks for 2024 Investment Analysis + +## Important Risk Disclaimer +As Risk-Agent, I must emphasize that this analysis is for educational purposes only and does not constitute financial advice. Energy sector investments carry significant risks including commodity price volatility, regulatory changes, and market sentiment shifts. Always consult with qualified financial advisors and conduct your own due diligence. + +## Top 3 Energy Stock Recommendations for 2024 + +### 1. **Chevron Corporation (CVX)** + +**Investment Thesis:** +- **Financial Strength**: Robust balance sheet with low debt-to-equity ratio (~0.25) +- **Dividend Reliability**: 36-year dividend growth streak, current yield ~3.2% +- **Operational Excellence**: Low-cost production assets in Permian Basin +- **Capital Discipline**: Committed to maintaining capital expenditure discipline + +**Key Metrics & Analysis:** +- **Free Cash Flow**: Strong FCF generation at $50+ oil prices +- **Breakeven Costs**: Among lowest in industry at ~$40/barrel +- **Geographic Diversification**: Operations across US, Kazakhstan, Australia +- **ESG Progress**: Investing in carbon capture and lower-carbon technologies + +**Risk Factors:** +- Oil price volatility exposure +- Regulatory pressure on fossil fuel operations +- Transition risk as world moves toward renewables + +### 2. **NextEra Energy (NEE)** + +**Investment Thesis:** +- **Renewable Leadership**: Largest renewable energy generator in North America +- **Regulated Utility Base**: Florida Power & Light provides stable cash flows +- **Growth Pipeline**: 30+ GW of renewable development pipeline +- **ESG Leadership**: Strong environmental credentials attracting ESG-focused capital + +**Key Metrics & Analysis:** +- **Dividend Growth**: 29-year dividend growth streak, ~2.8% yield +- **Rate Base Growth**: Regulated utility growing at 6-8% annually +- **Renewable Margins**: High-margin renewable contracts with long-term PPAs +- **Technology Leadership**: Early mover in battery storage and green hydrogen + +**Risk Factors:** +- Interest rate sensitivity due to capital-intensive nature +- Regulatory changes affecting renewable incentives +- Weather-related operational risks in Florida + +### 3. **ConocoPhillips (COP)** + +**Investment Thesis:** +- **Return of Capital Focus**: Industry-leading shareholder return program +- **Low-Cost Operations**: Unconventional resource expertise with low breakevens +- **Variable Dividend**: Flexible dividend policy tied to commodity prices +- **Portfolio Quality**: High-return, short-cycle assets + +**Key Metrics & Analysis:** +- **Shareholder Returns**: Targeting 50%+ of CFO returned to shareholders +- **Operational Efficiency**: Breakeven costs ~$40/barrel WTI +- **Balance Sheet**: Net cash position providing financial flexibility +- **Production Growth**: Modest, profitable growth in key basins + +**Risk Factors:** +- Commodity price cyclicality +- Variable dividend may not appeal to income-focused investors +- Exposure to geopolitical risks in international operations + +## Sector Risk Assessment + +### Key Risks to Monitor: +1. **Commodity Price Volatility**: Oil and gas prices remain primary driver +2. **Energy Transition**: Long-term demand concerns for fossil fuels +3. **Regulatory Environment**: Potential for increased environmental regulations +4. **Geopolitical Tensions**: Supply disruption risks +5. **Interest Rate Environment**: Impact on capital-intensive projects + +### Risk Mitigation Strategies: +- **Diversification**: Don't concentrate more than 5-10% in energy sector +- **Dollar-Cost Averaging**: Spread purchases over time to reduce timing risk +- **Regular Rebalancing**: Monitor positions and adjust based on changing fundamentals +- **Stay Informed**: Track commodity prices, regulatory changes, and company-specific developments + +## Conclusion + +These three stocks represent different approaches to energy investing: traditional integrated oil (CVX), renewable transition leader (NEE), and pure-play E&P with shareholder focus (COP). Each offers distinct risk-return profiles suitable for different investment objectives. + +**Remember**: Energy stocks are inherently volatile and cyclical. Consider your risk tolerance, investment timeline, and portfolio diversification before making investment decisions. Past performance does not guarantee future results. + +Would you like me to elaborate on any specific aspect of this analysis or discuss additional risk management strategies for energy sector investing?",2025-09-21T20:39:11.459523 diff --git a/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_usage.py b/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_usage.py new file mode 100644 index 00000000..fb8f9124 --- /dev/null +++ b/examples/multi_agent/new_spreadsheet_new_examples/spreadsheet_swarm_usage.py @@ -0,0 +1,161 @@ +""" +SpreadSheetSwarm Usage Examples +============================== + +This file demonstrates the two main ways to use SpreadSheetSwarm: +1. With pre-configured agents +2. With CSV configuration file +""" + +from swarms import Agent +from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm + + +def example_with_agents(): + """Example using pre-configured agents""" + print("=== Example 1: Using Pre-configured Agents ===") + + # Create agents + agents = [ + Agent( + agent_name="Writer-Agent", + agent_description="Creative writing specialist", + model_name="claude-sonnet-4-20250514", + dynamic_temperature_enabled=True, + max_loops=1, + streaming_on=False, + print_on=False, + ), + Agent( + agent_name="Editor-Agent", + agent_description="Content editing and proofreading expert", + model_name="claude-sonnet-4-20250514", + dynamic_temperature_enabled=True, + max_loops=1, + streaming_on=False, + print_on=False, + ), + ] + + # Create swarm with agents + swarm = SpreadSheetSwarm( + name="Content-Creation-Swarm", + description="A swarm for content creation and editing", + agents=agents, + autosave=True, + max_loops=1, + ) + + # Run with same task for all agents + result = swarm.run("Write a short story about AI and creativity") + + print(f"Tasks completed: {result['tasks_completed']}") + print(f"Number of agents: {result['number_of_agents']}") + return result + + +def example_with_csv(): + """Example using CSV configuration""" + print("\n=== Example 2: Using CSV Configuration ===") + + # Create CSV content + csv_content = """agent_name,description,system_prompt,task,model_name,max_loops,user_name +Writer-Agent,Creative writing specialist,You are a creative writer,Write a poem about technology,claude-sonnet-4-20250514,1,user +Editor-Agent,Content editing expert,You are an editor,Review and improve the poem,claude-sonnet-4-20250514,1,user +Critic-Agent,Literary critic,You are a literary critic,Provide constructive feedback on the poem,claude-sonnet-4-20250514,1,user""" + + # Save CSV file + with open("agents.csv", "w") as f: + f.write(csv_content) + + # Create swarm with CSV path only (no agents provided) + swarm = SpreadSheetSwarm( + name="Poetry-Swarm", + description="A swarm for poetry creation and review", + load_path="agents.csv", # No agents parameter - will load from CSV + autosave=True, + max_loops=1, + ) + + # Run with different tasks from CSV + result = swarm.run_from_config() + + print(f"Tasks completed: {result['tasks_completed']}") + print(f"Number of agents: {result['number_of_agents']}") + + # Clean up + import os + + if os.path.exists("agents.csv"): + os.remove("agents.csv") + + return result + + +def example_mixed_usage(): + """Example showing both agents and CSV can be used together""" + print("\n=== Example 3: Mixed Usage (Agents + CSV) ===") + + # Create one agent + agent = Agent( + agent_name="Coordinator-Agent", + agent_description="Project coordinator", + model_name="claude-sonnet-4-20250514", + dynamic_temperature_enabled=True, + max_loops=1, + streaming_on=False, + print_on=False, + ) + + # Create CSV content + csv_content = """agent_name,description,system_prompt,task,model_name,max_loops,user_name +Researcher-Agent,Research specialist,You are a researcher,Research the topic thoroughly,claude-sonnet-4-20250514,1,user +Analyst-Agent,Data analyst,You are a data analyst,Analyze the research data,claude-sonnet-4-20250514,1,user""" + + with open("research_agents.csv", "w") as f: + f.write(csv_content) + + # Create swarm with both agents and CSV + swarm = SpreadSheetSwarm( + name="Mixed-Swarm", + description="A swarm with both pre-configured and CSV-loaded agents", + agents=[agent], # Pre-configured agent + load_path="research_agents.csv", # CSV agents + autosave=True, + max_loops=1, + ) + + # Load CSV agents + swarm.load_from_csv() + + # Run with same task for all agents + result = swarm.run("Analyze the impact of AI on education") + + print(f"Tasks completed: {result['tasks_completed']}") + print(f"Number of agents: {result['number_of_agents']}") + + # Clean up + import os + + if os.path.exists("research_agents.csv"): + os.remove("research_agents.csv") + + return result + + +if __name__ == "__main__": + # Run all examples + result1 = example_with_agents() + result2 = example_with_csv() + result3 = example_mixed_usage() + + print("\n=== Summary ===") + print( + f"Example 1 - Pre-configured agents: {result1['tasks_completed']} tasks" + ) + print( + f"Example 2 - CSV configuration: {result2['tasks_completed']} tasks" + ) + print( + f"Example 3 - Mixed usage: {result3['tasks_completed']} tasks" + ) diff --git a/examples/multi_agent/new_spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-69f4c23f5a97477ab2b8114521c33fd4-metadata.json b/examples/multi_agent/new_spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-69f4c23f5a97477ab2b8114521c33fd4-metadata.json new file mode 100644 index 00000000..cf6b3d03 --- /dev/null +++ b/examples/multi_agent/new_spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-69f4c23f5a97477ab2b8114521c33fd4-metadata.json @@ -0,0 +1,27 @@ +{ + "run_id": "spreadsheet_swarm_run_69f4c23f5a97477ab2b8114521c33fd4", + "name": "Financial-Analysis-Swarm", + "description": "A swarm of specialized financial analysis agents", + "tasks_completed": 3, + "number_of_agents": 3, + "outputs": [ + { + "agent_name": "Research-Agent", + "task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.", + "result": "I'll provide a comprehensive analysis of three strong energy sector investment opportunities for 2024, focusing on companies with solid fundamentals, strategic positioning, and growth potential.\n\n## Top 3 Energy Stock Recommendations for 2024\n\n### 1. **Chevron Corporation (CVX)**\n\n**Investment Thesis:**\nChevron stands out as a premium integrated oil company with exceptional capital discipline and shareholder-friendly policies.\n\n**Key Strengths:**\n- **Financial Fortress:** Maintains one of the strongest balance sheets in the sector with low debt-to-equity ratio\n- **Dividend Aristocrat:** 36+ years of consecutive dividend increases, currently yielding ~3.2%\n- **Operational Excellence:** Low-cost production assets, particularly in the Permian Basin\n- **Capital Allocation:** Committed to returning 75% of free cash flow to shareholders through dividends and buybacks\n\n**2024 Catalysts:**\n- Continued Permian Basin expansion with industry-leading breakeven costs (~$35/barrel)\n- LNG project developments enhancing long-term cash flow visibility\n- Potential for increased shareholder returns if oil prices remain elevated\n\n**Valuation:** Trading at attractive P/E multiple compared to historical averages\n\n### 2. **NextEra Energy (NEE)**\n\n**Investment Thesis:**\nLeading utility with the largest renewable energy portfolio in North America, positioned to benefit from the energy transition.\n\n**Key Strengths:**\n- **Renewable Leadership:** Largest wind and solar generator in North America\n- **Regulated Utility Base:** Florida Power & Light provides stable cash flow foundation\n- **Growth Pipeline:** ~$85 billion capital investment plan through 2026\n- **ESG Appeal:** Strong environmental credentials attracting ESG-focused investors\n\n**2024 Catalysts:**\n- Inflation Reduction Act benefits boosting renewable project economics\n- Grid modernization investments supporting rate base growth\n- Potential for accelerated renewable development as corporate demand increases\n\n**Financial Profile:** Consistent earnings growth with 25+ year dividend growth streak\n\n### 3. **ConocoPhillips (COP)**\n\n**Investment Thesis:**\nPure-play E&P company with exceptional shareholder returns and operational efficiency.\n\n**Key Strengths:**\n- **Variable Dividend Model:** Industry-leading approach to capital returns based on cash flow generation\n- **Low-Cost Operations:** Diversified, low-cost resource base across multiple basins\n- **Technology Leadership:** Advanced drilling and completion techniques driving efficiency gains\n- **Flexible Capital Structure:** Ability to maintain strong returns across commodity cycles\n\n**2024 Catalysts:**\n- Continued optimization of Permian Basin operations\n- Potential for special dividends and increased buybacks with strong cash generation\n- Strategic acquisitions to enhance portfolio quality\n\n**Shareholder Returns:** Targeting 10%+ annual shareholder returns through the cycle\n\n## Risk Considerations\n\n**Sector-Wide Risks:**\n- **Commodity Price Volatility:** Oil and gas prices remain cyclical and unpredictable\n- **Regulatory Environment:** Potential policy changes affecting fossil fuel operations\n- **Energy Transition:** Long-term demand uncertainty as renewable adoption accelerates\n- **Geopolitical Factors:** Global supply disruptions and trade tensions\n\n**Individual Stock Risks:**\n- **CVX:** Exposure to international operations and refining margins\n- **NEE:** Interest rate sensitivity and regulatory approval risks for projects\n- **COP:** Pure upstream exposure without downstream diversification\n\n## Investment Strategy Recommendations\n\n**Portfolio Approach:**\n- **Diversification:** Consider allocating across different energy sub-sectors\n- **Risk Management:** Position sizing should reflect individual risk tolerance\n- **Time Horizon:** Energy stocks can be volatile; maintain medium to long-term perspective\n\n**Monitoring Metrics:**\n- Free cash flow generation and capital allocation policies\n- Production growth and cost management\n- ESG initiatives and regulatory compliance\n- Dividend sustainability and growth potential\n\n## Conclusion\n\nThese three stocks represent different approaches to energy sector investment: Chevron offers integrated oil stability, NextEra provides renewable energy growth, and ConocoPhillips delivers pure-play upstream exposure with exceptional shareholder returns. Each addresses different risk/return profiles while maintaining strong fundamentals for 2024.\n\n**Disclaimer:** This analysis is for informational purposes only and should not be considered personalized investment advice. Always conduct your own research and consider consulting with a financial advisor before making investment decisions.", + "timestamp": "2025-09-21T20:39:57.146852" + }, + { + "agent_name": "Technical-Agent", + "task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.", + "result": "I appreciate your interest in energy sector investments, but I need to provide an important disclaimer upfront: **I cannot provide specific investment recommendations or financial advice.** Investment decisions should always be made in consultation with qualified financial advisors and based on your individual financial situation, risk tolerance, and investment goals.\n\nHowever, I can provide you with an analytical framework and key considerations for evaluating energy stocks in 2024:\n\n## Key Factors to Consider When Evaluating Energy Stocks\n\n### 1. **Sector Diversification Analysis**\n- **Traditional Oil & Gas**: Companies with strong balance sheets and efficient operations\n- **Renewable Energy**: Solar, wind, and energy storage companies\n- **Energy Infrastructure**: Pipeline companies and utilities\n- **Energy Transition**: Companies pivoting to cleaner technologies\n\n### 2. **Critical Evaluation Metrics**\n- **Financial Health**: Debt-to-equity ratios, free cash flow, dividend sustainability\n- **Operational Efficiency**: Production costs, reserve replacement ratios\n- **ESG Compliance**: Environmental regulations and sustainability initiatives\n- **Market Position**: Competitive advantages and market share\n\n### 3. **2024 Market Dynamics to Monitor**\n- Global energy demand recovery patterns\n- Geopolitical tensions affecting supply chains\n- Regulatory changes in different jurisdictions\n- Technology adoption rates in renewable sectors\n- Interest rate impacts on capital-intensive projects\n\n## Research Approach I Recommend:\n\n1. **Screen companies** using financial databases (Bloomberg, Reuters, company 10-K filings)\n2. **Analyze quarterly earnings** and forward guidance\n3. **Compare peer performance** within subsectors\n4. **Assess management quality** and strategic vision\n5. **Consider macroeconomic factors** affecting the energy sector\n\n## Professional Resources:\n- Consult with licensed financial advisors\n- Review analyst reports from reputable investment firms\n- Utilize professional investment research platforms\n- Consider your portfolio's overall diversification needs\n\nWould you like me to help you understand how to evaluate specific energy sector metrics or explain particular aspects of energy market analysis instead?", + "timestamp": "2025-09-21T20:39:57.146852" + }, + { + "agent_name": "Risk-Agent", + "task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.", + "result": "# Top 3 Energy Stocks for 2024: Risk-Adjusted Investment Analysis\n\n## Executive Summary\nBased on fundamental analysis, market positioning, and risk assessment, here are my top 3 energy stock recommendations for 2024:\n\n---\n\n## 1. **Chevron Corporation (CVX)**\n**Risk Rating: Moderate | Investment Grade: A-**\n\n### Investment Thesis\n- **Dividend Aristocrat** with 36+ years of consecutive dividend increases\n- Strong free cash flow generation at current oil prices ($60+ WTI breakeven)\n- Disciplined capital allocation and debt reduction focus\n\n### Key Strengths\n- **Financial Resilience**: Low breakeven costs (~$50-55 WTI)\n- **Geographic Diversification**: Operations across Permian Basin, Guyana, Kazakhstan\n- **Downstream Integration**: Refining operations provide hedge against crude volatility\n- **ESG Leadership**: Clear net-zero commitments and lower-carbon investments\n\n### Risk Factors\n- Commodity price volatility exposure\n- Regulatory pressures on traditional energy\n- Execution risks in major projects (Guyana expansion)\n\n### 2024 Catalysts\n- Guyana production ramp-up (targeting 1M+ bpd by 2027)\n- Permian Basin efficiency gains\n- Potential dividend increases and share buybacks\n\n---\n\n## 2. **NextEra Energy (NEE)**\n**Risk Rating: Low-Moderate | Investment Grade: A**\n\n### Investment Thesis\n- **Renewable Energy Leader** with largest wind/solar portfolio in North America\n- Regulated utility providing stable cash flows\n- Best-in-class execution on clean energy transition\n\n### Key Strengths\n- **Diversified Revenue**: ~60% regulated utilities, 40% renewable development\n- **Growth Pipeline**: 23+ GW of renewable projects in development\n- **Rate Base Growth**: 6-8% annual growth in regulated operations\n- **ESG Premium**: Leading ESG scores attract institutional capital\n\n### Risk Factors\n- Interest rate sensitivity (utility-like characteristics)\n- Regulatory changes affecting renewable incentives\n- Weather dependency for renewable generation\n\n### 2024 Catalysts\n- IRA tax credit optimization\n- Florida rate case outcomes\n- Continued renewable development acceleration\n\n---\n\n## 3. **ConocoPhillips (COP)**\n**Risk Rating: Moderate | Investment Grade: A-**\n\n### Investment Thesis\n- **Return-focused strategy** with variable dividend policy\n- Low-cost, high-return asset portfolio\n- Strong balance sheet with net cash position\n\n### Key Strengths\n- **Capital Discipline**: Strict return thresholds (>30% IRR)\n- **Variable Dividend**: Returns excess cash to shareholders\n- **Low-Cost Production**: Permian, Eagle Ford, Alaska operations\n- **Flexible Operations**: Can quickly adjust production based on prices\n\n### Risk Factors\n- Commodity price sensitivity\n- Concentration in North American unconventionals\n- Shorter reserve life vs. integrated peers\n\n### 2024 Catalysts\n- Continued Permian optimization\n- Potential special dividends if oil prices remain elevated\n- Strategic asset portfolio optimization\n\n---\n\n## Risk Assessment Framework\n\n### Market Risks\n- **Oil Price Volatility**: $70-90 WTI expected range for 2024\n- **Geopolitical Tensions**: Middle East, Russia-Ukraine impacts\n- **Demand Concerns**: China economic slowdown, recession risks\n\n### Sector-Specific Risks\n- **Energy Transition**: Accelerating renewable adoption\n- **Regulatory Pressure**: Carbon pricing, drilling restrictions\n- **Capital Allocation**: History of boom-bust cycles\n\n### Mitigation Strategies\n1. **Diversification**: Mix of traditional and renewable energy\n2. **Quality Focus**: Companies with strong balance sheets and cash generation\n3. **Dividend Sustainability**: Focus on covered, growing dividends\n\n## Portfolio Allocation Recommendation\n- **Conservative Investor**: 40% NEE, 35% CVX, 25% COP\n- **Moderate Investor**: 35% each, equal weighting\n- **Growth-Oriented**: 45% NEE, 30% COP, 25% CVX\n\n## Conclusion\nThese selections balance traditional energy exposure with renewable transition plays, emphasizing companies with strong cash generation, disciplined capital allocation, and sustainable competitive advantages. Monitor commodity prices, regulatory developments, and execution on strategic initiatives throughout 2024.\n\n**Disclaimer**: This analysis is for informational purposes only and should not be considered personalized investment advice. Consult with a qualified financial advisor before making investment decisions.", + "timestamp": "2025-09-21T20:39:57.146852" + } + ] +} \ No newline at end of file diff --git a/examples/multi_agent/new_spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-b93a2946b074493f8fa34a47377b2625-metadata.json b/examples/multi_agent/new_spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-b93a2946b074493f8fa34a47377b2625-metadata.json new file mode 100644 index 00000000..07dc0715 --- /dev/null +++ b/examples/multi_agent/new_spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-b93a2946b074493f8fa34a47377b2625-metadata.json @@ -0,0 +1,27 @@ +{ + "run_id": "spreadsheet_swarm_run_b93a2946b074493f8fa34a47377b2625", + "name": "Financial-Analysis-Swarm", + "description": "A swarm of specialized financial analysis agents", + "tasks_completed": 3, + "number_of_agents": 3, + "outputs": [ + { + "agent_name": "Research-Agent", + "task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.", + "result": "# Top 3 Energy Stocks for 2024 Investment Analysis\n\nAs Research-Agent, I'll provide a comprehensive analysis of three compelling energy investment opportunities for 2024, considering current market dynamics, financial fundamentals, and sector trends.\n\n## 1. **Chevron Corporation (CVX)**\n\n### Investment Thesis\nChevron stands out as a premium integrated oil major with exceptional capital discipline and shareholder-friendly policies.\n\n### Key Strengths\n- **Financial Fortress**: Strongest balance sheet among oil majors with minimal debt burden\n- **Dividend Aristocrat**: 37-year dividend growth streak with current yield ~3.2%\n- **Permian Basin Leadership**: Low-cost, high-return shale operations in prime acreage\n- **Downstream Integration**: Refining operations provide natural hedging against crude volatility\n- **Capital Allocation**: Committed to returning 75% of free cash flow to shareholders\n\n### 2024 Catalysts\n- Permian production growth of 10%+ expected\n- Potential for increased dividend and share buybacks\n- Strong free cash flow generation at $60+ oil prices\n\n### Risk Factors\n- Commodity price volatility exposure\n- ESG investor concerns affecting valuation multiples\n\n---\n\n## 2. **Kinder Morgan Inc. (KMI)**\n\n### Investment Thesis\nNorth America's largest energy infrastructure company offering stable, fee-based cash flows with growing renewable energy exposure.\n\n### Key Strengths\n- **Predictable Revenue**: ~95% of cash flows from fee-based contracts\n- **Essential Infrastructure**: 83,000 miles of pipelines serving critical energy transport\n- **Natural Gas Exposure**: Benefits from ongoing coal-to-gas power generation transition\n- **Renewable Integration**: Expanding CO2 transport and renewable natural gas capabilities\n- **Strong Dividend**: ~6.7% yield with coverage ratio improving\n\n### 2024 Catalysts\n- Completion of major pipeline projects boosting capacity\n- Increased natural gas export demand\n- Potential renewable energy infrastructure investments\n\n### Risk Factors\n- Regulatory challenges for new pipeline development\n- Long-term demand concerns for fossil fuel infrastructure\n\n---\n\n## 3. **NextEra Energy (NEE)**\n\n### Investment Thesis\nLeading utility with the world's largest renewable energy development platform, positioned for the energy transition.\n\n### Key Strengths\n- **Renewable Leadership**: Largest wind and solar operator in North America\n- **Regulated Utility Base**: Florida Power & Light provides stable earnings foundation\n- **Growth Platform**: NextEra Energy Resources drives above-average growth\n- **ESG Leadership**: Strong sustainability credentials attracting ESG-focused capital\n- **Dividend Growth**: 29-year dividend growth streak with 6-10% annual increases guided\n\n### 2024 Catalysts\n- Inflation Reduction Act benefits accelerating renewable development\n- Grid modernization investments in Florida\n- Potential green hydrogen and battery storage expansion\n\n### Risk Factors\n- Interest rate sensitivity due to capital-intensive nature\n- Regulatory changes affecting renewable incentives\n- Weather-related operational risks in Florida\n\n---\n\n## Portfolio Allocation Recommendation\n\n**Balanced Energy Exposure (100% allocation):**\n- **40% Chevron (CVX)**: Core position for oil exposure and income\n- **35% NextEra Energy (NEE)**: Growth-oriented renewable energy play\n- **25% Kinder Morgan (KMI)**: Infrastructure stability and high yield\n\n## Market Context & Timing\n\n**Favorable Factors for 2024:**\n- Energy sector trading at attractive valuations vs. historical averages\n- Geopolitical tensions supporting energy security premiums\n- Underinvestment in traditional energy creating supply constraints\n- Growing recognition of energy transition requiring decades, not years\n\n**Key Monitoring Points:**\n- Federal Reserve policy impacts on interest rates\n- Global economic growth affecting energy demand\n- Geopolitical developments in major energy-producing regions\n- Regulatory changes affecting different energy subsectors\n\nThis diversified approach captures traditional energy cash flows, infrastructure stability, and renewable energy growth while managing sector-specific risks through balanced exposure.", + "timestamp": "2025-09-21T20:39:11.459523" + }, + { + "agent_name": "Technical-Agent", + "task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.", + "result": "I appreciate your interest in energy sector investments, but I need to provide an important disclaimer upfront: **I cannot provide specific investment recommendations or financial advice.** Investment decisions should always be made in consultation with qualified financial advisors and based on your individual financial situation, risk tolerance, and investment goals.\n\nHowever, I can offer an educational analysis of the energy sector landscape and key factors to consider when evaluating energy investments for 2024:\n\n## Energy Sector Analysis Framework for 2024\n\n### Key Market Dynamics to Consider:\n\n**1. Energy Transition Trends**\n- Continued growth in renewable energy adoption\n- Government policies supporting clean energy initiatives\n- Corporate ESG commitments driving demand for sustainable energy\n\n**2. Traditional Energy Factors**\n- Oil and gas price volatility\n- Geopolitical influences on energy markets\n- Supply chain considerations and production capacity\n\n**3. Technology Integration**\n- Digital transformation in energy operations\n- Energy storage solutions advancement\n- Grid modernization investments\n\n### Categories of Energy Investments to Research:\n\n**Renewable Energy Leaders**\n- Companies with strong solar, wind, and hydroelectric portfolios\n- Firms investing heavily in energy storage technology\n- Utilities transitioning to clean energy sources\n\n**Diversified Energy Companies**\n- Integrated oil companies with renewable energy divisions\n- Companies balancing traditional and alternative energy portfolios\n- Firms with strong cash flow management and dividend histories\n\n**Energy Infrastructure**\n- Pipeline and transmission companies\n- Energy storage and grid technology providers\n- Companies supporting the energy transition infrastructure\n\n### Due Diligence Factors:\n- Financial health and debt management\n- Management track record and strategic vision\n- Regulatory environment and policy impacts\n- Competitive positioning and market share\n- ESG ratings and sustainability commitments\n\n**Recommendation:** Consult with a financial advisor who can analyze your specific situation and provide personalized investment guidance based on current market conditions and your investment objectives.", + "timestamp": "2025-09-21T20:39:11.459523" + }, + { + "agent_name": "Risk-Agent", + "task": "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis.", + "result": "# Top 3 Energy Stocks for 2024 Investment Analysis\n\n## Important Risk Disclaimer\nAs Risk-Agent, I must emphasize that this analysis is for educational purposes only and does not constitute financial advice. Energy sector investments carry significant risks including commodity price volatility, regulatory changes, and market sentiment shifts. Always consult with qualified financial advisors and conduct your own due diligence.\n\n## Top 3 Energy Stock Recommendations for 2024\n\n### 1. **Chevron Corporation (CVX)**\n\n**Investment Thesis:**\n- **Financial Strength**: Robust balance sheet with low debt-to-equity ratio (~0.25)\n- **Dividend Reliability**: 36-year dividend growth streak, current yield ~3.2%\n- **Operational Excellence**: Low-cost production assets in Permian Basin\n- **Capital Discipline**: Committed to maintaining capital expenditure discipline\n\n**Key Metrics & Analysis:**\n- **Free Cash Flow**: Strong FCF generation at $50+ oil prices\n- **Breakeven Costs**: Among lowest in industry at ~$40/barrel\n- **Geographic Diversification**: Operations across US, Kazakhstan, Australia\n- **ESG Progress**: Investing in carbon capture and lower-carbon technologies\n\n**Risk Factors:**\n- Oil price volatility exposure\n- Regulatory pressure on fossil fuel operations\n- Transition risk as world moves toward renewables\n\n### 2. **NextEra Energy (NEE)**\n\n**Investment Thesis:**\n- **Renewable Leadership**: Largest renewable energy generator in North America\n- **Regulated Utility Base**: Florida Power & Light provides stable cash flows\n- **Growth Pipeline**: 30+ GW of renewable development pipeline\n- **ESG Leadership**: Strong environmental credentials attracting ESG-focused capital\n\n**Key Metrics & Analysis:**\n- **Dividend Growth**: 29-year dividend growth streak, ~2.8% yield\n- **Rate Base Growth**: Regulated utility growing at 6-8% annually\n- **Renewable Margins**: High-margin renewable contracts with long-term PPAs\n- **Technology Leadership**: Early mover in battery storage and green hydrogen\n\n**Risk Factors:**\n- Interest rate sensitivity due to capital-intensive nature\n- Regulatory changes affecting renewable incentives\n- Weather-related operational risks in Florida\n\n### 3. **ConocoPhillips (COP)**\n\n**Investment Thesis:**\n- **Return of Capital Focus**: Industry-leading shareholder return program\n- **Low-Cost Operations**: Unconventional resource expertise with low breakevens\n- **Variable Dividend**: Flexible dividend policy tied to commodity prices\n- **Portfolio Quality**: High-return, short-cycle assets\n\n**Key Metrics & Analysis:**\n- **Shareholder Returns**: Targeting 50%+ of CFO returned to shareholders\n- **Operational Efficiency**: Breakeven costs ~$40/barrel WTI\n- **Balance Sheet**: Net cash position providing financial flexibility\n- **Production Growth**: Modest, profitable growth in key basins\n\n**Risk Factors:**\n- Commodity price cyclicality\n- Variable dividend may not appeal to income-focused investors\n- Exposure to geopolitical risks in international operations\n\n## Sector Risk Assessment\n\n### Key Risks to Monitor:\n1. **Commodity Price Volatility**: Oil and gas prices remain primary driver\n2. **Energy Transition**: Long-term demand concerns for fossil fuels\n3. **Regulatory Environment**: Potential for increased environmental regulations\n4. **Geopolitical Tensions**: Supply disruption risks\n5. **Interest Rate Environment**: Impact on capital-intensive projects\n\n### Risk Mitigation Strategies:\n- **Diversification**: Don't concentrate more than 5-10% in energy sector\n- **Dollar-Cost Averaging**: Spread purchases over time to reduce timing risk\n- **Regular Rebalancing**: Monitor positions and adjust based on changing fundamentals\n- **Stay Informed**: Track commodity prices, regulatory changes, and company-specific developments\n\n## Conclusion\n\nThese three stocks represent different approaches to energy investing: traditional integrated oil (CVX), renewable transition leader (NEE), and pure-play E&P with shareholder focus (COP). Each offers distinct risk-return profiles suitable for different investment objectives.\n\n**Remember**: Energy stocks are inherently volatile and cyclical. Consider your risk tolerance, investment timeline, and portfolio diversification before making investment decisions. Past performance does not guarantee future results.\n\nWould you like me to elaborate on any specific aspect of this analysis or discuss additional risk management strategies for energy sector investing?", + "timestamp": "2025-09-21T20:39:11.459523" + } + ] +} \ No newline at end of file diff --git a/examples/multi_agent/swarmarrange/rearrange_test.py b/examples/multi_agent/swarmarrange/rearrange_test.py deleted file mode 100644 index de020cc7..00000000 --- a/examples/multi_agent/swarmarrange/rearrange_test.py +++ /dev/null @@ -1,120 +0,0 @@ -import os - -from swarms import Agent, AgentRearrange - -from swarm_models import OpenAIChat - -# Get the OpenAI API key from the environment variable -api_key = os.getenv("OPENAI_API_KEY") - -# Create an instance of the OpenAIChat class -model = OpenAIChat( - api_key=api_key, model_name="gpt-4o-mini", temperature=0.1 -) - - -# Initialize the boss agent (Director) -boss_agent = Agent( - agent_name="BossAgent", - system_prompt=""" - You are the BossAgent responsible for managing and overseeing a swarm of agents analyzing company expenses. - Your job is to dynamically assign tasks, prioritize their execution, and ensure that all agents collaborate efficiently. - After receiving a report on the company's expenses, you will break down the work into smaller tasks, - assigning specific tasks to each agent, such as detecting recurring high costs, categorizing expenditures, - and identifying unnecessary transactions. Ensure the results are communicated back in a structured way - so the finance team can take actionable steps to cut off unproductive spending. You also monitor and - dynamically adapt the swarm to optimize their performance. Finally, you summarize their findings - into a coherent report. - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="boss_agent.json", -) - -# Initialize worker 1: Expense Analyzer -worker1 = Agent( - agent_name="ExpenseAnalyzer", - system_prompt=""" - Your task is to carefully analyze the company's expense data provided to you. - You will focus on identifying high-cost recurring transactions, categorizing expenditures - (e.g., marketing, operations, utilities, etc.), and flagging areas where there seems to be excessive spending. - You will provide a detailed breakdown of each category, along with specific recommendations for cost-cutting. - Pay close attention to monthly recurring subscriptions, office supplies, and non-essential expenditures. - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker1.json", -) - -# Initialize worker 2: Summary Generator -worker2 = Agent( - agent_name="SummaryGenerator", - system_prompt=""" - After receiving the detailed breakdown from the ExpenseAnalyzer, - your task is to create a concise summary of the findings. You will focus on the most actionable insights, - such as highlighting the specific transactions that can be immediately cut off and summarizing the areas - where the company is overspending. Your summary will be used by the BossAgent to generate the final report. - Be clear and to the point, emphasizing the urgency of cutting unnecessary expenses. - """, - llm=model, - max_loops=1, - dashboard=False, - streaming_on=True, - verbose=True, - stopping_token="", - state_save_file_type="json", - saved_state_path="worker2.json", -) - -# Swarm-Level Prompt (Collaboration Prompt) -swarm_prompt = """ - As a swarm, your collective goal is to analyze the company's expenses and identify transactions that should be cut off. - You will work collaboratively to break down the entire process of expense analysis into manageable steps. - The BossAgent will direct the flow and assign tasks dynamically to the agents. The ExpenseAnalyzer will first - focus on breaking down the expense report, identifying high-cost recurring transactions, categorizing them, - and providing recommendations for potential cost reduction. After the analysis, the SummaryGenerator will then - consolidate all the findings into an actionable summary that the finance team can use to immediately cut off unnecessary expenses. - Together, your collaboration is essential to streamlining and improving the company’s financial health. -""" - -# Create a list of agents -agents = [boss_agent, worker1, worker2] - -# Define the flow pattern for the swarm -flow = "BossAgent -> ExpenseAnalyzer -> SummaryGenerator" - -# Using AgentRearrange class to manage the swarm -agent_system = AgentRearrange( - name="pe-swarm", - description="ss", - agents=agents, - flow=flow, - return_json=False, - output_type="final", - max_loops=1, -) - -# Input task for the swarm -task = f""" - - {swarm_prompt} - - The company has been facing a rising number of unnecessary expenses, and the finance team needs a detailed - analysis of recent transactions to identify which expenses can be cut off to improve profitability. - Analyze the provided transaction data and create a detailed report on cost-cutting opportunities, - focusing on recurring transactions and non-essential expenditures. -""" - -# Run the swarm system with the task -output = agent_system.run(task) -print(output) diff --git a/examples/rag/README.md b/examples/rag/README.md new file mode 100644 index 00000000..bde13960 --- /dev/null +++ b/examples/rag/README.md @@ -0,0 +1,6 @@ +# RAG (Retrieval Augmented Generation) Examples + +This directory contains examples demonstrating RAG implementations and vector database integrations in Swarms. + +## Qdrant RAG +- [qdrant_rag_example.py](qdrant_rag_example.py) - Complete Qdrant RAG implementation diff --git a/examples/reasoning_agents/README.md b/examples/reasoning_agents/README.md new file mode 100644 index 00000000..30292db1 --- /dev/null +++ b/examples/reasoning_agents/README.md @@ -0,0 +1,12 @@ +# Reasoning Agents Examples + +This directory contains examples demonstrating advanced reasoning capabilities and agent evaluation systems in Swarms. + +## Agent Judge Examples +- [example1_basic_evaluation.py](agent_judge_examples/example1_basic_evaluation.py) - Basic agent evaluation +- [example2_technical_evaluation.py](agent_judge_examples/example2_technical_evaluation.py) - Technical evaluation criteria +- [example3_creative_evaluation.py](agent_judge_examples/example3_creative_evaluation.py) - Creative evaluation patterns + +## O3 Integration +- [example_o3.py](example_o3.py) - O3 model integration example +- [o3_agent.py](o3_agent.py) - O3 agent implementation diff --git a/examples/single_agent/README.md b/examples/single_agent/README.md new file mode 100644 index 00000000..d9997390 --- /dev/null +++ b/examples/single_agent/README.md @@ -0,0 +1,115 @@ +# Single Agent Examples + +This directory contains examples demonstrating single agent patterns, configurations, and use cases in Swarms. + +## Demos +- [insurance_agent.py](demos/insurance_agent.py) - Insurance processing agent +- [persistent_legal_agent.py](demos/persistent_legal_agent.py) - Legal document processing agent + +## External Agents +- [custom_agent_example.py](external_agents/custom_agent_example.py) - Custom agent implementation +- [openai_assistant_wrapper.py](external_agents/openai_assistant_wrapper.py) - OpenAI Assistant integration + +## LLM Integrations + +### Azure +- [azure_agent_api_verison.py](llms/azure_agent_api_verison.py) - Azure API version handling +- [azure_agent.py](llms/azure_agent.py) - Azure OpenAI integration +- [azure_model_support.py](llms/azure_model_support.py) - Azure model support + +### Claude +- [claude_4_example.py](llms/claude_examples/claude_4_example.py) - Claude 4 integration +- [claude_4.py](llms/claude_examples/claude_4.py) - Claude 4 implementation +- [swarms_claude_example.py](llms/claude_examples/swarms_claude_example.py) - Swarms Claude integration + +### DeepSeek +- [deepseek_r1.py](llms/deepseek_examples/deepseek_r1.py) - DeepSeek R1 model +- [fast_r1_groq.py](llms/deepseek_examples/fast_r1_groq.py) - Fast R1 with Groq +- [grok_deepseek_agent.py](llms/deepseek_examples/grok_deepseek_agent.py) - Grok DeepSeek integration + +### Mistral +- [mistral_example.py](llms/mistral_example.py) - Mistral model integration + +### OpenAI +- [4o_mini_demo.py](llms/openai_examples/4o_mini_demo.py) - GPT-4o Mini demonstration +- [reasoning_duo_batched.py](llms/openai_examples/reasoning_duo_batched.py) - Batched reasoning with OpenAI +- [test_async_litellm.py](llms/openai_examples/test_async_litellm.py) - Async LiteLLM testing + +### Qwen +- [qwen_3_base.py](llms/qwen_3_base.py) - Qwen 3 base model + +## Onboarding +- [agents.yaml](onboard/agents.yaml) - Agent configuration file +- [onboard-basic.py](onboard/onboard-basic.py) - Basic onboarding example + +## RAG (Retrieval Augmented Generation) +- [full_agent_rag_example.py](rag/full_agent_rag_example.py) - Complete RAG implementation +- [pinecone_example.py](rag/pinecone_example.py) - Pinecone vector database integration +- [qdrant_agent.py](rag/qdrant_agent.py) - Qdrant vector database agent +- [qdrant_rag_example.py](rag/qdrant_rag_example.py) - Qdrant RAG implementation +- [simple_example.py](rag/simple_example.py) - Simple RAG example +- [README.md](rag/README.md) - RAG documentation + +## Reasoning Agents +- [agent_judge_evaluation_criteria_example.py](reasoning_agent_examples/agent_judge_evaluation_criteria_example.py) - Evaluation criteria for agent judging +- [agent_judge_example.py](reasoning_agent_examples/agent_judge_example.py) - Agent judging system +- [consistency_agent.py](reasoning_agent_examples/consistency_agent.py) - Consistency checking agent +- [consistency_example.py](reasoning_agent_examples/consistency_example.py) - Consistency example +- [gpk_agent.py](reasoning_agent_examples/gpk_agent.py) - GPK reasoning agent +- [iterative_agent.py](reasoning_agent_examples/iterative_agent.py) - Iterative reasoning agent +- [malt_example.py](reasoning_agent_examples/malt_example.py) - MALT reasoning example +- [reasoning_agent_router_now.py](reasoning_agent_examples/reasoning_agent_router_now.py) - Current reasoning router +- [reasoning_agent_router.py](reasoning_agent_examples/reasoning_agent_router.py) - Reasoning agent router +- [reasoning_duo_example.py](reasoning_agent_examples/reasoning_duo_example.py) - Two-agent reasoning +- [reasoning_duo_test.py](reasoning_agent_examples/reasoning_duo_test.py) - Reasoning duo testing +- [reasoning_duo.py](reasoning_agent_examples/reasoning_duo.py) - Reasoning duo implementation + +## Tools Integration +- [exa_search_agent.py](tools/exa_search_agent.py) - Exa search integration +- [example_async_vs_multithread.py](tools/example_async_vs_multithread.py) - Async vs multithreading comparison +- [litellm_tool_example.py](tools/litellm_tool_example.py) - LiteLLM tool integration +- [multi_tool_usage_agent.py](tools/multi_tool_usage_agent.py) - Multi-tool agent +- [new_tools_examples.py](tools/new_tools_examples.py) - Latest tool examples +- [omni_modal_agent.py](tools/omni_modal_agent.py) - Omni-modal agent +- [swarms_of_browser_agents.py](tools/swarms_of_browser_agents.py) - Browser automation swarms +- [swarms_tools_example.py](tools/swarms_tools_example.py) - Swarms tools integration +- [together_deepseek_agent.py](tools/together_deepseek_agent.py) - Together AI DeepSeek integration + +### Solana Tools +- [solana_tool.py](tools/solana_tool/solana_tool.py) - Solana blockchain integration +- [solana_tool_test.py](tools/solana_tool/solana_tool_test.py) - Solana tool testing + +### Structured Outputs +- [example_meaning_of_life_agents.py](tools/structured_outputs/example_meaning_of_life_agents.py) - Meaning of life example +- [structured_outputs_example.py](tools/structured_outputs/structured_outputs_example.py) - Structured output examples + +### Tools Examples +- [dex_screener.py](tools/tools_examples/dex_screener.py) - DEX screener tool +- [financial_news_agent.py](tools/tools_examples/financial_news_agent.py) - Financial news agent +- [simple_tool_example.py](tools/tools_examples/simple_tool_example.py) - Simple tool usage +- [swarms_tool_example_simple.py](tools/tools_examples/swarms_tool_example_simple.py) - Simple Swarms tool + +## Utils +- [async_agent.py](utils/async_agent.py) - Async agent implementation +- [dynamic_context_window.py](utils/dynamic_context_window.py) - Dynamic context window management +- [fallback_test.py](utils/fallback_test.py) - Fallback mechanism testing +- [grok_4_agent.py](utils/grok_4_agent.py) - Grok 4 agent implementation +- [handoffs_example.py](utils/handoffs_example.py) - Agent handoff examples +- [list_agent_output_types.py](utils/list_agent_output_types.py) - Output type listing +- [markdown_agent.py](utils/markdown_agent.py) - Markdown processing agent +- [xml_output_example.py](utils/xml_output_example.py) - XML output example + +### Transform Prompts +- [transforms_agent_example.py](utils/transform_prompts/transforms_agent_example.py) - Prompt transformation agent +- [transforms_examples.py](utils/transform_prompts/transforms_examples.py) - Prompt transformation examples + +## Vision +- [anthropic_vision_test.py](vision/anthropic_vision_test.py) - Anthropic vision testing +- [image_batch_example.py](vision/image_batch_example.py) - Batch image processing +- [multimodal_example.py](vision/multimodal_example.py) - Multimodal agent example +- [multiple_image_processing.py](vision/multiple_image_processing.py) - Multiple image processing +- [vision_test.py](vision/vision_test.py) - Vision testing +- [vision_tools.py](vision/vision_tools.py) - Vision tools integration + +## Main Files +- [simple_agent.py](simple_agent.py) - Basic single agent example diff --git a/examples/single_agent/tools/omni_modal_agent.py b/examples/single_agent/tools/omni_modal_agent.py index a075535d..242a1171 100644 --- a/examples/single_agent/tools/omni_modal_agent.py +++ b/examples/single_agent/tools/omni_modal_agent.py @@ -1,7 +1,8 @@ -from typing import Dict, Union, Any import os -import requests from enum import Enum +from typing import Any, Dict, Union + +import requests from dotenv import load_dotenv load_dotenv() diff --git a/examples/single_agent/tools/swarms_tools_example.py b/examples/single_agent/tools/swarms_tools_example.py index 9aec628f..c381d5ea 100644 --- a/examples/single_agent/tools/swarms_tools_example.py +++ b/examples/single_agent/tools/swarms_tools_example.py @@ -1,20 +1,14 @@ from swarms import Agent -from swarms.prompts.finance_agent_sys_prompt import ( - FINANCIAL_AGENT_SYS_PROMPT, -) -from swarms_tools import yahoo_finance_api +from swarms_tools.finance.okx_tool import okx_api_tool # Initialize the agent agent = Agent( agent_name="Financial-Analysis-Agent", agent_description="Personal finance advisor agent", - system_prompt=FINANCIAL_AGENT_SYS_PROMPT, max_loops=1, model_name="gpt-4o-mini", - tools=[yahoo_finance_api], + tools=[okx_api_tool], dynamic_temperature_enabled=True, ) -agent.run( - "Fetch the data for nvidia and tesla both with the yahoo finance api" -) +agent.run("fetch the current price of bitcoin with okx") diff --git a/examples/single_agent/utils/fallback_test.py b/examples/single_agent/utils/fallback_test.py new file mode 100644 index 00000000..c0c6c5bd --- /dev/null +++ b/examples/single_agent/utils/fallback_test.py @@ -0,0 +1,23 @@ +from swarms.structs.agent import Agent + +# Initialize the agent +agent = Agent( + agent_name="Quantitative-Trading-Agent", + agent_description="Advanced quantitative trading and algorithmic analysis agent", + model_name="claude-sonnetfwoeewe-4-20250514", + dynamic_temperature_enabled=True, + max_loops=1, + fallback_models=[ + "gpt-4o-mini", + ], + dynamic_context_window=True, + streaming_on=False, + print_on=True, + verbose=False, +) + +out = agent.run( + task="What are the top five best energy stocks across nuclear, solar, gas, and other energy sources?", +) + +print(out) diff --git a/examples/single_agent/utils/handoffs_example.py b/examples/single_agent/utils/handoffs_example.py new file mode 100644 index 00000000..345d69fa --- /dev/null +++ b/examples/single_agent/utils/handoffs_example.py @@ -0,0 +1,63 @@ +from swarms.structs.agent import Agent + +# Agent 1: Risk Metrics Calculator +risk_metrics_agent = Agent( + agent_name="Risk-Metrics-Calculator", + agent_description="Calculates key risk metrics like VaR, Sharpe ratio, and volatility", + system_prompt="""You are a risk metrics specialist. Calculate and explain: + - Value at Risk (VaR) + - Sharpe ratio + - Volatility + - Maximum drawdown + - Beta coefficient + + Provide clear, numerical results with brief explanations.""", + max_loops=1, + model_name="gpt-4o-mini", + dynamic_temperature_enabled=True, +) + + +# Agent 3: Market Risk Monitor +market_risk_agent = Agent( + agent_name="Market-Risk-Monitor", + agent_description="Monitors market conditions and identifies risk factors", + system_prompt="""You are a market risk monitor. Identify and assess: + - Market volatility trends + - Economic risk factors + - Geopolitical risks + - Interest rate risks + - Currency risks + + Provide current risk alerts and trends.""", + max_loops=1, + dynamic_temperature_enabled=True, +) + + +# Agent 2: Portfolio Risk Analyzer +portfolio_risk_agent = Agent( + agent_name="Portfolio-Risk-Analyzer", + agent_description="Analyzes portfolio diversification and concentration risk", + system_prompt="""You are a portfolio risk analyst. Focus on: + - Portfolio diversification analysis + - Concentration risk assessment + - Correlation analysis + - Sector/asset allocation risk + - Liquidity risk evaluation + + Provide actionable insights for risk reduction.""", + max_loops=1, + dynamic_temperature_enabled=True, + handoffs=[ + risk_metrics_agent, + market_risk_agent, + ], +) + + +out = portfolio_risk_agent.run( + "Calculate VaR and Sharpe ratio for a portfolio with 15% annual return and 20% volatility using the risk metrics agent and market risk agent" +) + +print(out) diff --git a/examples/swarms_api_examples/README.md b/examples/swarms_api_examples/README.md new file mode 100644 index 00000000..7092e1fb --- /dev/null +++ b/examples/swarms_api_examples/README.md @@ -0,0 +1,22 @@ +# Swarms API Examples + +This directory contains examples demonstrating how to use the Swarms API for various agent operations. + +## Agent Overview +- [agent_overview.py](agent_overview.py) - Comprehensive overview of agent capabilities + +## Batch Processing +- [batch_example.py](batch_example.py) - Batch processing with multiple agents + +## Client Integration +- [client_example.py](client_example.py) - Basic client usage example + +## Team Examples +- [hospital_team.py](hospital_team.py) - Hospital management team simulation +- [legal_team.py](legal_team.py) - Legal team collaboration example + +## Analysis Examples +- [icd_ten_analysis.py](icd_ten_analysis.py) - ICD-10 medical code analysis + +## Rate Limiting +- [rate_limits.py](rate_limits.py) - Rate limiting and throttling examples diff --git a/examples/tools/README.md b/examples/tools/README.md new file mode 100644 index 00000000..a7b7ddb1 --- /dev/null +++ b/examples/tools/README.md @@ -0,0 +1,45 @@ +# Tools Examples + +This directory contains examples demonstrating various tool integrations and usage patterns in Swarms. + +## Agent as Tools +- [agent_as_tools.py](agent_as_tools.py) - Using agents as tools in workflows + +## Base Tool Examples +- [base_tool_examples.py](base_tool_examples/base_tool_examples.py) - Core base tool functionality +- [conver_funcs_to_schema.py](base_tool_examples/conver_funcs_to_schema.py) - Function to schema conversion +- [convert_basemodels.py](base_tool_examples/convert_basemodels.py) - BaseModel conversion utilities +- [exa_search_test.py](base_tool_examples/exa_search_test.py) - Exa search testing +- [example_usage.py](base_tool_examples/example_usage.py) - Basic usage examples +- [schema_validation_example.py](base_tool_examples/schema_validation_example.py) - Schema validation +- [test_anthropic_specific.py](base_tool_examples/test_anthropic_specific.py) - Anthropic-specific testing +- [test_base_tool_comprehensive_fixed.py](base_tool_examples/test_base_tool_comprehensive_fixed.py) - Comprehensive testing (fixed) +- [test_base_tool_comprehensive.py](base_tool_examples/test_base_tool_comprehensive.py) - Comprehensive testing +- [test_function_calls_anthropic.py](base_tool_examples/test_function_calls_anthropic.py) - Anthropic function calls +- [test_function_calls.py](base_tool_examples/test_function_calls.py) - Function call testing + +## Browser Integration +- [browser_use_as_tool.py](browser_use_as_tool.py) - Browser automation as a tool +- [browser_use_demo.py](browser_use_demo.py) - Browser automation demonstration + +## Claude Integration +- [claude_as_a_tool.py](claude_as_a_tool.py) - Using Claude as a tool + +## Exa Search +- [exa_search_agent.py](exa_search_agent.py) - Exa search agent implementation + +## Firecrawl Integration +- [firecrawl_agents_example.py](firecrawl_agents_example.py) - Firecrawl web scraping agents + +## Multi-Tool Usage +- [many_tool_use_demo.py](multii_tool_use/many_tool_use_demo.py) - Multiple tool usage demonstration +- [multi_tool_anthropic.py](multii_tool_use/multi_tool_anthropic.py) - Multi-tool with Anthropic + +## Stagehand Integration +- [1_stagehand_wrapper_agent.py](stagehand/1_stagehand_wrapper_agent.py) - Stagehand wrapper agent +- [2_stagehand_tools_agent.py](stagehand/2_stagehand_tools_agent.py) - Stagehand tools agent +- [3_stagehand_mcp_agent.py](stagehand/3_stagehand_mcp_agent.py) - Stagehand MCP agent +- [4_stagehand_multi_agent_workflow.py](stagehand/4_stagehand_multi_agent_workflow.py) - Multi-agent workflow +- [README.md](stagehand/README.md) - Stagehand documentation +- [requirements.txt](stagehand/requirements.txt) - Stagehand dependencies +- [tests/](stagehand/tests/) - Stagehand testing suite diff --git a/examples/ui/README.md b/examples/ui/README.md new file mode 100644 index 00000000..ddef2a0a --- /dev/null +++ b/examples/ui/README.md @@ -0,0 +1,6 @@ +# UI Examples + +This directory contains user interface examples and implementations for Swarms. + +## Chat Interface +- [chat.py](chat.py) - Chat interface implementation diff --git a/examples/utils/README.md b/examples/utils/README.md new file mode 100644 index 00000000..7e7c23d6 --- /dev/null +++ b/examples/utils/README.md @@ -0,0 +1,40 @@ +# Utils Examples + +This directory contains utility examples and helper functions for various Swarms operations. + +## Agent Loader +- [agent_loader_demo.py](agent_loader/agent_loader_demo.py) - Agent loading demonstration +- [claude_code_compatible.py](agent_loader/claude_code_compatible.py) - Claude code compatibility +- [finance_advisor.md](agent_loader/finance_advisor.md) - Finance advisor documentation +- [multi_agents_loader_demo.py](agent_loader/multi_agents_loader_demo.py) - Multi-agent loading demo + +## Communication Examples +- [duckdb_agent.py](communication_examples/duckdb_agent.py) - DuckDB database agent +- [pulsar_conversation.py](communication_examples/pulsar_conversation.py) - Apache Pulsar messaging +- [redis_conversation.py](communication_examples/redis_conversation.py) - Redis-based conversations +- [sqlite_conversation.py](communication_examples/sqlite_conversation.py) - SQLite conversation storage + +## Concurrent Wrapper +- [concurrent_wrapper_examples.py](concurrent_wrapper_examples.py) - Concurrent execution wrapper examples + +## Miscellaneous +- [agent_map_test.py](misc/agent_map_test.py) - Agent mapping testing +- [conversation_simple.py](misc/conversation_simple.py) - Simple conversation handling +- [conversation_test_truncate.py](misc/conversation_test_truncate.py) - Conversation truncation testing +- [conversation_test.py](misc/conversation_test.py) - Conversation testing +- [csvagent_example.py](misc/csvagent_example.py) - CSV processing agent +- [dict_to_table.py](misc/dict_to_table.py) - Dictionary to table conversion +- [swarm_matcher_example.py](misc/swarm_matcher_example.py) - Swarm matching utilities +- [test_load_conversation.py](misc/test_load_conversation.py) - Conversation loading tests +- [visualizer_test.py](misc/visualizer_test.py) - Visualization testing + +### AOP (Aspect-Oriented Programming) +- [client.py](misc/aop/client.py) - AOP client implementation +- [test_aop.py](misc/aop/test_aop.py) - AOP testing + +### Conversation Structure +- [conversation_example_supabase.py](misc/conversation_structure/conversation_example_supabase.py) - Supabase conversation example + +## Telemetry +- [class_method_example.py](telemetry/class_method_example.py) - Class method telemetry +- [example_decorator_usage.py](telemetry/example_decorator_usage.py) - Decorator usage examples diff --git a/examples/workshops/README.md b/examples/workshops/README.md new file mode 100644 index 00000000..71800c9b --- /dev/null +++ b/examples/workshops/README.md @@ -0,0 +1,15 @@ +# Workshop Examples + +This directory contains examples from workshops and educational sessions. + +## Workshop September 20 +- [agent_tools_dict_example.py](workshop_sep_20/agent_tools_dict_example.py) - Agent tools dictionary example +- [batched_grid_simple_example.py](workshop_sep_20/batched_grid_simple_example.py) - Simple batched grid example +- [geo_guesser_agent.py](workshop_sep_20/geo_guesser_agent.py) - Geographic location guessing agent +- [jarvis_agent.py](workshop_sep_20/jarvis_agent.py) - Jarvis AI assistant +- [same_task_example.py](workshop_sep_20/same_task_example.py) - Same task execution example + +### Sample Images +- [hk.jpg](workshop_sep_20/hk.jpg) - Hong Kong sample image +- [miami.jpg](workshop_sep_20/miami.jpg) - Miami sample image +- [mountains.jpg](workshop_sep_20/mountains.jpg) - Mountains sample image 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..ad4d1ba7 --- /dev/null +++ b/examples/workshops/workshop_sep_20/jarvis_agent.py @@ -0,0 +1,25 @@ +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/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 66f08be6..9095ce51 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api" [tool.poetry] name = "swarms" -version = "8.2.2" +version = "8.3.0" description = "Swarms - TGSC" license = "MIT" authors = ["Kye Gomez "] @@ -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..b40061df 100644 --- a/scripts/setup.sh +++ b/scripts/setup.sh @@ -38,36 +38,90 @@ print_status "Starting Swarms development environment setup..." # Check Python version print_status "Checking Python version..." -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" + +# 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 '$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 - + + # 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" @@ -77,7 +131,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 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" +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/spreadsheet_example.py b/spreadsheet_example.py new file mode 100644 index 00000000..3be9fe8f --- /dev/null +++ b/spreadsheet_example.py @@ -0,0 +1,46 @@ +from swarms import Agent +from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm + +# Example 1: Using pre-configured agents +agents = [ + Agent( + agent_name="Research-Agent", + agent_description="Specialized in market research and analysis", + model_name="claude-sonnet-4-20250514", + dynamic_temperature_enabled=True, + max_loops=1, + streaming_on=False, + ), + Agent( + agent_name="Technical-Agent", + agent_description="Expert in technical analysis and trading strategies", + model_name="claude-sonnet-4-20250514", + dynamic_temperature_enabled=True, + max_loops=1, + streaming_on=False, + ), + Agent( + agent_name="Risk-Agent", + agent_description="Focused on risk assessment and portfolio management", + model_name="claude-sonnet-4-20250514", + dynamic_temperature_enabled=True, + max_loops=1, + streaming_on=False, + ), +] + +# Initialize the SpreadSheetSwarm with agents +swarm = SpreadSheetSwarm( + name="Financial-Analysis-Swarm", + description="A swarm of specialized financial analysis agents", + agents=agents, + max_loops=1, + autosave=False, + workspace_dir="./swarm_outputs", +) + +# Run all agents with the same task +task = "What are the top 3 energy stocks to invest in for 2024? Provide detailed analysis." +result = swarm.run(task=task) + +print(result) diff --git a/swarms/structs/agent.py b/swarms/structs/agent.py index 578f42a6..970c2a7a 100644 --- a/swarms/structs/agent.py +++ b/swarms/structs/agent.py @@ -14,7 +14,9 @@ from typing import ( Callable, Dict, List, + Literal, Optional, + Sequence, Tuple, Union, ) @@ -22,6 +24,11 @@ from typing import ( import toml import yaml from litellm import model_list +from litellm.exceptions import ( + AuthenticationError, + BadRequestError, + InternalServerError, +) from litellm.utils import ( get_max_tokens, supports_function_calling, @@ -57,15 +64,16 @@ from swarms.schemas.mcp_schemas import ( from swarms.structs.agent_roles import agent_roles from swarms.structs.conversation import Conversation from swarms.structs.ma_utils import set_random_models_for_agents +from swarms.structs.multi_agent_router import MultiAgentRouter +from swarms.structs.safe_loading import ( + SafeLoaderUtils, + SafeStateManager, +) from swarms.structs.transforms import ( MessageTransforms, TransformConfig, handle_transforms, ) -from swarms.structs.safe_loading import ( - SafeLoaderUtils, - SafeStateManager, -) from swarms.telemetry.main import log_agent_data from swarms.tools.base_tool import BaseTool from swarms.tools.mcp_client_tools import ( @@ -202,6 +210,8 @@ class Agent: list_of_pdf (str): The list of pdf tokenizer (Any): The tokenizer long_term_memory (BaseVectorDatabase): The long term memory + fallback_model_name (str): The fallback model name to use if primary model fails + fallback_models (List[str]): List of model names to try in order. First model is primary, rest are fallbacks preset_stopping_token (bool): Enable preset stopping token traceback (Any): The traceback traceback_handlers (Any): The traceback handlers @@ -302,6 +312,14 @@ class Agent: >>> response = agent.run("Tell me a long story.") # Will stream in real-time >>> print(response) # Final complete response + >>> # Fallback model example + >>> agent = Agent( + ... fallback_models=["gpt-4o", "gpt-4o-mini", "gpt-3.5-turbo"], + ... max_loops=1 + ... ) + >>> response = agent.run("Generate a report on the financials.") + >>> # Will try gpt-4o first, then gpt-4o-mini, then gpt-3.5-turbo if each fails + """ def __init__( @@ -340,6 +358,7 @@ class Agent: tokenizer: Optional[Any] = None, long_term_memory: Optional[Union[Callable, Any]] = None, fallback_model_name: Optional[str] = None, + fallback_models: Optional[List[str]] = None, preset_stopping_token: Optional[bool] = False, traceback: Optional[Any] = None, traceback_handlers: Optional[Any] = None, @@ -444,6 +463,9 @@ class Agent: drop_params: bool = True, thinking_tokens: int = None, reasoning_enabled: bool = False, + handoffs: Optional[Union[Sequence[Callable], Any]] = None, + capabilities: Optional[List[str]] = None, + mode: Literal["interactive", "fast", "standard"] = "standard", *args, **kwargs, ): @@ -467,19 +489,6 @@ class Agent: self.user_name = user_name self.context_length = context_length - # Initialize transforms - if transforms is None: - self.transforms = None - elif isinstance(transforms, TransformConfig): - self.transforms = MessageTransforms(transforms) - elif isinstance(transforms, dict): - config = TransformConfig(**transforms) - self.transforms = MessageTransforms(config) - else: - raise ValueError( - "transforms must be a TransformConfig object or a dictionary" - ) - self.sop = sop self.sop_list = sop_list self.tools = tools @@ -605,6 +614,28 @@ class Agent: self.thinking_tokens = thinking_tokens self.reasoning_enabled = reasoning_enabled self.fallback_model_name = fallback_model_name + self.handoffs = handoffs + self.capabilities = capabilities + self.mode = mode + + # Initialize transforms + if transforms is None: + self.transforms = None + elif isinstance(transforms, TransformConfig): + self.transforms = MessageTransforms(transforms) + elif isinstance(transforms, dict): + config = TransformConfig(**transforms) + self.transforms = MessageTransforms(config) + else: + pass + + self.fallback_models = fallback_models or [] + self.current_model_index = 0 + self.model_attempts = {} + + # If fallback_models is provided, use the first model as the primary model + if self.fallback_models and not self.model_name: + self.model_name = self.fallback_models[0] # self.init_handling() self.setup_config() @@ -655,6 +686,22 @@ 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, + description=self.agent_description, + agents=self.handoffs, + model=self.model_name, + temperature=self.temperature, + output_type=self.output_type, + ) + + return router.run(task=task) + def setup_tools(self): return BaseTool( tools=self.tools, @@ -729,6 +776,12 @@ class Agent: if self.model_name is None: self.model_name = "gpt-4o-mini" + # Use current model (which may be a fallback) only if fallbacks are configured + if self.fallback_models: + current_model = self.get_current_model() + else: + current_model = self.model_name + # Determine if parallel tool calls should be enabled if exists(self.tools) and len(self.tools) >= 2: parallel_tool_calls = True @@ -742,7 +795,7 @@ class Agent: try: # Base configuration that's always included common_args = { - "model_name": self.model_name, + "model_name": current_model, "temperature": self.temperature, "max_tokens": self.max_tokens, "system_prompt": self.system_prompt, @@ -1278,7 +1331,12 @@ class Agent: success = True # Mark as successful to exit the retry loop - except Exception as e: + except ( + BadRequestError, + InternalServerError, + AuthenticationError, + Exception, + ) as e: if self.autosave is True: log_agent_data(self.to_dict()) @@ -2551,9 +2609,16 @@ class Agent: return out - except AgentLLMError as e: + except ( + AgentLLMError, + BadRequestError, + InternalServerError, + AuthenticationError, + Exception, + ) as e: logger.error( - f"Error calling LLM: {e}. Task: {task}, Args: {args}, Kwargs: {kwargs} Traceback: {traceback.format_exc()}" + f"Error calling LLM with model '{self.get_current_model()}': {e}. " + f"Task: {task}, Args: {args}, Kwargs: {kwargs} Traceback: {traceback.format_exc()}" ) raise e @@ -2621,6 +2686,8 @@ class Agent: *args, **kwargs, ) + elif exists(self.handoffs): + output = self.handle_handoffs(task=task) else: output = self._run( task=task, @@ -2632,8 +2699,78 @@ class Agent: return output - except AgentRunError as e: - self._handle_run_error(e) + except ( + AgentRunError, + AgentLLMError, + BadRequestError, + InternalServerError, + AuthenticationError, + Exception, + ) as e: + # Try fallback models if available + if ( + self.is_fallback_available() + and self.switch_to_next_model() + ): + # Always log fallback events, regardless of verbose setting + if self.verbose: + logger.warning( + f"⚠️ [FALLBACK] Agent '{self.agent_name}' failed with model '{self.get_current_model()}'. " + f"Switching to fallback model '{self.get_current_model()}' (attempt {self.current_model_index + 1}/{len(self.get_available_models())})" + ) + try: + # Recursive call to run() with the new model + result = self.run( + task=task, + img=img, + imgs=imgs, + correct_answer=correct_answer, + streaming_callback=streaming_callback, + *args, + **kwargs, + ) + if self.verbose: + # Log successful completion with fallback model + logger.info( + f"✅ [FALLBACK SUCCESS] Agent '{self.agent_name}' successfully completed task " + f"using fallback model '{self.get_current_model()}'" + ) + return result + except Exception as fallback_error: + logger.error( + f"Fallback model '{self.get_current_model()}' also failed: {fallback_error}" + ) + # Continue to next fallback or raise if no more models + if ( + self.is_fallback_available() + and self.switch_to_next_model() + ): + return self.run( + task=task, + img=img, + imgs=imgs, + correct_answer=correct_answer, + streaming_callback=streaming_callback, + *args, + **kwargs, + ) + else: + if self.verbose: + logger.error( + f"❌ [FALLBACK EXHAUSTED] Agent '{self.agent_name}' has exhausted all available models. " + f"Tried {len(self.get_available_models())} models: {self.get_available_models()}" + ) + + self._handle_run_error(e) + else: + if self.verbose: + # No fallback available + logger.error( + f"❌ [NO FALLBACK] Agent '{self.agent_name}' failed with model '{self.get_current_model()}' " + f"and no fallback models are configured. Error: {str(e)[:100]}{'...' if len(str(e)) > 100 else ''}" + ) + + self._handle_run_error(e) except KeyboardInterrupt: logger.warning( @@ -2976,6 +3113,98 @@ class Agent: api_key=self.llm_api_key, ) + def get_available_models(self) -> List[str]: + """ + Get the list of available models including primary and fallback models. + + Returns: + List[str]: List of model names in order of preference + """ + models = [] + + # If fallback_models is specified, use it as the primary list + if self.fallback_models: + models = self.fallback_models.copy() + else: + # Otherwise, build the list from individual parameters + if self.model_name: + models.append(self.model_name) + if ( + self.fallback_model_name + and self.fallback_model_name not in models + ): + models.append(self.fallback_model_name) + + return models + + def get_current_model(self) -> str: + """ + Get the current model being used. + + Returns: + str: Current model name + """ + available_models = self.get_available_models() + if self.current_model_index < len(available_models): + return available_models[self.current_model_index] + return ( + available_models[0] if available_models else "gpt-4o-mini" + ) + + def switch_to_next_model(self) -> bool: + """ + Switch to the next available model in the fallback list. + + Returns: + bool: True if successfully switched to next model, False if no more models available + """ + available_models = self.get_available_models() + + if self.current_model_index + 1 < len(available_models): + previous_model = ( + available_models[self.current_model_index] + if self.current_model_index < len(available_models) + else "Unknown" + ) + self.current_model_index += 1 + new_model = available_models[self.current_model_index] + + # Always log model switches + logger.warning( + f"🔄 [MODEL SWITCH] Agent '{self.agent_name}' switching from '{previous_model}' to fallback model: '{new_model}' " + f"(attempt {self.current_model_index + 1}/{len(available_models)})" + ) + + # Update the model name and reinitialize LLM + self.model_name = new_model + self.llm = self.llm_handling() + + return True + else: + logger.error( + f"❌ [NO MORE MODELS] Agent '{self.agent_name}' has exhausted all available models. " + f"Tried {len(available_models)} models: {available_models}" + ) + return False + + def reset_model_index(self) -> None: + """Reset the model index to use the primary model.""" + self.current_model_index = 0 + available_models = self.get_available_models() + if available_models: + self.model_name = available_models[0] + self.llm = self.llm_handling() + + def is_fallback_available(self) -> bool: + """ + Check if fallback models are available. + + Returns: + bool: True if fallback models are configured + """ + available_models = self.get_available_models() + return len(available_models) > 1 + def execute_tools(self, response: any, loop_count: int): # Handle None response gracefully if response is None: diff --git a/swarms/structs/agent_rearrange.py b/swarms/structs/agent_rearrange.py index a4f4944f..d3016de4 100644 --- a/swarms/structs/agent_rearrange.py +++ b/swarms/structs/agent_rearrange.py @@ -4,6 +4,8 @@ from typing import Any, Callable, Dict, List, Optional, Union from swarms.structs.agent import Agent from swarms.structs.conversation import Conversation +from swarms.structs.multi_agent_exec import run_agents_concurrently +from swarms.structs.swarm_id import swarm_id from swarms.telemetry.main import log_agent_data from swarms.utils.any_to_str import any_to_str from swarms.utils.history_output_formatter import ( @@ -11,12 +13,75 @@ from swarms.utils.history_output_formatter import ( ) from swarms.utils.loguru_logger import initialize_logger from swarms.utils.output_types import OutputType -from swarms.structs.swarm_id import swarm_id logger = initialize_logger(log_folder="rearrange") class AgentRearrange: + """ + A sophisticated multi-agent system for task rearrangement and orchestration. + + The AgentRearrange class enables complex workflows where multiple agents can work + sequentially or concurrently based on a defined flow pattern. It supports both + sequential execution (using '->') and concurrent execution (using ',') within + the same workflow. + + Key Features: + - Sequential and concurrent agent execution + - Custom flow patterns with arrow (->) and comma (,) syntax + - Team awareness and sequential flow information + - Human-in-the-loop integration + - Memory system support + - Batch and concurrent processing capabilities + - Comprehensive error handling and logging + + Flow Syntax: + - Use '->' to define sequential execution: "agent1 -> agent2 -> agent3" + - Use ',' to define concurrent execution: "agent1, agent2 -> agent3" + - Combine both: "agent1 -> agent2, agent3 -> agent4" + - Use 'H' for human-in-the-loop: "agent1 -> H -> agent2" + + Attributes: + id (str): Unique identifier for the agent rearrange system + name (str): Human-readable name for the system + description (str): Description of the system's purpose + agents (Dict[str, Agent]): Dictionary mapping agent names to Agent objects + flow (str): Flow pattern defining agent execution order + max_loops (int): Maximum number of execution loops + verbose (bool): Whether to enable verbose logging + memory_system (Any): Optional memory system for persistence + human_in_the_loop (bool): Whether to enable human interaction + custom_human_in_the_loop (Callable): Custom human interaction handler + output_type (OutputType): Format for output results + autosave (bool): Whether to automatically save execution data + rules (str): System rules and constraints + team_awareness (bool): Whether agents are aware of team structure + time_enabled (bool): Whether to track timestamps + message_id_on (bool): Whether to include message IDs + conversation (Conversation): Conversation history management + + Example: + >>> from swarms import Agent, AgentRearrange + >>> + >>> # Create agents + >>> agent1 = Agent(name="researcher", ...) + >>> agent2 = Agent(name="writer", ...) + >>> agent3 = Agent(name="reviewer", ...) + >>> + >>> # Define flow: agent1 runs first, then agent2 and agent3 run concurrently + >>> flow = "researcher -> writer, reviewer" + >>> + >>> # Create rearrange system + >>> rearrange_system = AgentRearrange( + ... agents=[agent1, agent2, agent3], + ... flow=flow, + ... max_loops=1, + ... team_awareness=True + ... ) + >>> + >>> # Execute task + >>> result = rearrange_system.run("Research and write a report") + """ def __init__( self, @@ -38,9 +103,55 @@ class AgentRearrange: team_awareness: bool = False, time_enabled: bool = False, message_id_on: bool = False, - *args, - **kwargs, ): + """ + Initialize the AgentRearrange system. + + Args: + id (str): Unique identifier for the agent rearrange system. + Defaults to a generated swarm ID. + name (str): Human-readable name for the system. + Defaults to "AgentRearrange". + description (str): Description of the system's purpose. + Defaults to "A swarm of agents for rearranging tasks.". + agents (List[Union[Agent, Callable]], optional): List of agents to include + in the system. Can be Agent objects or callable functions. + Defaults to None. + flow (str, optional): Flow pattern defining agent execution order. + Uses '->' for sequential and ',' for concurrent execution. + Defaults to None. + max_loops (int): Maximum number of execution loops. Must be > 0. + Defaults to 1. + verbose (bool): Whether to enable verbose logging. + Defaults to True. + memory_system (Any, optional): Optional memory system for persistence. + Defaults to None. + human_in_the_loop (bool): Whether to enable human interaction points. + Defaults to False. + custom_human_in_the_loop (Callable[[str], str], optional): Custom function + for handling human interaction. Takes input string, returns response. + Defaults to None. + output_type (OutputType): Format for output results. Can be "all", "final", + "list", or "dict". Defaults to "all". + autosave (bool): Whether to automatically save execution data. + Defaults to True. + rules (str, optional): System rules and constraints to add to conversation. + Defaults to None. + team_awareness (bool): Whether agents should be aware of team structure + and sequential flow. Defaults to False. + time_enabled (bool): Whether to track timestamps in conversations. + Defaults to False. + message_id_on (bool): Whether to include message IDs in conversations. + Defaults to False. + + Raises: + ValueError: If agents list is None or empty, max_loops is 0, + flow is None or empty, or output_type is None or empty. + + Note: + The agents parameter is converted to a dictionary mapping agent names + to Agent objects for efficient lookup during execution. + """ self.name = name self.description = description self.id = id @@ -80,6 +191,23 @@ class AgentRearrange: self.reliability_check() def reliability_check(self): + """ + Validates the configuration parameters to ensure the system can run properly. + + Performs comprehensive validation checks on critical parameters including + agents list, max_loops, flow pattern, and output_type to prevent runtime errors. + + Raises: + ValueError: If any of the following conditions are met: + - agents list is None or empty + - max_loops is 0 + - flow is None or empty string + - output_type is None or empty string + + Note: + This method is called automatically during initialization to ensure + the system is properly configured before execution. + """ if self.agents is None or len(self.agents) == 0: raise ValueError("Agents list cannot be None or empty") @@ -93,6 +221,24 @@ class AgentRearrange: raise ValueError("output_type cannot be None or empty") def set_custom_flow(self, flow: str): + """ + Sets a custom flow pattern for agent execution. + + Allows dynamic modification of the execution flow after initialization. + The flow pattern defines how agents should be executed in sequence or + parallel using the standard syntax ('->' for sequential, ',' for concurrent). + + Args: + flow (str): The new flow pattern to use for agent execution. + Must follow the syntax: "agent1 -> agent2, agent3 -> agent4" + + Note: + The flow will be validated on the next execution. If invalid, + a ValueError will be raised during the run() method. + + Example: + >>> rearrange_system.set_custom_flow("researcher -> writer, editor") + """ self.flow = flow logger.info(f"Custom flow set: {flow}") @@ -111,6 +257,20 @@ class AgentRearrange: agent_name: str, result: str, ): + """ + Tracks the execution history for a specific agent. + + Records the result of an agent's execution in the swarm history + for later analysis or debugging purposes. + + Args: + agent_name (str): The name of the agent whose result to track. + result (str): The result/output from the agent's execution. + + Note: + This method is typically called internally during agent execution + to maintain a complete history of all agent activities. + """ self.swarm_history[agent_name].append(result) def remove_agent(self, agent_name: str): @@ -306,6 +466,120 @@ class AgentRearrange: """ return self._get_sequential_flow_info() + def _run_concurrent_workflow( + self, + agent_names: List[str], + img: str = None, + *args, + **kwargs, + ) -> Dict[str, str]: + """ + Executes agents concurrently when comma is detected in the flow. + + This method handles the parallel execution of multiple agents when they + are separated by commas in the flow pattern. All specified agents run + simultaneously and their results are collected and returned. + + Args: + agent_names (List[str]): List of agent names to run concurrently. + These agents will execute in parallel. + img (str, optional): Image input for agents that support it. + Defaults to None. + *args: Additional positional arguments passed to agent execution. + **kwargs: Additional keyword arguments passed to agent execution. + + Returns: + Dict[str, str]: Dictionary mapping agent names to their execution results. + Keys are agent names, values are their respective outputs. + + Note: + This method uses the run_agents_concurrently utility function + to handle the actual parallel execution and result collection. + """ + logger.info(f"Running agents in parallel: {agent_names}") + + # Get agent objects for concurrent execution + agents_to_run = [ + self.agents[agent_name] for agent_name in agent_names + ] + + # Run agents concurrently + results = run_agents_concurrently( + agents=agents_to_run, + task=self.conversation.get_str(), + ) + + # Process results and update conversation + response_dict = {} + for i, agent_name in enumerate(agent_names): + result = results[i] + + # print(f"Result: {result}") + + self.conversation.add(agent_name, result) + response_dict[agent_name] = result + logger.debug(f"Agent {agent_name} output: {result}") + + return response_dict + + def _run_sequential_workflow( + self, + agent_name: str, + tasks: List[str], + img: str = None, + *args, + **kwargs, + ) -> str: + """ + Executes a single agent sequentially. + + This method handles the sequential execution of a single agent in the flow. + It provides sequential awareness information to the agent if team_awareness + is enabled, allowing the agent to understand its position in the workflow. + + Args: + agent_name (str): Name of the agent to run sequentially. + tasks (List[str]): List of all tasks in the flow for awareness context. + Used to determine the agent's position and provide awareness info. + img (str, optional): Image input for agents that support it. + Defaults to None. + *args: Additional positional arguments passed to agent execution. + **kwargs: Additional keyword arguments passed to agent execution. + + Returns: + str: The result from the agent's execution, converted to string format. + + Note: + If team_awareness is enabled, this method will add sequential awareness + information to the conversation before executing the agent, informing + the agent about its position in the workflow sequence. + """ + logger.info(f"Running agent sequentially: {agent_name}") + + agent = self.agents[agent_name] + + # Add sequential awareness information for the agent + awareness_info = self._get_sequential_awareness( + agent_name, tasks + ) + if awareness_info: + self.conversation.add("system", awareness_info) + logger.info( + f"Added sequential awareness for {agent_name}: {awareness_info}" + ) + + current_task = agent.run( + task=self.conversation.get_str(), + img=img, + *args, + **kwargs, + ) + current_task = any_to_str(current_task) + + self.conversation.add(agent.agent_name, current_task) + + return current_task + def _run( self, task: str = None, @@ -315,27 +589,39 @@ class AgentRearrange: **kwargs, ): """ - Runs the swarm to rearrange the tasks. + Runs the swarm to rearrange the tasks according to the defined flow. + + This is the core execution method that orchestrates the entire workflow. + It processes the flow pattern, executes agents sequentially or concurrently + as specified, and returns the results in the requested format. Args: - task (str, optional): The initial task to be processed. Defaults to None. - img (str, optional): Image input for agents that support it. Defaults to None. - custom_tasks (Dict[str, str], optional): Custom tasks for specific agents. Defaults to None. - output_type (str, optional): Format of the output. Can be: + task (str, optional): The initial task to be processed by the swarm. + This is added to the conversation history. Defaults to None. + img (str, optional): Image input for agents that support it. + Defaults to None. + custom_tasks (Dict[str, str], optional): Custom tasks for specific agents. + Allows overriding the main task for specific agents in the flow. + Defaults to None. + *args: Additional positional arguments passed to agent execution. + **kwargs: Additional keyword arguments passed to agent execution. + + Returns: + Union[str, List[str], Dict[str, str]]: The processed output in the format + specified by output_type: - "all": String containing all agent responses concatenated - "final": Only the final agent's response - "list": List of all agent responses - "dict": Dict mapping agent names to their responses - Defaults to "final". - *args: Additional positional arguments - **kwargs: Additional keyword arguments - - Returns: - Union[str, List[str], Dict[str, str]]: The processed output in the specified format Raises: - ValueError: If flow validation fails - Exception: For any other errors during execution + ValueError: If flow validation fails or configuration is invalid. + Exception: For any other errors during execution. + + Note: + This method handles both sequential and concurrent execution patterns + based on the flow syntax. It also supports custom task injection + and multiple execution loops as configured. """ try: self.conversation.add("User", task) @@ -345,14 +631,13 @@ class AgentRearrange: return "Invalid flow configuration." tasks = self.flow.split("->") - current_task = task response_dict = {} logger.info( f"Starting task execution with {len(tasks)} steps" ) - # # Handle custom tasks + # Handle custom tasks if custom_tasks is not None: logger.info("Processing custom tasks") c_agent_name, c_task = next( @@ -377,68 +662,28 @@ class AgentRearrange: ] if len(agent_names) > 1: - # Parallel processing - logger.info( - f"Running agents in parallel: {agent_names}" - ) - - for agent_name in agent_names: - agent = self.agents[agent_name] - result = agent.run( - task=self.conversation.get_str(), + # Concurrent processing - comma detected + concurrent_results = ( + self._run_concurrent_workflow( + agent_names=agent_names, img=img, *args, **kwargs, ) - result = any_to_str(result) - - self.conversation.add( - agent.agent_name, result - ) - - response_dict[agent_name] = result - logger.debug( - f"Agent {agent_name} output: {result}" - ) - - ",".join(agent_names) + ) + response_dict.update(concurrent_results) else: # Sequential processing - logger.info( - f"Running agent sequentially: {agent_names[0]}" - ) agent_name = agent_names[0] - - agent = self.agents[agent_name] - - # Add sequential awareness information for the agent - awareness_info = ( - self._get_sequential_awareness( - agent_name, tasks - ) - ) - if awareness_info: - self.conversation.add( - "system", awareness_info - ) - logger.info( - f"Added sequential awareness for {agent_name}: {awareness_info}" - ) - - current_task = agent.run( - task=self.conversation.get_str(), + result = self._run_sequential_workflow( + agent_name=agent_name, + tasks=tasks, img=img, *args, **kwargs, ) - current_task = any_to_str(current_task) - - self.conversation.add( - agent.agent_name, current_task - ) - - response_dict[agent_name] = current_task + response_dict[agent_name] = result loop_count += 1 @@ -453,11 +698,28 @@ class AgentRearrange: self._catch_error(e) def _catch_error(self, e: Exception): + """ + Handles errors that occur during swarm execution. + + Provides comprehensive error handling including logging, data persistence, + and error reporting. This method is called whenever an exception occurs + during the execution of the swarm. + + Args: + e (Exception): The exception that occurred during execution. + + Returns: + Exception: The original exception for potential re-raising. + + Note: + If autosave is enabled, the current state of the swarm will be + automatically saved to the logging system before error reporting. + """ if self.autosave is True: log_agent_data(self.to_dict()) logger.error( - f"An error occurred with your swarm {self.name}: Error: {e} Traceback: {e.__traceback__}" + f"AgentRearrange: Id: {self.id}, Name: {self.name}. An error occurred with your agent '{self.name}': Error: {e}. Traceback: {e.__traceback__}" ) return e @@ -470,16 +732,28 @@ class AgentRearrange: **kwargs, ): """ - Execute the agent rearrangement task with specified compute resources. + Execute the agent rearrangement task with comprehensive logging and error handling. + + This is the main public method for executing tasks through the agent rearrange + system. It provides telemetry logging, error handling, and delegates to the + internal _run method for actual execution. Args: - task (str, optional): The task to execute. Defaults to None. - img (str, optional): Path to input image if required. Defaults to None. - *args: Additional positional arguments passed to _run(). - **kwargs: Additional keyword arguments passed to _run(). + task (str, optional): The task to execute through the agent workflow. + Defaults to None. + img (str, optional): Path to input image if required by any agents. + Defaults to None. + *args: Additional positional arguments passed to the internal _run() method. + **kwargs: Additional keyword arguments passed to the internal _run() method. Returns: - The result from executing the task through the cluster operations wrapper. + The result from executing the task through the agent rearrange system. + The format depends on the configured output_type. + + Note: + This method automatically logs agent data before and after execution + for telemetry and debugging purposes. Any exceptions are caught and + handled by the _catch_error method. """ try: log_agent_data(self.to_dict()) @@ -502,13 +776,20 @@ class AgentRearrange: """ Make the class callable by executing the run() method. + Enables the AgentRearrange instance to be called directly as a function, + providing a convenient interface for task execution. + Args: - task (str): The task to execute. + task (str): The task to execute through the agent workflow. *args: Additional positional arguments passed to run(). **kwargs: Additional keyword arguments passed to run(). Returns: - The result from executing run(). + The result from executing the task through the agent rearrange system. + + Example: + >>> rearrange_system = AgentRearrange(agents=[agent1, agent2], flow="agent1 -> agent2") + >>> result = rearrange_system("Process this data") """ try: return self.run(task=task, *args, **kwargs) @@ -525,19 +806,29 @@ class AgentRearrange: **kwargs, ) -> List[str]: """ - Process multiple tasks in batches. + Process multiple tasks in batches for efficient execution. + + This method allows processing multiple tasks by dividing them into + smaller batches and processing each batch sequentially. This is useful + for managing memory usage and resource allocation when dealing with + large numbers of tasks. Args: - tasks: List of tasks to process - img: Optional list of images corresponding to tasks - batch_size: Number of tasks to process simultaneously - device: Computing device to use - device_id: Specific device ID if applicable - all_cores: Whether to use all CPU cores - all_gpus: Whether to use all available GPUs + tasks (List[str]): List of tasks to process through the agent workflow. + img (Optional[List[str]]): Optional list of images corresponding to tasks. + Must be the same length as tasks list. Defaults to None. + batch_size (int): Number of tasks to process simultaneously in each batch. + Defaults to 10. + *args: Additional positional arguments passed to individual task execution. + **kwargs: Additional keyword arguments passed to individual task execution. Returns: - List of results corresponding to input tasks + List[str]: List of results corresponding to input tasks in the same order. + + Note: + This method processes tasks in batches to manage resource usage. + Each batch is processed sequentially, but individual tasks within + a batch may run concurrently depending on the flow configuration. """ try: results = [] @@ -576,17 +867,27 @@ class AgentRearrange: """ Process multiple tasks concurrently using ThreadPoolExecutor. + This method enables true parallel processing of multiple tasks by using + Python's ThreadPoolExecutor to run tasks simultaneously across multiple + threads. This is ideal for I/O-bound tasks or when you want maximum + parallelization. + Args: - tasks: List of tasks to process - img: Optional list of images corresponding to tasks - max_workers: Maximum number of worker threads - device: Computing device to use - device_id: Specific device ID if applicable - all_cores: Whether to use all CPU cores - all_gpus: Whether to use all available GPUs + tasks (List[str]): List of tasks to process through the agent workflow. + img (Optional[List[str]]): Optional list of images corresponding to tasks. + Must be the same length as tasks list. Defaults to None. + max_workers (Optional[int]): Maximum number of worker threads to use. + If None, uses the default ThreadPoolExecutor behavior. Defaults to None. + *args: Additional positional arguments passed to individual task execution. + **kwargs: Additional keyword arguments passed to individual task execution. Returns: - List of results corresponding to input tasks + List[str]: List of results corresponding to input tasks in the same order. + + Note: + This method uses ThreadPoolExecutor for true parallel execution. + The number of concurrent executions is limited by max_workers parameter. + Each task runs independently through the full agent workflow. """ try: with ThreadPoolExecutor( @@ -613,11 +914,19 @@ class AgentRearrange: """ Serializes callable attributes by extracting their name and docstring. + This helper method handles the serialization of callable objects (functions, + methods, etc.) by extracting their metadata for storage or logging purposes. + Args: - attr_value (Callable): The callable to serialize. + attr_value (Callable): The callable object to serialize. Returns: - Dict[str, Any]: Dictionary with name and docstring of the callable. + Dict[str, Any]: Dictionary containing the callable's name and docstring. + Keys are "name" and "doc", values are the corresponding attributes. + + Note: + This method is used internally by to_dict() to handle non-serializable + callable attributes in a graceful manner. """ return { "name": getattr( @@ -630,12 +939,22 @@ class AgentRearrange: """ Serializes an individual attribute, handling non-serializable objects. + This helper method attempts to serialize individual attributes for storage + or logging. It handles different types of objects including callables, + objects with to_dict methods, and basic serializable types. + Args: - attr_name (str): The name of the attribute. - attr_value (Any): The value of the attribute. + attr_name (str): The name of the attribute being serialized. + attr_value (Any): The value of the attribute to serialize. Returns: - Any: The serialized value of the attribute. + Any: The serialized value of the attribute. For non-serializable objects, + returns a string representation indicating the object type. + + Note: + This method is used internally by to_dict() to handle various types + of attributes in a robust manner, ensuring the serialization process + doesn't fail on complex objects. """ try: if callable(attr_value): @@ -655,10 +974,21 @@ class AgentRearrange: def to_dict(self) -> Dict[str, Any]: """ Converts all attributes of the class, including callables, into a dictionary. - Handles non-serializable attributes by converting them or skipping them. + + This method provides a comprehensive serialization of the AgentRearrange + instance, converting all attributes into a dictionary format suitable for + storage, logging, or transmission. It handles complex objects gracefully + by using helper methods for serialization. Returns: - Dict[str, Any]: A dictionary representation of the class attributes. + Dict[str, Any]: A dictionary representation of all class attributes. + Non-serializable objects are converted to string representations + or serialized using their to_dict method if available. + + Note: + This method is used for telemetry logging and state persistence. + It recursively handles nested objects and provides fallback handling + for objects that cannot be directly serialized. """ return { attr_name: self._serialize_attr(attr_name, attr_value) @@ -677,23 +1007,45 @@ def rearrange( **kwargs, ): """ - Rearranges the given list of agents based on the specified flow. + Convenience function to create and execute an AgentRearrange system in one call. + + This function provides a simplified interface for creating an AgentRearrange + instance and immediately executing a task with it. It's useful for quick + prototyping or when you don't need to reuse the rearrange system. Parameters: - agents (List[Agent]): The list of agents to be rearranged. - flow (str): The flow used for rearranging the agents. - task (str, optional): The task to be performed during rearrangement. Defaults to None. - *args: Additional positional arguments. - **kwargs: Additional keyword arguments. + name (str, optional): Name for the agent rearrange system. + Defaults to None (uses AgentRearrange default). + description (str, optional): Description of the system. + Defaults to None (uses AgentRearrange default). + agents (List[Agent]): The list of agents to be included in the system. + flow (str): The flow pattern defining agent execution order. + Uses '->' for sequential and ',' for concurrent execution. + task (str, optional): The task to be performed during rearrangement. + Defaults to None. + img (str, optional): Image input for agents that support it. + Defaults to None. + *args: Additional positional arguments passed to AgentRearrange constructor. + **kwargs: Additional keyword arguments passed to AgentRearrange constructor. Returns: The result of running the agent system with the specified task. + The format depends on the output_type configuration. Example: - agents = [agent1, agent2, agent3] - flow = "agent1 -> agent2, agent3" - task = "Perform a task" - rearrange(agents, flow, task) + >>> from swarms import Agent, rearrange + >>> + >>> # Create agents + >>> agent1 = Agent(name="researcher", ...) + >>> agent2 = Agent(name="writer", ...) + >>> agent3 = Agent(name="reviewer", ...) + >>> + >>> # Execute task with flow + >>> result = rearrange( + ... agents=[agent1, agent2, agent3], + ... flow="researcher -> writer, reviewer", + ... task="Research and write a report" + ... ) """ agent_system = AgentRearrange( name=name, 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( diff --git a/swarms/structs/multi_agent_router.py b/swarms/structs/multi_agent_router.py index ca719603..f724c53b 100644 --- a/swarms/structs/multi_agent_router.py +++ b/swarms/structs/multi_agent_router.py @@ -1,31 +1,92 @@ -import os -from typing import List, Optional +import concurrent.futures +import traceback +from concurrent.futures import ThreadPoolExecutor +from typing import Callable, List, Optional +import orjson from loguru import logger from pydantic import BaseModel, Field -from swarms.utils.function_caller_model import OpenAIFunctionCaller + from swarms.structs.conversation import Conversation -from swarms.utils.output_types import OutputType -from swarms.utils.any_to_str import any_to_str +from swarms.tools.base_tool import BaseTool +from swarms.utils.formatter import formatter +from swarms.utils.generate_keys import generate_api_key from swarms.utils.history_output_formatter import ( history_output_formatter, ) -from swarms.utils.formatter import formatter -from swarms.structs.omni_agent_types import AgentListType +from swarms.utils.litellm_wrapper import LiteLLM +from swarms.utils.output_types import OutputType -class AgentResponse(BaseModel): - """Response from the boss agent indicating which agent should handle the task""" +class HandOffsResponse(BaseModel): + """ + Response from the boss agent indicating which agent should handle the task. + + This model encapsulates the reasoning behind the agent selection, the name of the selected agent, and an optional modified version of the task. It is used to communicate the boss agent's decision and rationale to the rest of the system. + """ - selected_agent: str = Field( - description="Name of the agent selected to handle the task" - ) reasoning: str = Field( - description="Explanation for why this agent was selected" + description="A detailed explanation for why this agent was selected. This should include the logic or criteria used by the boss agent to make the selection, providing transparency and traceability for the routing decision." ) - modified_task: Optional[str] = Field( - None, description="Optional modified version of the task" + agent_name: str = Field( + description="The name of the agent selected to handle the task. This should match the identifier of one of the available agents in the system, ensuring the task is routed correctly." ) + task: Optional[str] = Field( + None, + description="An optional, modified version of the original task. If the boss agent determines that the task should be rephrased or clarified before execution, the new version is provided here. If no modification is needed, this field may be left as None.", + ) + + +class MultipleHandOffsResponse(BaseModel): + """ + Response from the boss agent indicating which agents should handle the task. + """ + + handoffs: List[HandOffsResponse] = Field( + description="A list of handoffs, each containing the reasoning, agent name, and task for each agent." + ) + + +def get_agent_response_schema(model_name: str = None): + return BaseTool().base_model_to_dict(MultipleHandOffsResponse) + + +def agent_boss_router_prompt(agent_descriptions: any): + return f""" + You are an intelligent boss agent responsible for routing tasks to the most appropriate specialized agents. + + Available agents: + {agent_descriptions} + + Your primary responsibilities: + 1. **Understand the user's intent and task requirements** - Carefully analyze what the user is asking for + 2. **Determine task complexity** - Identify if this is a single task or multiple related tasks + 3. **Match capabilities to requirements** - Select the most suitable agent(s) based on their descriptions and expertise + 4. **Provide clear reasoning** - Explain your selection logic transparently + 5. **Optimize task assignment** - Modify tasks if needed to better suit the selected agent's capabilities + + **Routing Logic:** + - **Single Task**: If the user presents one clear task, select the single best agent for that task + - **Multiple Tasks**: If the user presents multiple distinct tasks or a complex task that requires different expertise areas, select multiple agents and break down the work accordingly + - **Collaborative Tasks**: If a task benefits from multiple perspectives or requires different skill sets, assign it to multiple agents + + **Response Format:** + You must respond with JSON containing a "handoffs" array with one or more handoff objects. Each handoff object must contain: + - reasoning: Detailed explanation of why this agent was selected and how they fit the task requirements + - agent_name: Name of the chosen agent (must exactly match one of the available agents) + - task: A modified/optimized version of the task if needed, or the original task if no modification is required + + **Important Guidelines:** + - Always analyze the user's intent first before making routing decisions + - Consider task dependencies and whether agents need to work sequentially or in parallel + - If multiple agents are selected, ensure their tasks are complementary and don't conflict + - Provide specific, actionable reasoning for each agent selection + - Ensure all agent names exactly match the available agents list + - If a single agent can handle the entire request efficiently, use only one agent + - If the request requires different expertise areas, use multiple agents with clearly defined, non-overlapping tasks + + Remember: Your goal is to maximize task completion quality by matching the right agent(s) to the right work based on their capabilities and the user's actual needs. + """ class MultiAgentRouter: @@ -38,23 +99,32 @@ class MultiAgentRouter: name (str): The name of the router. description (str): A description of the router's purpose. agents (dict): A dictionary of agents, where the key is the agent's name and the value is the agent object. - api_key (str): The API key for OpenAI. - output_type (str): The type of output expected from the agents. Can be either "json" or "string". - execute_task (bool): A flag indicating whether the task should be executed by the selected agent. - boss_system_prompt (str): A system prompt for the boss agent that includes information about all available agents. - function_caller (OpenAIFunctionCaller): An instance of OpenAIFunctionCaller for calling the boss agent. + model (str): The model to use for the boss agent. + temperature (float): The temperature for the boss agent's model. + shared_memory_system (callable): A shared memory system for agents to query. + output_type (OutputType): The type of output expected from the agents. + print_on (bool): Whether to print the boss agent's decision. + system_prompt (str): Custom system prompt for the router. + skip_null_tasks (bool): Whether to skip executing agents when their assigned task is null or None. + conversation (Conversation): The conversation history. + function_caller (LiteLLM): An instance of LiteLLM for calling the boss agent. """ def __init__( self, + id: str = generate_api_key(prefix="multi-agent-router"), name: str = "swarm-router", description: str = "Routes tasks to specialized agents based on their capabilities", - agents: AgentListType = None, + agents: List[Callable] = None, model: str = "gpt-4o-mini", temperature: float = 0.1, shared_memory_system: callable = None, output_type: OutputType = "dict", - if_print: bool = True, + print_on: bool = True, + system_prompt: str = None, + skip_null_tasks: bool = True, + *args, + **kwargs, ): """ Initializes the MultiAgentRouter with a list of agents and configuration options. @@ -63,10 +133,13 @@ class MultiAgentRouter: name (str, optional): The name of the router. Defaults to "swarm-router". description (str, optional): A description of the router's purpose. Defaults to "Routes tasks to specialized agents based on their capabilities". agents (List[Agent], optional): A list of agents to be managed by the router. Defaults to an empty list. - model (str, optional): The model to use for the boss agent. Defaults to "gpt-4-0125-preview". + model (str, optional): The model to use for the boss agent. Defaults to "gpt-4o-mini". temperature (float, optional): The temperature for the boss agent's model. Defaults to 0.1. - output_type (Literal["json", "string"], optional): The type of output expected from the agents. Defaults to "json". - execute_task (bool, optional): A flag indicating whether the task should be executed by the selected agent. Defaults to True. + shared_memory_system (callable, optional): A shared memory system for agents to query. Defaults to None. + output_type (OutputType, optional): The type of output expected from the agents. Defaults to "dict". + print_on (bool, optional): Whether to print the boss agent's decision. Defaults to True. + system_prompt (str, optional): Custom system prompt for the router. Defaults to None. + skip_null_tasks (bool, optional): Whether to skip executing agents when their assigned task is null or None. Defaults to True. """ self.name = name self.description = description @@ -74,23 +147,28 @@ class MultiAgentRouter: self.output_type = output_type self.model = model self.temperature = temperature - self.if_print = if_print - self.agents = {agent.name: agent for agent in agents} + self.print_on = print_on + self.system_prompt = system_prompt + self.skip_null_tasks = skip_null_tasks + self.agents = {agent.agent_name: agent for agent in agents} self.conversation = Conversation() - self.api_key = os.getenv("OPENAI_API_KEY") - - if not self.api_key: - raise ValueError("OpenAI API key must be provided") + router_system_prompt = "" - self.boss_system_prompt = self._create_boss_system_prompt() - - # Initialize the function caller - self.function_caller = OpenAIFunctionCaller( - system_prompt=self.boss_system_prompt, - api_key=self.api_key, - temperature=temperature, - base_model=AgentResponse, + router_system_prompt += ( + self.system_prompt if self.system_prompt else "" + ) + router_system_prompt += self._create_boss_system_prompt() + + self.function_caller = LiteLLM( + model_name=self.model, + system_prompt=router_system_prompt, + temperature=self.temperature, + tool_choice="auto", + parallel_tool_calls=True, + response_format=MultipleHandOffsResponse, + *args, + **kwargs, ) def __repr__(self): @@ -114,24 +192,110 @@ class MultiAgentRouter: ] ) - return f"""You are a boss agent responsible for routing tasks to the most appropriate specialized agent. - Available agents: - {agent_descriptions} + return agent_boss_router_prompt(agent_descriptions) + + def handle_single_handoff( + self, boss_response_str: dict, task: str + ) -> dict: + """ + Handles a single handoff to one agent. + + If skip_null_tasks is True and the assigned task is null or None, + the agent execution will be skipped. + """ - Your job is to: - 1. Analyze the incoming task - 2. Select the most appropriate agent based on their descriptions - 3. Provide clear reasoning for your selection - 4. Optionally modify the task to better suit the selected agent's capabilities + # Validate that the selected agent exists + if ( + boss_response_str["handoffs"][0]["agent_name"] + not in self.agents + ): + raise ValueError( + f"Boss selected unknown agent: {boss_response_str.agent_name}" + ) + + # Get the selected agent + selected_agent = self.agents[ + boss_response_str["handoffs"][0]["agent_name"] + ] + + # Use the modified task if provided, otherwise use original task + final_task = boss_response_str["handoffs"][0]["task"] or task + + # Skip execution if task is null/None and skip_null_tasks is True + if self.skip_null_tasks and ( + final_task is None or final_task == "" + ): + if self.print_on: + logger.info( + f"Skipping execution for agent {selected_agent.agent_name} - task is null/None" + ) - You must respond with JSON that contains: - - selected_agent: Name of the chosen agent (must be one of the available agents) - - reasoning: Brief explanation of why this agent was selected - - modified_task: (Optional) A modified version of the task if needed + # Use the agent's run method directly + agent_response = selected_agent.run(final_task) + + self.conversation.add( + role=selected_agent.agent_name, content=agent_response + ) - Always select exactly one agent that best matches the task requirements. + # return agent_response + + def handle_multiple_handoffs( + self, boss_response_str: dict, task: str + ) -> dict: + """ + Handles multiple handoffs to multiple agents. + + If skip_null_tasks is True and any assigned task is null or None, + those agents will be skipped and only agents with valid tasks will be executed. """ + # Validate that the selected agents exist + for handoff in boss_response_str["handoffs"]: + if handoff["agent_name"] not in self.agents: + raise ValueError( + f"Boss selected unknown agent: {handoff.agent_name}" + ) + + # Get the selected agents and their tasks + selected_agents = [] + final_tasks = [] + skipped_agents = [] + + for handoff in boss_response_str["handoffs"]: + agent = self.agents[handoff["agent_name"]] + final_task = handoff["task"] or task + + # Skip execution if task is null/None and skip_null_tasks is True + if self.skip_null_tasks and ( + final_task is None or final_task == "" + ): + if self.print_on: + logger.info( + f"Skipping execution for agent {agent.agent_name} - task is null/None" + ) + skipped_agents.append(agent.agent_name) + continue + + selected_agents.append(agent) + final_tasks.append(final_task) + + # Execute agents only if there are valid tasks + if selected_agents: + # Use the agents' run method directly + agent_responses = [ + agent.run(final_task) + for agent, final_task in zip( + selected_agents, final_tasks + ) + ] + + self.conversation.add( + role=selected_agents[0].agent_name, + content=agent_responses[0], + ) + + # return agent_responses + def route_task(self, task: str) -> dict: """ Routes a task to the appropriate agent and returns their response. @@ -146,46 +310,32 @@ class MultiAgentRouter: self.conversation.add(role="user", content=task) # Get boss decision using function calling - boss_response = self.function_caller.run(task) - boss_response_str = any_to_str(boss_response) + boss_response_str = self.function_caller.run(task) - if self.if_print: - formatter.print_panel( - boss_response_str, - title="Multi-Agent Router Decision", - ) - else: - pass + boss_response_str = orjson.loads(boss_response_str) - self.conversation.add( - role="Agent Router", content=boss_response_str - ) - - # Validate that the selected agent exists - if boss_response.selected_agent not in self.agents: - raise ValueError( - f"Boss selected unknown agent: {boss_response.selected_agent}" + if self.print_on: + formatter.print_panel( + # orjson.dumps(boss_response_str, indent=4), + orjson.dumps( + boss_response_str, option=orjson.OPT_INDENT_2 + ).decode("utf-8"), + title=self.name, ) - # Get the selected agent - selected_agent = self.agents[boss_response.selected_agent] - - # Use the modified task if provided, otherwise use original task - final_task = boss_response.modified_task or task - - # Use the agent's run method directly - agent_response = selected_agent.run(final_task) - - self.conversation.add( - role=selected_agent.name, content=agent_response - ) + if len(boss_response_str["handoffs"]) > 1: + self.handle_multiple_handoffs(boss_response_str, task) + else: + self.handle_single_handoff(boss_response_str, task) return history_output_formatter( conversation=self.conversation, type=self.output_type ) except Exception as e: - logger.error(f"Error routing task: {str(e)}") + logger.error( + f"Error routing task: {str(e)} Traceback: {traceback.format_exc()}" + ) raise def run(self, task: str): @@ -209,9 +359,6 @@ class MultiAgentRouter: def concurrent_batch_run(self, tasks: List[str] = []): """Concurrently route tasks to the appropriate agents""" - import concurrent.futures - from concurrent.futures import ThreadPoolExecutor - results = [] with ThreadPoolExecutor() as executor: futures = [ diff --git a/swarms/structs/spreadsheet_swarm.py b/swarms/structs/spreadsheet_swarm.py index 90bed7eb..44970188 100644 --- a/swarms/structs/spreadsheet_swarm.py +++ b/swarms/structs/spreadsheet_swarm.py @@ -1,16 +1,14 @@ -import asyncio import csv import datetime import os import uuid -from typing import Dict, List, Union - -import aiofiles -from pydantic import BaseModel, Field +from typing import List from swarms.structs.agent import Agent -from swarms.structs.base_swarm import BaseSwarm -from swarms.telemetry.main import log_agent_data +from swarms.structs.multi_agent_exec import ( + run_agents_with_different_tasks, +) +from swarms.structs.omni_agent_types import AgentType from swarms.utils.file_processing import create_file_in_folder from swarms.utils.loguru_logger import initialize_logger @@ -25,105 +23,68 @@ formatted_time = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S") # --------------- NEW CHANGE END --------------- -class AgentConfig(BaseModel): - """Configuration for an agent loaded from CSV""" - - agent_name: str - description: str - system_prompt: str - task: str - - -class AgentOutput(BaseModel): - agent_name: str - task: str - result: str - timestamp: str - - -class SwarmRunMetadata(BaseModel): - run_id: str = Field( - default_factory=lambda: f"spreadsheet_swarm_run_{uuid_hex}" - ) - name: str - description: str - agents: List[str] - start_time: str = Field( - default_factory=lambda: time, - description="The start time of the swarm run.", - ) - end_time: str - tasks_completed: int - outputs: List[AgentOutput] - number_of_agents: int = Field( - ..., - description="The number of agents participating in the swarm.", - ) - - -class SpreadSheetSwarm(BaseSwarm): +class SpreadSheetSwarm: """ A swarm that processes tasks concurrently using multiple agents. Args: name (str, optional): The name of the swarm. Defaults to "Spreadsheet-Swarm". description (str, optional): The description of the swarm. Defaults to "A swarm that processes tasks concurrently using multiple agents.". - agents (Union[Agent, List[Agent]], optional): The agents participating in the swarm. Defaults to an empty list. - autosave_on (bool, optional): Whether to enable autosave of swarm metadata. Defaults to True. + agents (Union[Agent, List[Agent], None], optional): The agents participating in the swarm. If None, agents will be loaded from load_path. Defaults to None. + autosave (bool, optional): Whether to enable autosave of swarm metadata. Defaults to True. save_file_path (str, optional): The file path to save the swarm metadata as a CSV file. Defaults to "spreedsheet_swarm.csv". max_loops (int, optional): The number of times to repeat the swarm tasks. Defaults to 1. workspace_dir (str, optional): The directory path of the workspace. Defaults to the value of the "WORKSPACE_DIR" environment variable. + load_path (str, optional): Path to CSV file containing agent configurations. Required if agents is None. *args: Additional positional arguments. **kwargs: Additional keyword arguments. + + Note: + Either 'agents' or 'load_path' must be provided. If both are provided, 'agents' will be used. """ def __init__( self, name: str = "Spreadsheet-Swarm", - description: str = "A swarm that that processes tasks concurrently using multiple agents and saves the metadata to a CSV file.", - agents: Union[Agent, List[Agent]] = [], - autosave_on: bool = True, + description: str = "A swarm that processes tasks concurrently using multiple agents and saves the metadata to a CSV file.", + agents: List[AgentType] = None, + autosave: bool = True, save_file_path: str = None, max_loops: int = 1, workspace_dir: str = os.getenv("WORKSPACE_DIR"), load_path: str = None, + verbose: bool = False, *args, **kwargs, ): - super().__init__( - name=name, - description=description, - agents=agents if isinstance(agents, list) else [agents], - *args, - **kwargs, - ) self.name = name self.description = description + self.agents = agents self.save_file_path = save_file_path - self.autosave_on = autosave_on + self.autosave = autosave self.max_loops = max_loops self.workspace_dir = workspace_dir self.load_path = load_path - self.agent_configs: Dict[str, AgentConfig] = {} + self.verbose = verbose # --------------- NEW CHANGE START --------------- # The save_file_path now uses the formatted_time and uuid_hex - self.save_file_path = ( - f"spreadsheet_swarm_run_id_{uuid_hex}.csv" - ) + # Save CSV files in the workspace_dir instead of root directory + if self.workspace_dir: + os.makedirs(self.workspace_dir, exist_ok=True) + self.save_file_path = os.path.join( + self.workspace_dir, + f"spreadsheet_swarm_run_id_{uuid_hex}.csv", + ) + else: + self.save_file_path = ( + f"spreadsheet_swarm_run_id_{uuid_hex}.csv" + ) # --------------- NEW CHANGE END --------------- - self.metadata = SwarmRunMetadata( - run_id=f"spreadsheet_swarm_run_{time}", - name=name, - description=description, - agents=[agent.name for agent in agents], - start_time=time, - end_time="", - tasks_completed=0, - outputs=[], - number_of_agents=len(agents), - ) + self.outputs = [] + self.tasks_completed = 0 + self.agent_tasks = {} # Simple dict to store agent tasks self.reliability_check() @@ -132,21 +93,28 @@ class SpreadSheetSwarm(BaseSwarm): Check the reliability of the swarm. Raises: - ValueError: If no agents are provided or no save file path is provided. + ValueError: If neither agents nor load_path is provided, or if max_loops is not provided. """ - logger.info("Checking the reliability of the swarm...") + if self.verbose: + logger.info( + f"SpreadSheetSwarm Name: {self.name} reliability checks in progress..." + ) + + if not self.agents: + raise ValueError("No agents are provided.") - # if not self.agents: - # raise ValueError("No agents are provided.") - # if not self.save_file_path: - # raise ValueError("No save file path is provided.") if not self.max_loops: raise ValueError("No max loops are provided.") - logger.info("Swarm reliability check passed.") - logger.info("Swarm is ready to run.") + if self.verbose: + logger.info( + f"SpreadSheetSwarm Name: {self.name} reliability check passed." + ) + logger.info( + f"SpreadSheetSwarm Name: {self.name} is ready to run." + ) - async def _load_from_csv(self): + def _load_from_csv(self): """ Load agent configurations from a CSV file. Expected CSV format: agent_name,description,system_prompt,task @@ -160,23 +128,21 @@ class SpreadSheetSwarm(BaseSwarm): f"Loading agent configurations from {csv_path}" ) - async with aiofiles.open(csv_path, mode="r") as file: - content = await file.read() - csv_reader = csv.DictReader(content.splitlines()) + with open(csv_path, mode="r") as file: + csv_reader = csv.DictReader(file) for row in csv_reader: - config = AgentConfig( - agent_name=row["agent_name"], - description=row["description"], - system_prompt=row["system_prompt"], - task=row["task"], - ) + agent_name = row["agent_name"] + task = row["task"] + + # Store agent task mapping + self.agent_tasks[agent_name] = task # Create new agent with configuration new_agent = Agent( - agent_name=config.agent_name, - system_prompt=config.system_prompt, - description=config.description, + agent_name=agent_name, + system_prompt=row["system_prompt"], + description=row["description"], model_name=( row["model_name"] if "model_name" in row @@ -194,7 +160,6 @@ class SpreadSheetSwarm(BaseSwarm): if "user_name" in row else "user" ), - # output_type="str", stopping_token=( row["stopping_token"] if "stopping_token" in row @@ -204,60 +169,68 @@ class SpreadSheetSwarm(BaseSwarm): # Add agent to swarm self.agents.append(new_agent) - self.agent_configs[config.agent_name] = config - # Update metadata with new agents - self.metadata.agents = [ - agent.name for agent in self.agents - ] - self.metadata.number_of_agents = len(self.agents) + # Agents have been loaded successfully logger.info( - f"Loaded {len(self.agent_configs)} agent configurations" + f"Loaded {len(self.agents)} agent configurations" ) except Exception as e: logger.error(f"Error loading agent configurations: {e}") def load_from_csv(self): - asyncio.run(self._load_from_csv()) + self._load_from_csv() - async def run_from_config(self): + def run_from_config(self): """ Run all agents with their configured tasks concurrently """ logger.info("Running agents from configuration") - self.metadata.start_time = time - tasks = [] + # Load agents from CSV if no agents are provided but load_path is + if not self.agents and self.load_path: + self.load_from_csv() + + start_time = time + + # Prepare agent-task pairs for concurrent execution + agent_task_pairs = [] + for agent in self.agents: - config = self.agent_configs.get(agent.agent_name) - if config: + task = self.agent_tasks.get(agent.agent_name) + if task: for _ in range(self.max_loops): - tasks.append( - asyncio.to_thread( - self._run_agent_task, agent, config.task - ) - ) + agent_task_pairs.append((agent, task)) - # Run all tasks concurrently - results = await asyncio.gather(*tasks) + # Run all tasks concurrently using the multi_agent_exec function + results = run_agents_with_different_tasks(agent_task_pairs) # Process the results - for result in results: - self._track_output(*result) + for i, result in enumerate(results): + agent, task = agent_task_pairs[i] + self._track_output(agent.agent_name, task, result) - self.metadata.end_time = time + end_time = time - # Save metadata - logger.info("Saving metadata to CSV and JSON...") - await self._save_metadata() + # Save outputs + logger.info("Saving outputs to CSV...") + self._save_metadata() - if self.autosave_on: + if self.autosave: self.data_to_json_file() - log_agent_data(self.metadata.model_dump()) - return self.metadata.model_dump_json(indent=4) - - async def _run(self, task: str = None, *args, **kwargs): + # Return simple summary + return { + "run_id": f"spreadsheet_swarm_run_{uuid_hex}", + "name": self.name, + "description": self.description, + "start_time": start_time, + "end_time": end_time, + "tasks_completed": self.tasks_completed, + "number_of_agents": len(self.agents), + "outputs": self.outputs, + } + + def _run(self, task: str = None, *args, **kwargs): """ Run the swarm either with a specific task or using configured tasks. @@ -267,21 +240,34 @@ class SpreadSheetSwarm(BaseSwarm): **kwargs: Additional keyword arguments. Returns: - str: The JSON representation of the swarm metadata. + dict: Summary of the swarm execution. """ - if task is None and self.agent_configs: - return await self.run_from_config() + # Load agents from CSV if no agents are provided but load_path is + if not self.agents and self.load_path: + self.load_from_csv() + + if task is None and self.agent_tasks: + return self.run_from_config() else: - self.metadata.start_time = time - await self._run_tasks(task, *args, **kwargs) - self.metadata.end_time = time - await self._save_metadata() + start_time = time + self._run_tasks(task, *args, **kwargs) + end_time = time + self._save_metadata() - if self.autosave_on: + if self.autosave: self.data_to_json_file() - print(log_agent_data(self.metadata.model_dump())) - return self.metadata.model_dump_json(indent=4) + # Return simple summary + return { + "run_id": f"spreadsheet_swarm_run_{uuid_hex}", + "name": self.name, + "description": self.description, + "start_time": start_time, + "end_time": end_time, + "tasks_completed": self.tasks_completed, + "number_of_agents": len(self.agents), + "outputs": self.outputs, + } def run(self, task: str = None, *args, **kwargs): """ @@ -293,16 +279,16 @@ class SpreadSheetSwarm(BaseSwarm): **kwargs: Additional keyword arguments. Returns: - str: The JSON representation of the swarm metadata. + dict: Summary of the swarm execution. """ try: - return asyncio.run(self._run(task, *args, **kwargs)) + return self._run(task, *args, **kwargs) except Exception as e: logger.error(f"Error running swarm: {e}") raise e - async def _run_tasks(self, task: str, *args, **kwargs): + def _run_tasks(self, task: str, *args, **kwargs): """ Run the swarm tasks concurrently. @@ -311,49 +297,29 @@ class SpreadSheetSwarm(BaseSwarm): *args: Additional positional arguments. **kwargs: Additional keyword arguments. """ - tasks = [] + # Load agents from CSV if no agents are provided but load_path is + if not self.agents and self.load_path: + self.load_from_csv() + + # Prepare agents and tasks for concurrent execution + agents_to_run = [] + tasks_to_run = [] + for _ in range(self.max_loops): for agent in self.agents: - # Use asyncio.to_thread to run the blocking task in a thread pool - tasks.append( - asyncio.to_thread( - self._run_agent_task, - agent, - task, - *args, - **kwargs, - ) - ) + agents_to_run.append(agent) + tasks_to_run.append(task) - # Run all tasks concurrently - results = await asyncio.gather(*tasks) + # Run all tasks concurrently using the multi_agent_exec function + results = run_agents_with_different_tasks( + list(zip(agents_to_run, tasks_to_run)) + ) # Process the results - for result in results: - self._track_output(*result) - - def _run_agent_task(self, agent, task, *args, **kwargs): - """ - Run a single agent's task in a separate thread. - - Args: - agent: The agent to run the task for. - task (str): The task to be executed by the agent. - *args: Additional positional arguments. - **kwargs: Additional keyword arguments. - - Returns: - Tuple[str, str, str]: A tuple containing the agent name, task, and result. - """ - try: - result = agent.run(task=task, *args, **kwargs) - # Assuming agent.run() is a blocking call - return agent.agent_name, task, result - except Exception as e: - logger.error( - f"Error running task for {agent.agent_name}: {e}" - ) - return agent.agent_name, task, str(e) + for i, result in enumerate(results): + agent = agents_to_run[i] + task_str = tasks_to_run[i] + self._track_output(agent.agent_name, task_str, result) def _track_output(self, agent_name: str, task: str, result: str): """ @@ -364,24 +330,36 @@ class SpreadSheetSwarm(BaseSwarm): task (str): The task that was completed. result (str): The result of the completed task. """ - self.metadata.tasks_completed += 1 - self.metadata.outputs.append( - AgentOutput( - agent_name=agent_name, - task=task, - result=result, - timestamp=time, - ) + self.tasks_completed += 1 + self.outputs.append( + { + "agent_name": agent_name, + "task": task, + "result": result, + "timestamp": time, + } ) def export_to_json(self): """ - Export the swarm metadata to JSON. + Export the swarm outputs to JSON. Returns: - str: The JSON representation of the swarm metadata. + str: The JSON representation of the swarm outputs. """ - return self.metadata.model_dump_json(indent=4) + import json + + return json.dumps( + { + "run_id": f"spreadsheet_swarm_run_{uuid_hex}", + "name": self.name, + "description": self.description, + "tasks_completed": self.tasks_completed, + "number_of_agents": len(self.agents), + "outputs": self.outputs, + }, + indent=4, + ) def data_to_json_file(self): """ @@ -395,14 +373,14 @@ class SpreadSheetSwarm(BaseSwarm): content=out, ) - async def _save_metadata(self): + def _save_metadata(self): """ Save the swarm metadata to CSV and JSON. """ - if self.autosave_on: - await self._save_to_csv() + if self.autosave: + self._save_to_csv() - async def _save_to_csv(self): + def _save_to_csv(self): """ Save the swarm metadata to a CSV file. """ @@ -414,14 +392,12 @@ class SpreadSheetSwarm(BaseSwarm): # Check if file exists before opening it file_exists = os.path.exists(self.save_file_path) - async with aiofiles.open( - self.save_file_path, mode="a" - ) as file: + with open(self.save_file_path, mode="a", newline="") as file: writer = csv.writer(file) # Write header if file doesn't exist if not file_exists: - await writer.writerow( + writer.writerow( [ "Run ID", "Agent Name", @@ -431,13 +407,13 @@ class SpreadSheetSwarm(BaseSwarm): ] ) - for output in self.metadata.outputs: - await writer.writerow( + for output in self.outputs: + writer.writerow( [ str(run_id), - output.agent_name, - output.task, - output.result, - output.timestamp, + output["agent_name"], + output["task"], + output["result"], + output["timestamp"], ] ) diff --git a/swarms/utils/litellm_wrapper.py b/swarms/utils/litellm_wrapper.py index d053f565..162ae698 100644 --- a/swarms/utils/litellm_wrapper.py +++ b/swarms/utils/litellm_wrapper.py @@ -9,7 +9,6 @@ import litellm import requests from litellm import completion, supports_vision from loguru import logger -from pydantic import BaseModel class LiteLLMException(Exception): @@ -235,6 +234,7 @@ class LiteLLM: drop_params: bool = True, thinking_tokens: int = None, reasoning_enabled: bool = False, + response_format: any = None, *args, **kwargs, ): @@ -292,6 +292,7 @@ class LiteLLM: self.thinking_tokens = thinking_tokens self.reasoning_enabled = reasoning_enabled self.verbose = verbose + self.response_format = response_format self.modalities = [] self.messages = [] # Initialize messages list @@ -394,46 +395,73 @@ class LiteLLM: completion_params["runtime_args"] = runtime_args def output_for_tools(self, response: any): - if self.mcp_call is True: + """ + Process tool calls from the LLM response and return formatted output. + + Args: + response: The response object from the LLM API call + + Returns: + dict or list: Formatted tool call data, or default response if no tool calls + """ + try: + # Convert response to dict if it's a Pydantic model + if hasattr(response, "model_dump"): + response_dict = response.model_dump() + else: + response_dict = response + # Check if tool_calls exists and is not None if ( - response.choices - and response.choices[0].message - and response.choices[0].message.tool_calls - and len(response.choices[0].message.tool_calls) > 0 - ): - out = ( - response.choices[0].message.tool_calls[0].function + response_dict.get("choices") + and response_dict["choices"][0].get("message") + and response_dict["choices"][0]["message"].get( + "tool_calls" ) - output = { - "function": { - "name": out.name, - "arguments": out.arguments, + and len( + response_dict["choices"][0]["message"][ + "tool_calls" + ] + ) + > 0 + ): + tool_call = response_dict["choices"][0]["message"][ + "tool_calls" + ][0] + if "function" in tool_call: + return { + "function": { + "name": tool_call["function"].get( + "name", "" + ), + "arguments": tool_call["function"].get( + "arguments", "{}" + ), + } } - } - return output + else: + # Handle case where tool_call structure is different + return tool_call else: # Return a default response when no tool calls are present + logger.warning( + "No tool calls found in response, returning default response" + ) return { "function": { "name": "no_tool_call", "arguments": "{}", } } - else: - # Check if tool_calls exists and is not None - if ( - response.choices - and response.choices[0].message - and response.choices[0].message.tool_calls - ): - out = response.choices[0].message.tool_calls - if isinstance(out, BaseModel): - out = out.model_dump() - return out - else: - # Return empty list when no tool calls are present - return [] + except Exception as e: + logger.error(f"Error processing tool calls: {str(e)}") + # Return a safe default response + return { + "function": { + "name": "error_processing_tool_calls", + "arguments": f'{{"error": "{str(e)}"}}', + } + } def output_for_reasoning(self, response: any): """ @@ -886,6 +914,11 @@ class LiteLLM: if self.base_url is not None: completion_params["base_url"] = self.base_url + if self.response_format is not None: + completion_params["response_format"] = ( + self.response_format + ) + # Add modalities if needed if self.modalities and len(self.modalities) >= 2: completion_params["modalities"] = self.modalities @@ -914,6 +947,14 @@ class LiteLLM: # Make the completion call response = completion(**completion_params) + # print(response) + + # Validate response + if not response: + logger.error( + "Received empty response from completion call" + ) + return None # Handle streaming response if self.stream: @@ -928,25 +969,19 @@ class LiteLLM: # Handle tool-based response elif self.tools_list_dictionary is not None: - return self.output_for_tools(response) + result = self.output_for_tools(response) + return result elif self.return_all is True: return response.model_dump() elif "gemini" in self.model_name.lower(): return gemini_output_img_handler(response) else: - # For non-Gemini models, return the content directly return response.choices[0].message.content except LiteLLMException as error: logger.error( f"Error in LiteLLM run: {str(error)} Traceback: {traceback.format_exc()}" ) - if "rate_limit" in str(error).lower(): - logger.warning( - "Rate limit hit, retrying with exponential backoff..." - ) - return self.run(task, audio, img, *args, **kwargs) - raise error def __call__(self, task: str, *args, **kwargs): """ diff --git a/tests/test_comprehensive_test.py b/tests/test_comprehensive_test.py index 01a74954..2ef00e1e 100644 --- a/tests/test_comprehensive_test.py +++ b/tests/test_comprehensive_test.py @@ -445,7 +445,7 @@ def test_spreadsheet_swarm(): description="A swarm for processing data", agents=agents, max_loops=1, - autosave_on=False, + autosave=False, ) response = swarm.run(