SpreadSheetSwarm manages thousands of agents concurrently for efficient task processing. It supports one-to-many task distribution, scalability, and autosaving results. Initialized with a name, description, agents, and settings, the run method executes tasks and returns a dictionary of agent outputs.
Get onboarded now with the creator and lead maintainer of Swarms, Kye Gomez, who will show you how to get started with the installation, usage examples, and starting to build your custom use case! [CLICK HERE](https://cal.com/swarms/swarms-onboarding-session)
---
## Documentation
Documentation is located here at: [docs.swarms.world](https://docs.swarms.world)
-----
## Folder Structure
The swarms package has been meticulously crafted for extreme usability and understanding,the swarms package is split up into various modules such as `swarms.agents` that holds pre-built agents, `swarms.structs` that holds a vast array of structures like `Agent` and multi agent structures. The package is split into various modules, with the most important being `structs`, `tools`, and `agents`.
```sh
├── __init__.py
├── agents/
├── artifacts/
├── client/
├── cli/
├── prompts/
├── schemas/
├── structs/
├── telemetry/
├── tools/
└── utils/
```
----
## 🫶 Contributions:
The easiest way to contribute is to pick any issue with the `good first issue` tag 💪. Read the Contributing guidelines [here](/CONTRIBUTING.md). Bug Report? [File here](https://github.com/swarms/gateway/issues) | Feature Request? [File here](https://github.com/swarms/gateway/issues)
@ -2067,17 +2051,20 @@ Swarms is an open-source project, and contributions are VERY welcome. If you wan
----
## Community
### Connect With Us
| Platform | Link | Description |
|----------|------|-------------|
| 📚 Documentation | [docs.swarms.world](https://docs.swarms.world) | Official documentation and guides |
| 📝 Blog | [Medium](https://medium.com/@kyeg) | Latest updates and technical articles |
| 💬 Discord | [Join Discord](https://discord.gg/jM3Z6M9uMq) | Live chat and community support |
- Processing time may vary based on task complexity
- Model response quality depends on input clarity
- Resource usage scales with batch size
## Example Script
For a runnable demonstration, see the [reasoning_duo_batched.py](https://github.com/kyegomez/swarms/blob/master/examples/models/reasoning_duo_batched.py) example.
@ -34,6 +34,7 @@ Swarm architectures leverage these communication patterns to ensure that agents
| Spreadsheet Swarm | Manages tasks at scale, tracking agent outputs in a structured format like CSV files. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/) | Large-scale marketing analytics, financial audits |
| Forest Swarm | A swarm structure that organizes agents in a tree-like hierarchy for complex decision-making processes. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/) | Multi-stage workflows, hierarchical reinforcement learning |
| Swarm Router | Routes and chooses the swarm architecture based on the task requirements and available agents. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/) | Dynamic task routing, adaptive swarm architecture selection, optimized agent allocation |
| MultiAgentRouter | Boss agent selects the best agent for each task. | [Minimal Example](https://github.com/kyegomez/swarms/blob/master/examples/multi_agent/mar/multi_agent_router_minimal.py) | Task-specific agent routing |
The `aggregate` function allows you to run multiple agents concurrently on the same task and then synthesize their responses using an intelligent aggregator agent. This is useful for getting diverse perspectives on a problem and then combining them into a comprehensive analysis.
## Installation
You can get started by first installing swarms with the following command, or [click here for more detailed installation instructions](https://docs.swarms.world/en/latest/swarms/install/install/):
```bash
pip3 install -U swarms
```
## Environment Variables
```txt
OPENAI_API_KEY=""
ANTHROPIC_API_KEY=""
```
## Function Parameters
### `workers: List[Callable]` (Required)
A list of Agent instances that will work on the task concurrently. Each agent should be a callable object (typically an Agent instance).
### `task: str` (Required)
The task or question that all agents will work on simultaneously. This should be a clear, specific prompt that allows for diverse perspectives.
The model to use for the aggregator agent that synthesizes all the individual agent responses. This should be a model capable of understanding and summarizing complex multi-agent conversations.
## How It Works
1. **Concurrent Execution**: All agents in the `workers` list run the same task simultaneously
2. **Response Collection**: Individual agent responses are collected into a conversation
3. **Intelligent Aggregation**: A specialized aggregator agent analyzes all responses and creates a comprehensive synthesis
4. **Formatted Output**: The final result is returned in the specified format
## Code Example
```python
from swarms.structs.agent import Agent
from swarms.structs.ma_blocks import aggregate
# Create specialized agents for different perspectives
agents = [
Agent(
agent_name="Sector-Financial-Analyst",
agent_description="Senior financial analyst at BlackRock.",
system_prompt="You are a financial analyst tasked with optimizing asset allocations for a $50B portfolio. Provide clear, quantitative recommendations for each sector.",
system_prompt="You are a risk analyst responsible for advising on risk allocation within a $50B portfolio. Provide detailed insights on risk exposures for each sector.",
max_loops=1,
model_name="gpt-4o-mini",
max_tokens=3000,
),
Agent(
agent_name="Tech-Sector-Analyst",
agent_description="Technology sector analyst.",
system_prompt="You are a tech sector analyst focused on capital and risk allocations. Provide data-backed insights for the tech sector.",
This is an example of the InteractiveGroupChat module in swarms. [Click here for full documentation](https://docs.swarms.world/en/latest/swarms/structs/interactive_groupchat/)
## Installation
You can get started by first installing swarms with the following command, or [click here for more detailed installation instructions](https://docs.swarms.world/en/latest/swarms/install/install/):
```bash
pip3 install -U swarms
```
## Environment Variables
```txt
OPENAI_API_KEY=""
ANTHROPIC_API_KEY=""
GROQ_API_KEY=""
```
# Code
## Interactive Session in Terminal
```python
from swarms import Agent
from swarms.structs.interactive_groupchat import InteractiveGroupChat
if __name__ == "__main__":
# Initialize agents
financial_advisor = Agent(
agent_name="FinancialAdvisor",
system_prompt="You are a financial advisor specializing in investment strategies and portfolio management.",
random_models_on=True,
output_type="final",
)
tax_expert = Agent(
agent_name="TaxExpert",
system_prompt="You are a tax expert who provides guidance on tax optimization and compliance.",
random_models_on=True,
output_type="final",
)
investment_analyst = Agent(
agent_name="InvestmentAnalyst",
system_prompt="You are an investment analyst focusing on market trends and investment opportunities.",
random_models_on=True,
output_type="final",
)
# Create a list of agents including both Agent instances and callables
agents = [
financial_advisor,
tax_expert,
investment_analyst,
]
# Initialize another chat instance in interactive mode
interactive_chat = InteractiveGroupChat(
name="Interactive Financial Advisory Team",
description="An interactive team of financial experts providing comprehensive financial advice",
agents=agents,
max_loops=1,
output_type="all",
interactive=True,
)
try:
# Start the interactive session
print("\nStarting interactive session...")
# interactive_chat.run("What is the best methodology to accumulate gold and silver commodities, and what is the best long-term strategy to accumulate them?")
interactive_chat.start_interactive_session()
except Exception as e:
print(f"An error occurred in interactive mode: {e}")
```
## Run Method // Manual Method
```python
from swarms import Agent
from swarms.structs.interactive_groupchat import InteractiveGroupChat
if __name__ == "__main__":
# Initialize agents
financial_advisor = Agent(
agent_name="FinancialAdvisor",
system_prompt="You are a financial advisor specializing in investment strategies and portfolio management.",
random_models_on=True,
output_type="final",
)
tax_expert = Agent(
agent_name="TaxExpert",
system_prompt="You are a tax expert who provides guidance on tax optimization and compliance.",
random_models_on=True,
output_type="final",
)
investment_analyst = Agent(
agent_name="InvestmentAnalyst",
system_prompt="You are an investment analyst focusing on market trends and investment opportunities.",
random_models_on=True,
output_type="final",
)
# Create a list of agents including both Agent instances and callables
agents = [
financial_advisor,
tax_expert,
investment_analyst,
]
# Initialize another chat instance in interactive mode
interactive_chat = InteractiveGroupChat(
name="Interactive Financial Advisory Team",
description="An interactive team of financial experts providing comprehensive financial advice",
agents=agents,
max_loops=1,
output_type="all",
interactive=False,
)
try:
# Start the interactive session
print("\nStarting interactive session...")
# interactive_chat.run("What is the best methodology to accumulate gold and silver commodities, and what is the best long-term strategy to accumulate them?")
interactive_chat.run('@TaxExpert how can I understand tax tactics for crypto payroll in solana?')
except Exception as e:
print(f"An error occurred in interactive mode: {e}")
A tool is a Python function designed to perform specific tasks, with clear type annotations and comprehensive docstrings. Below are examples of tools to help you get started.
A tool is a Python function designed to perform specific tasks with clear type annotations and comprehensive docstrings. Below are examples of financial tools to help you get started.
# Rules
## Rules
To create a tool in the Swarms environment, follow these rules:
@ -25,509 +25,480 @@ To create a tool in the Swarms environment, follow these rules:
- The function's input must be a string.
- The function's output must be a string.
## Example Financial Tools
### Example Tools
### Examples and Anti-Examples
#### Example 1: Fetch Financial News
**Correct Implementation**
### Example 1: Fetch Stock Price from Yahoo Finance
return f"The amount after {time} years is {amount:.2f}"
except requests.exceptions.RequestException as e:
print(f"Request Error: {e}")
raise
except ValueError as e:
print(f"Value Error: {e}")
raise
except Exception as e:
print(f"Error fetching crypto data: {e}")
raise
```
**Incorrect Implementation**
### Example 3: Calculate Portfolio Performance
```python
def calculate_compound_interest(principal, rate, time, n):
# Calculates compound interest.
principal = float(principal)
rate = float(rate)
time = float(time)
n = int(n)
if principal <0orrate<0ortime<0orn<0:
raise ValueError("Inputs must be non-negative.")
amount = principal * (1 + rate / n) ** (n * time)
return f"The amount after {time} years is {amount:.2f}"
```
**Issues with Incorrect Implementation:**
- No type annotations for arguments and return value.
- Missing comprehensive docstring.
- Input types are not enforced as strings.
By following these rules and using the examples provided, you can create robust and well-documented tools in the Swarms environment. Ensure that all functions include proper type annotations, comprehensive docstrings, and that both input and output types are strings.
By following the examples provided, you can create your own tools to perform various tasks in the Swarms environment. Ensure each function includes type annotations, comprehensive docstrings, and appropriate error handling to make your tools robust and easy to use.
## Integrating Tools into an Agent
## Integrate tools into Agent
To integrate tools into an agent, you'd simply just pass in a callable function with types and documentation into the agent class.
To integrate tools into an agent, simply pass callable functions with proper type annotations and documentation into the agent class.
```python
from swarms import Agent
from swarms import Agent, OpenAIChat # ChromaDB
import subprocess
# Model
llm = OpenAIChat(
temperature=0.1,
)
# Tools
def terminal(
code: str,
):
"""
Run code in the terminal.
Args:
code (str): The code to run in the terminal.
Returns:
str: The output of the code.
"""
out = subprocess.run(
code, shell=True, capture_output=True, text=True
).stdout
return str(out)
def browser(query: str):
"""
Search the query in the browser with the `browser` tool.
agent.run("Create a new file for a plan to take over the world.")
response = agent("Analyze the current price of Apple stock and Bitcoin, then calculate the performance of a $10,000 investment in each over the past 2 years.")
print(response)
```
## Example 2
## Complete Financial Analysis Example
```python
import os
import yfinance as yf
import requests
from swarms import Agent
from swarm_models import OpenAIChat
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
def get_stock_price(symbol: str) -> str:
"""
Fetches the current stock price from Yahoo Finance.
description="The unique name assigned to the agent, which identifies its role and functionality within the swarm.",
)
description:Optional[str]=Field(
default=None,
description="A detailed explanation of the agent's purpose, capabilities, and any specific tasks it is designed to perform.",
)
system_prompt:Optional[str]=Field(
default=None,
description="The initial instruction or context provided to the agent, guiding its behavior and responses during execution.",
)
model_name:Optional[str]=Field(
default="gpt-4o-mini",
description="The name of the AI model that the agent will utilize for processing tasks and generating outputs. For example: gpt-4o, gpt-4o-mini, openai/o3-mini",
)
auto_generate_prompt:Optional[bool]=Field(
default=False,
description="A flag indicating whether the agent should automatically create prompts based on the task requirements.",
)
max_tokens:Optional[int]=Field(
default=8192,
description="The maximum number of tokens that the agent is allowed to generate in its responses, limiting output length.",
)
temperature:Optional[float]=Field(
default=0.5,
description="A parameter that controls the randomness of the agent's output; lower values result in more deterministic responses.",
)
role:Optional[str]=Field(
default="worker",
description="The designated role of the agent within the swarm, which influences its behavior and interaction with other agents.",
)
max_loops:Optional[int]=Field(
default=1,
description="The maximum number of times the agent is allowed to repeat its task, enabling iterative processing if necessary.",