From 42d93f91c5c842ddaa56940f921f50792ff04691 Mon Sep 17 00:00:00 2001 From: Kye Gomez Date: Sun, 21 Sep 2025 22:27:52 -0700 Subject: [PATCH] [IMPROVEMENT][Improve SpreadSheetSwarm, make it truly concurrent, improve csv logging, improve docs, new examples] --- docs/llm.txt | 22 +- docs/quickstart.md | 2 +- docs/swarms/structs/index.md | 2 +- docs/swarms/structs/spreadsheet_swarm.md | 491 ++++++++++-------- spreadsheet_example.py | 46 ++ .../agent_config_example.csv | 5 + ...un_id_02575aa12829486c91967c24b927100b.csv | 167 ++++++ ...un_id_69f4c23f5a97477ab2b8114521c33fd4.csv | 241 +++++++++ ...un_id_b93a2946b074493f8fa34a47377b2625.csv | 231 ++++++++ .../spreadsheet_swarm_usage.py | 161 ++++++ ...c23f5a97477ab2b8114521c33fd4-metadata.json | 27 + ...2946b074493f8fa34a47377b2625-metadata.json | 27 + swarms/structs/spreadsheet_swarm.py | 378 +++++++------- tests/test_comprehensive_test.py | 2 +- 14 files changed, 1377 insertions(+), 425 deletions(-) create mode 100644 spreadsheet_example.py create mode 100644 spreadsheet_new_examples/agent_config_example.csv create mode 100644 spreadsheet_new_examples/spreadsheet_swarm_run_id_02575aa12829486c91967c24b927100b.csv create mode 100644 spreadsheet_new_examples/spreadsheet_swarm_run_id_69f4c23f5a97477ab2b8114521c33fd4.csv create mode 100644 spreadsheet_new_examples/spreadsheet_swarm_run_id_b93a2946b074493f8fa34a47377b2625.csv create mode 100644 spreadsheet_new_examples/spreadsheet_swarm_usage.py create mode 100644 spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-69f4c23f5a97477ab2b8114521c33fd4-metadata.json create mode 100644 spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-b93a2946b074493f8fa34a47377b2625-metadata.json 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/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/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/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/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/spreadsheet_new_examples/agent_config_example.csv b/spreadsheet_new_examples/agent_config_example.csv new file mode 100644 index 00000000..1b02f7cf --- /dev/null +++ b/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/spreadsheet_new_examples/spreadsheet_swarm_run_id_02575aa12829486c91967c24b927100b.csv b/spreadsheet_new_examples/spreadsheet_swarm_run_id_02575aa12829486c91967c24b927100b.csv new file mode 100644 index 00000000..8ddd8136 --- /dev/null +++ b/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/spreadsheet_new_examples/spreadsheet_swarm_run_id_69f4c23f5a97477ab2b8114521c33fd4.csv b/spreadsheet_new_examples/spreadsheet_swarm_run_id_69f4c23f5a97477ab2b8114521c33fd4.csv new file mode 100644 index 00000000..cdf8a3ba --- /dev/null +++ b/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/spreadsheet_new_examples/spreadsheet_swarm_run_id_b93a2946b074493f8fa34a47377b2625.csv b/spreadsheet_new_examples/spreadsheet_swarm_run_id_b93a2946b074493f8fa34a47377b2625.csv new file mode 100644 index 00000000..6b4fcd78 --- /dev/null +++ b/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/spreadsheet_new_examples/spreadsheet_swarm_usage.py b/spreadsheet_new_examples/spreadsheet_swarm_usage.py new file mode 100644 index 00000000..fb8f9124 --- /dev/null +++ b/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/spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-69f4c23f5a97477ab2b8114521c33fd4-metadata.json b/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/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/spreadsheet_new_examples/swarm_outputs/Spreedsheet-Swarm-Financial-Analysis-Swarm/Financial-Analysis-Swarm/spreedsheet-swarm-b93a2946b074493f8fa34a47377b2625-metadata.json b/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/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/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/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(