<div align="center">
<a href="https://swarms.world">
<img src="https://github.com/kyegomez/swarms/blob/master/images/swarmslogobanner.png" style="margin: 15px; max-width: 300px" width="50%" alt="Logo">
</a>
</div>
<p align="center">
<em>The Enterprise-Grade Production-Ready Multi-Agent Orchestration Framework </em>
</p>
<p align="center">
<a href="https://pypi.org/project/swarms/" target="_blank">
<img alt="Python" src="https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54" />
<img alt="Version" src="https://img.shields.io/pypi/v/swarms?style=for-the-badge&color=3670A0">
</a>
</p>
<p align="center">
<a href="https://twitter.com/swarms_corp/">π¦ Twitter</a>
<span> β’ </span>
<a href="https://discord.gg/agora-999382051935506503">π’ Discord</a>
<span> β’ </span>
<a href="https://swarms.world">Swarms Platform</a>
<span> β’ </span>
<a href="https://docs.swarms.world">π Documentation</a>
</p>
[![Join our Discord](https://img.shields.io/badge/Discord-Join%20our%20server-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/agora-999382051935506503) [![Subscribe on YouTube](https://img.shields.io/badge/YouTube-Subscribe-red?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/@kyegomez3242) [![Connect on LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/kye-g-38759a207/) [![Follow on X.com](https://img.shields.io/badge/X.com-Follow-1DA1F2?style=for-the-badge&logo=x&logoColor=white)](https://x.com/kyegomezb)
[![GitHub issues](https://img.shields.io/github/issues/kyegomez/swarms)](https://github.com/kyegomez/swarms/issues) [![GitHub forks](https://img.shields.io/github/forks/kyegomez/swarms)](https://github.com/kyegomez/swarms/network) [![GitHub stars](https://img.shields.io/github/stars/kyegomez/swarms)](https://github.com/kyegomez/swarms/stargazers) [![GitHub license](https://img.shields.io/github/license/kyegomez/swarms)](https://github.com/kyegomez/swarms/blob/main/LICENSE)[![GitHub star chart](https://img.shields.io/github/stars/kyegomez/swarms?style=social)](https://star-history.com/#kyegomez/swarms)[![Dependency Status](https://img.shields.io/librariesio/github/kyegomez/swarms)](https://libraries.io/github/kyegomez/swarms) [![Downloads](https://static.pepy.tech/badge/swarms/month)](https://pepy.tech/project/swarms)
[![Share on Twitter](https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social&label=Share%20%40kyegomez/swarms)](https://twitter.com/intent/tweet?text=Check%20out%20this%20amazing%20AI%20project:%20&url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms) [![Share on Facebook](https://img.shields.io/badge/Share-%20facebook-blue)](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms) [![Share on LinkedIn](https://img.shields.io/badge/Share-%20linkedin-blue)](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&title=&summary=&source=)
[![Share on Reddit](https://img.shields.io/badge/-Share%20on%20Reddit-orange)](https://www.reddit.com/submit?url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&title=Swarms%20-%20the%20future%20of%20AI) [![Share on Hacker News](https://img.shields.io/badge/-Share%20on%20Hacker%20News-orange)](https://news.ycombinator.com/submitlink?u=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&t=Swarms%20-%20the%20future%20of%20AI) [![Share on Pinterest](https://img.shields.io/badge/-Share%20on%20Pinterest-red)](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&media=https%3A%2F%2Fexample.com%2Fimage.jpg&description=Swarms%20-%20the%20future%20of%20AI) [![Share on WhatsApp](https://img.shields.io/badge/-Share%20on%20WhatsApp-green)](https://api.whatsapp.com/send?text=Check%20out%20Swarms%20-%20the%20future%20of%20AI%20%23swarms%20%23AI%0A%0Ahttps%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms)
## β¨ Features
| Category | Features | Benefits |
|----------|----------|-----------|
| π’ Enterprise Architecture | β’ Production-Ready Infrastructure<br>β’ High Reliability Systems<br>β’ Modular Design<br>β’ Comprehensive Logging | β’ Reduced downtime<br>β’ Easier maintenance<br>β’ Better debugging<br>β’ Enhanced monitoring |
| π€ Agent Orchestration | β’ Hierarchical Swarms<br>β’ Parallel Processing<br>β’ Sequential Workflows<br>β’ Graph-based Workflows<br>β’ Dynamic Agent Rearrangement | β’ Complex task handling<br>β’ Improved performance<br>β’ Flexible workflows<br>β’ Optimized execution |
| π Integration Capabilities | β’ Multi-Model Support<br>β’ Custom Agent Creation<br>β’ Extensive Tool Library<br>β’ Multiple Memory Systems | β’ Provider flexibility<br>β’ Custom solutions<br>β’ Extended functionality<br>β’ Enhanced memory management |
| π Scalability | β’ Concurrent Processing<br>β’ Resource Management<br>β’ Load Balancing<br>β’ Horizontal Scaling | β’ Higher throughput<br>β’ Efficient resource use<br>β’ Better performance<br>β’ Easy scaling |
| π οΈ Developer Tools | β’ Simple API<br>β’ Extensive Documentation<br>β’ Active Community<br>β’ CLI Tools | β’ Faster development<br>β’ Easy learning curve<br>β’ Community support<br>β’ Quick deployment |
| π Security Features | β’ Error Handling<br>β’ Rate Limiting<br>β’ Monitoring Integration<br>β’ Audit Logging | β’ Improved reliability<br>β’ API protection<br>β’ Better monitoring<br>β’ Enhanced tracking |
| π Advanced Features | β’ SpreadsheetSwarm<br>β’ Group Chat<br>β’ Agent Registry<br>β’ Mixture of Agents | β’ Mass agent management<br>β’ Collaborative AI<br>β’ Centralized control<br>β’ Complex solutions |
| π Provider Support | β’ OpenAI<br>β’ Anthropic<br>β’ ChromaDB<br>β’ Custom Providers | β’ Provider flexibility<br>β’ Storage options<br>β’ Custom integration<br>β’ Vendor independence |
| πͺ Production Features | β’ Automatic Retries<br>β’ Async Support<br>β’ Environment Management<br>β’ Type Safety | β’ Better reliability<br>β’ Improved performance<br>β’ Easy configuration<br>β’ Safer code |
| π― Use Case Support | β’ Task-Specific Agents<br>β’ Custom Workflows<br>β’ Industry Solutions<br>β’ Extensible Framework | β’ Quick deployment<br>β’ Flexible solutions<br>β’ Industry readiness<br>β’ Easy customization |
----
## Requirements
- `python3.10` or above!
- `$ pip install -U swarms` And, don't forget to install swarms!
- `.env` file with API keys from your providers like `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`
- Set an `.env` Variable with your desired workspace dir: `WORKSPACE_DIR="agent_workspace"` or do it in your terminal with `export WORKSPACE_DIR="agent_workspace"`
- Finally, `swarms onboarding` to get you started.
## Guides and Walkthroughs
Refer to our documentation for production grade implementation details.
| Section | Links |
|----------------------|--------------------------------------------------------------------------------------------|
| Installation | [Installation](https://docs.swarms.world/en/latest/swarms/install/install/) |
| Quickstart | [Get Started](https://docs.swarms.world/en/latest/swarms/install/quickstart/) |
| Agent Internal Mechanisms | [Agent Architecture](https://docs.swarms.world/en/latest/swarms/framework/agents_explained/) |
| Agent API | [Agent API](https://docs.swarms.world/en/latest/swarms/structs/agent/) |
| Integrating External Agents Griptape, Autogen, etc | [Integrating External APIs](https://docs.swarms.world/en/latest/swarms/agents/external_party_agents/) |
| Creating Agents from YAML | [Creating Agents from YAML](https://docs.swarms.world/en/latest/swarms/agents/create_agents_yaml/) |
| Why You Need Swarms | [Why MultiAgent Collaboration is Necessary](https://docs.swarms.world/en/latest/swarms/concept/why/) |
| Swarm Architectures Analysis | [Swarm Architectures](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/) |
| Choosing the Right Swarm for Your Business ProblemΒΆ | [CLICK HERE](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/) |
| AgentRearrange Docs| [CLICK HERE](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/) |
## Install π»
Install the following packages with copy and paste
```bash
$ pip3 install -U swarms swarm-models swarms-memory
```
## Onboarding
Now that you have downloaded swarms with `pip3 install -U swarms`, we get access to the `CLI`. Get Onboarded with CLI Now with:
```bash
swarms onboarding
```
You can also run this command for help:
```bash
swarms help
```
For more documentation on the CLI [CLICK HERE](https://docs.swarms.world/en/latest/swarms/cli/main/)
---
# Usage Examples π€
Here are some example scripts to get you started. For more comprehensive documentation, visit our [docs](https://docs.swarms.world/en/latest/).
| Example Name | Description | Type of Examples | Link |
| --- | --- | --- | --- |
| Swarms Examples | A collection of simple examples to demonstrate Swarms capabilities. | Basic Usage | [https://github.com/The-Swarm-Corporation/swarms-examples?tab=readme-ov-file](https://github.com/The-Swarm-Corporation/swarms-examples?tab=readme-ov-file) |
| Cookbook | A comprehensive guide with recipes for various use cases and scenarios. | Advanced Usage | [https://github.com/The-Swarm-Corporation/Cookbook](https://github.com/The-Swarm-Corporation/Cookbook) |
---
## `Agent` Class
The `Agent` class is a fundamental component of the Swarms framework, designed to execute tasks autonomously. It fuses llms, tools and long-term memory capabilities to create a full stack agent. The `Agent` class is highly customizable, allowing for fine-grained control over its behavior and interactions.
### `run` Method
The `run` method is the primary entry point for executing tasks with an `Agent` instance. It accepts a task string as the main input task and processes it according to the agent's configuration. And, it can also accept an `img` parameter such as `img="image_filepath.png` to process images if you have a VLM attached such as `GPT4VisionAPI`
## Simple Example
```python
from swarms import Agent
agent = Agent(
agent_name="Stock-Analysis-Agent",
model_name="gpt-4o-mini",
max_loops="auto",
interactive=True,
streaming_on=True,
)
agent.run("What is the current market trend for tech stocks?")
```
### Settings and Customization
The `Agent` class offers a range of settings to tailor its behavior to specific needs. Some key settings include:
| Setting | Description | Default Value |
| --- | --- | --- |
| `agent_name` | The name of the agent. | "DefaultAgent" |
| `system_prompt` | The system prompt to use for the agent. | "Default system prompt." |
| `llm` | The language model to use for processing tasks. | `OpenAIChat` instance |
| `max_loops` | The maximum number of loops to execute for a task. | 1 |
| `autosave` | Enables or disables autosaving of the agent's state. | False |
| `dashboard` | Enables or disables the dashboard for the agent. | False |
| `verbose` | Controls the verbosity of the agent's output. | False |
| `dynamic_temperature_enabled` | Enables or disables dynamic temperature adjustment for the language model. | False |
| `saved_state_path` | The path to save the agent's state. | "agent_state.json" |
| `user_name` | The username associated with the agent. | "default_user" |
| `retry_attempts` | The number of retry attempts for failed tasks. | 1 |
| `context_length` | The maximum length of the context to consider for tasks. | 200000 |
| `return_step_meta` | Controls whether to return step metadata in the output. | False |
| `output_type` | The type of output to return (e.g., "json", "string"). | "string" |
```python
import os
from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
# Initialize the agent
agent = Agent(
agent_name="Financial-Analysis-Agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
model_name="gpt-4o-mini",
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="finance_agent.json",
user_name="swarms_corp",
retry_attempts=1,
context_length=200000,
return_step_meta=False,
output_type="string",
streaming_on=False,
)
agent.run(
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria"
)
```
-----
### Integrating RAG with Swarms for Enhanced Long-Term Memory
`Agent` equipped with quasi-infinite long term memory using RAG (Relational Agent Graph) for advanced document understanding, analysis, and retrieval capabilities.
**Mermaid Diagram for RAG Integration**
```mermaid
graph TD
A[Initialize Agent with RAG] --> B[Receive Task]
B --> C[Query Long-Term Memory]
C --> D[Process Task with Context]
D --> E[Generate Response]
E --> F[Update Long-Term Memory]
F --> G[Return Output]
```
```python
from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
import os
from swarms_memory import ChromaDB
# Initialize the ChromaDB client for long-term memory management
chromadb = ChromaDB(
metric="cosine", # Metric for similarity measurement
output_dir="finance_agent_rag", # Directory for storing RAG data
# docs_folder="artifacts", # Uncomment and specify the folder containing your documents
)
# Initialize the agent with RAG capabilities
agent = Agent(
agent_name="Financial-Analysis-Agent",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
agent_description="Agent creates a comprehensive financial analysis",
model_name="gpt-4o-mini",
max_loops="auto", # Auto-adjusts loops based on task complexity
autosave=True, # Automatically saves agent state
dashboard=False, # Disables dashboard for this example
verbose=True, # Enables verbose mode for detailed output
streaming_on=True, # Enables streaming for real-time processing
dynamic_temperature_enabled=True, # Dynamically adjusts temperature for optimal performance
saved_state_path="finance_agent.json", # Path to save agent state
user_name="swarms_corp", # User name for the agent
retry_attempts=3, # Number of retry attempts for failed tasks
context_length=200000, # Maximum length of the context to consider
long_term_memory=chromadb, # Integrates ChromaDB for long-term memory management
return_step_meta=False,
output_type="string",
)
# Run the agent with a sample task
agent.run(
"What are the components of a startups stock incentive equity plan"
)
```
-------
### Misc Agent Settings
We provide vast array of features to save agent states using json, yaml, toml, upload pdfs, batched jobs, and much more!
**Method Table**
| Method | Description |
| --- | --- |
| `to_dict()` | Converts the agent object to a dictionary. |
| `to_toml()` | Converts the agent object to a TOML string. |
| `model_dump_json()` | Dumps the model to a JSON file. |
| `model_dump_yaml()` | Dumps the model to a YAML file. |
| `ingest_docs()` | Ingests documents into the agent's knowledge base. |
| `receive_message()` | Receives a message from a user and processes it. |
| `send_agent_message()` | Sends a message from the agent to a user. |
| `filtered_run()` | Runs the agent with a filtered system prompt. |
| `bulk_run()` | Runs the agent with multiple system prompts. |
| `add_memory()` | Adds a memory to the agent. |
| `check_available_tokens()` | Checks the number of available tokens for the agent. |
| `tokens_checks()` | Performs token checks for the agent. |
| `print_dashboard()` | Prints the dashboard of the agent. |
| `get_docs_from_doc_folders()` | Fetches all the documents from the doc folders. |
| `activate_agentops()` | Activates agent operations. |
| `check_end_session_agentops()` | Checks the end of the session for agent operations. |
```python
# # Convert the agent object to a dictionary
print(agent.to_dict())
print(agent.to_toml())
print(agent.model_dump_json())
print(agent.model_dump_yaml())
# Ingest documents into the agent's knowledge base
agent.ingest_docs("your_pdf_path.pdf")
# Receive a message from a user and process it
agent.receive_message(name="agent_name", message="message")
# Send a message from the agent to a user
agent.send_agent_message(agent_name="agent_name", message="message")
# Ingest multiple documents into the agent's knowledge base
agent.ingest_docs("your_pdf_path.pdf", "your_csv_path.csv")
# Run the agent with a filtered system prompt
agent.filtered_run(
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria?"
)
# Run the agent with multiple system prompts
agent.bulk_run(
[
"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria?",
"Another system prompt",
]
)
# Add a memory to the agent
agent.add_memory("Add a memory to the agent")
# Check the number of available tokens for the agent
agent.check_available_tokens()
# Perform token checks for the agent
agent.tokens_checks()
# Print the dashboard of the agent
agent.print_dashboard()
# Fetch all the documents from the doc folders
agent.get_docs_from_doc_folders()
# Activate agent ops
agent.activate_agentops()
agent.check_end_session_agentops()
# Dump the model to a JSON file
agent.model_dump_json()
print(agent.to_toml())
```
### `Agent`with Pydantic BaseModel as Output Type
The following is an example of an agent that intakes a pydantic basemodel and outputs it at the same time:
```python
from pydantic import BaseModel, Field
from swarms import Agent
# Initialize the schema for the person's information
class Schema(BaseModel):
name: str = Field(..., title="Name of the person")
agent: int = Field(..., title="Age of the person")
is_student: bool = Field(..., title="Whether the person is a student")
courses: list[str] = Field(
..., title="List of courses the person is taking"
)
# Convert the schema to a JSON string
tool_schema = Schema(
name="Tool Name",
agent=1,
is_student=True,
courses=["Course1", "Course2"],
)
# Define the task to generate a person's information
task = "Generate a person's information based on the following schema:"
# Initialize the agent
agent = Agent(
agent_name="Person Information Generator",
system_prompt=(
"Generate a person's information based on the following schema:"
),
# Set the tool schema to the JSON string -- this is the key difference
tool_schema=tool_schema,
model_name="gpt-4o",
max_loops=3,
autosave=True,
dashboard=False,
streaming_on=True,
verbose=True,
interactive=True,
# Set the output type to the tool schema which is a BaseModel
output_type=tool_schema, # or dict, or str
metadata_output_type="json",
# List of schemas that the agent can handle
list_base_models=[tool_schema],
function_calling_format_type="OpenAI",
function_calling_type="json", # or soon yaml
)
# Run the agent to generate the person's information
generated_data = agent.run(task)
# Print the generated data
print(f"Generated data: {generated_data}")
```
### Multi Modal Autonomous Agent
Run the agent with multiple modalities useful for various real-world tasks in manufacturing, logistics, and health.
```python
import os
from dotenv import load_dotenv
from swarms import Agent
from swarm_models import GPT4VisionAPI
# Load the environment variables
load_dotenv()
# Initialize the language model
llm = GPT4VisionAPI(
openai_api_key=os.environ.get("OPENAI_API_KEY"),
max_tokens=500,
)
# Initialize the task
task = (
"Analyze this image of an assembly line and identify any issues such as"
" misaligned parts, defects, or deviations from the standard assembly"
" process. IF there is anything unsafe in the image, explain why it is"
" unsafe and how it could be improved."
)
img = "assembly_line.jpg"
## Initialize the workflow
agent = Agent(
agent_name = "Multi-ModalAgent",
llm=llm,
max_loops="auto",
autosave=True,
dashboard=True,
multi_modal=True
)
# Run the workflow on a task
agent.run(task, img)
```
----
### Local Agent `ToolAgent`
ToolAgent is an fully local agent that can use tools through JSON function calling. It intakes any open source model from huggingface and is extremely modular and plug in and play. We need help adding general support to all models soon.
```python
from pydantic import BaseModel, Field
from transformers import AutoModelForCausalLM, AutoTokenizer
from swarms import ToolAgent
from swarms.tools.json_utils import base_model_to_json
# Load the pre-trained model and tokenizer
model = AutoModelForCausalLM.from_pretrained(
"databricks/dolly-v2-12b",
load_in_4bit=True,
device_map="auto",
)
tokenizer = AutoTokenizer.from_pretrained("databricks/dolly-v2-12b")
# Initialize the schema for the person's information
class Schema(BaseModel):
name: str = Field(..., title="Name of the person")
agent: int = Field(..., title="Age of the person")
is_student: bool = Field(
..., title="Whether the person is a student"
)
courses: list[str] = Field(
..., title="List of courses the person is taking"
)
# Convert the schema to a JSON string
tool_schema = base_model_to_json(Schema)
# Define the task to generate a person's information
task = (
"Generate a person's information based on the following schema:"
)
# Create an instance of the ToolAgent class
agent = ToolAgent(
name="dolly-function-agent",
description="Ana gent to create a child data",
model=model,
tokenizer=tokenizer,
json_schema=tool_schema,
)
# Run the agent to generate the person's information
generated_data = agent.run(task)
# Print the generated data
print(f"Generated data: {generated_data}")
```
## Understanding Swarms
A swarm refers to a group of more than two agents working collaboratively to achieve a common goal. These agents can be software entities, such as llms that interact with each other to perform complex tasks. The concept of a swarm is inspired by natural systems like ant colonies or bird flocks, where simple individual behaviors lead to complex group dynamics and problem-solving capabilities.
### How Swarm Architectures Facilitate Communication
Swarm architectures are designed to establish and manage communication between agents within a swarm. These architectures define how agents interact, share information, and coordinate their actions to achieve the desired outcomes. Here are some key aspects of swarm architectures:
1. **Hierarchical Communication**: In hierarchical swarms, communication flows from higher-level agents to lower-level agents. Higher-level agents act as coordinators, distributing tasks and aggregating results. This structure is efficient for tasks that require top-down control and decision-making.
2. **Parallel Communication**: In parallel swarms, agents operate independently and communicate with each other as needed. This architecture is suitable for tasks that can be processed concurrently without dependencies, allowing for faster execution and scalability.
3. **Sequential Communication**: Sequential swarms process tasks in a linear order, where each agent's output becomes the input for the next agent. This ensures that tasks with dependencies are handled in the correct sequence, maintaining the integrity of the workflow.
Swarm architectures leverage these communication patterns to ensure that agents work together efficiently, adapting to the specific requirements of the task at hand. By defining clear communication protocols and interaction models, swarm architectures enable the seamless orchestration of multiple agents, leading to enhanced performance and problem-solving capabilities.
| **Name** | **Description** | **Code Link** | **Use Cases** |
|-------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------|
| Hierarchical Swarms | A system where agents are organized in a hierarchy, with higher-level agents coordinating lower-level agents to achieve complex tasks. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#hierarchical-swarm) | Manufacturing process optimization, multi-level sales management, healthcare resource coordination |
| Agent Rearrange | A setup where agents rearrange themselves dynamically based on the task requirements and environmental conditions. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/) | Adaptive manufacturing lines, dynamic sales territory realignment, flexible healthcare staffing |
| Concurrent Workflows | Agents perform different tasks simultaneously, coordinating to complete a larger goal. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#concurrent-workflows) | Concurrent production lines, parallel sales operations, simultaneous patient care processes |
| Sequential Coordination | Agents perform tasks in a specific sequence, where the completion of one task triggers the start of the next. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/) | Step-by-step assembly lines, sequential sales processes, stepwise patient treatment workflows |
| Parallel Processing | Agents work on different parts of a task simultaneously to speed up the overall process. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#parallel-processing) | Parallel data processing in manufacturing, simultaneous sales analytics, concurrent medical tests |
| Mixture of Agents | A heterogeneous swarm where agents with different capabilities are combined to solve complex problems. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/moa/) | Financial forecasting, complex problem-solving requiring diverse skills |
| Graph Workflow | Agents collaborate in a directed acyclic graph (DAG) format to manage dependencies and parallel tasks. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/graph_workflow/) | AI-driven software development pipelines, complex project management |
| Group Chat | Agents engage in a chat-like interaction to reach decisions collaboratively. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/group_chat/) | Real-time collaborative decision-making, contract negotiations |
| Agent Registry | A centralized registry where agents are stored, retrieved, and invoked dynamically. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/agent_registry/) | Dynamic agent management, evolving recommendation engines |
| 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 |
### `SequentialWorkflow`
Sequential Workflow enables you to sequentially execute tasks with `Agent` and then pass the output into the next agent and onwards until you have specified your max loops.
```mermaid
graph LR
A[Agent 1] --> B[Agent 2]
B --> C[Agent 3]
C --> D[Agent 4]
D --> E[Max Loops]
E --> F[End]
```
### Methods
| Method | Description | Parameters | Return Value |
|--------|-------------|------------|--------------|
| `__init__` | Initialize the SequentialWorkflow | `agents`: List of Agent objects<br>`max_loops`: Maximum number of iterations<br>`verbose`: Boolean for verbose output | None |
| `run` | Execute the workflow | `input_data`: Initial input for the first agent | Final output after all agents have processed |
### Inputs
| Input | Type | Description |
|-------|------|-------------|
| `agents` | List[Agent] | List of Agent objects to be executed sequentially |
| `max_loops` | int | Maximum number of times the entire sequence will be repeated |
| `verbose` | bool | If True, print detailed information during execution |
### Output
The `run` method returns the final output after all agents have processed the input sequentially.
In this example, each `Agent` represents a task that is executed sequentially. The output of each agent is passed to the next agent in the sequence until the maximum number of loops is reached. This workflow is particularly useful for tasks that require a series of steps to be executed in a specific order, such as data processing pipelines or complex calculations that rely on the output of previous steps.
```python
import os
from swarms import Agent, SequentialWorkflow
from swarm_models import OpenAIChat
# model = Anthropic(anthropic_api_key=os.getenv("ANTHROPIC_API_KEY"))
company = "Nvidia"
# Get the OpenAI API key from the environment variable
api_key = os.getenv("GROQ_API_KEY")
# Model
model = OpenAIChat(
openai_api_base="https://api.groq.com/openai/v1",
openai_api_key=api_key,
model_name="llama-3.1-70b-versatile",
temperature=0.1,
)
# Initialize the Managing Director agent
managing_director = Agent(
agent_name="Managing-Director",
system_prompt=f"""
As the Managing Director at Blackstone, your role is to oversee the entire investment analysis process for potential acquisitions.
Your responsibilities include:
1. Setting the overall strategy and direction for the analysis
2. Coordinating the efforts of the various team members and ensuring a comprehensive evaluation
3. Reviewing the findings and recommendations from each team member
4. Making the final decision on whether to proceed with the acquisition
For the current potential acquisition of {company}, direct the tasks for the team to thoroughly analyze all aspects of the company, including its financials, industry position, technology, market potential, and regulatory compliance. Provide guidance and feedback as needed to ensure a rigorous and unbiased assessment.
""",
llm=model,
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="managing-director.json",
)
# Initialize the Vice President of Finance
vp_finance = Agent(
agent_name="VP-Finance",
system_prompt=f"""
As the Vice President of Finance at Blackstone, your role is to lead the financial analysis of potential acquisitions.
For the current potential acquisition of {company}, your tasks include:
1. Conducting a thorough review of {company}' financial statements, including income statements, balance sheets, and cash flow statements
2. Analyzing key financial metrics such as revenue growth, profitability margins, liquidity ratios, and debt levels
3. Assessing the company's historical financial performance and projecting future performance based on assumptions and market conditions
4. Identifying any financial risks or red flags that could impact the acquisition decision
5. Providing a detailed report on your findings and recommendations to the Managing Director
Be sure to consider factors such as the sustainability of {company}' business model, the strength of its customer base, and its ability to generate consistent cash flows. Your analysis should be data-driven, objective, and aligned with Blackstone's investment criteria.
""",
llm=model,
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="vp-finance.json",
)
# Initialize the Industry Analyst
industry_analyst = Agent(
agent_name="Industry-Analyst",
system_prompt=f"""
As the Industry Analyst at Blackstone, your role is to provide in-depth research and analysis on the industries and markets relevant to potential acquisitions.
For the current potential acquisition of {company}, your tasks include:
1. Conducting a comprehensive analysis of the industrial robotics and automation solutions industry, including market size, growth rates, key trends, and future prospects
2. Identifying the major players in the industry and assessing their market share, competitive strengths and weaknesses, and strategic positioning
3. Evaluating {company}' competitive position within the industry, including its market share, differentiation, and competitive advantages
4. Analyzing the key drivers and restraints for the industry, such as technological advancements, labor costs, regulatory changes, and economic conditions
5. Identifying potential risks and opportunities for {company} based on the industry analysis, such as disruptive technologies, emerging markets, or shifts in customer preferences
Your analysis should provide a clear and objective assessment of the attractiveness and future potential of the industrial robotics industry, as well as {company}' positioning within it. Consider both short-term and long-term factors, and provide evidence-based insights to inform the investment decision.
""",
llm=model,
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="industry-analyst.json",
)
# Initialize the Technology Expert
tech_expert = Agent(
agent_name="Tech-Expert",
system_prompt=f"""
As the Technology Expert at Blackstone, your role is to assess the technological capabilities, competitive advantages, and potential risks of companies being considered for acquisition.
For the current potential acquisition of {company}, your tasks include:
1. Conducting a deep dive into {company}' proprietary technologies, including its robotics platforms, automation software, and AI capabilities
2. Assessing the uniqueness, scalability, and defensibility of {company}' technology stack and intellectual property
3. Comparing {company}' technologies to those of its competitors and identifying any key differentiators or technology gaps
4. Evaluating {company}' research and development capabilities, including its innovation pipeline, engineering talent, and R&D investments
5. Identifying any potential technology risks or disruptive threats that could impact {company}' long-term competitiveness, such as emerging technologies or expiring patents
Your analysis should provide a comprehensive assessment of {company}' technological strengths and weaknesses, as well as the sustainability of its competitive advantages. Consider both the current state of its technology and its future potential in light of industry trends and advancements.
""",
llm=model,
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="tech-expert.json",
)
# Initialize the Market Researcher
market_researcher = Agent(
agent_name="Market-Researcher",
system_prompt=f"""
As the Market Researcher at Blackstone, your role is to analyze the target company's customer base, market share, and growth potential to assess the commercial viability and attractiveness of the potential acquisition.
For the current potential acquisition of {company}, your tasks include:
1. Analyzing {company}' current customer base, including customer segmentation, concentration risk, and retention rates
2. Assessing {company}' market share within its target markets and identifying key factors driving its market position
3. Conducting a detailed market sizing and segmentation analysis for the industrial robotics and automation markets, including identifying high-growth segments and emerging opportunities
4. Evaluating the demand drivers and sales cycles for {company}' products and services, and identifying any potential risks or limitations to adoption
5. Developing financial projections and estimates for {company}' revenue growth potential based on the market analysis and assumptions around market share and penetration
Your analysis should provide a data-driven assessment of the market opportunity for {company} and the feasibility of achieving our investment return targets. Consider both bottom-up and top-down market perspectives, and identify any key sensitivities or assumptions in your projections.
""",
llm=model,
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="market-researcher.json",
)
# Initialize the Regulatory Specialist
regulatory_specialist = Agent(
agent_name="Regulatory-Specialist",
system_prompt=f"""
As the Regulatory Specialist at Blackstone, your role is to identify and assess any regulatory risks, compliance requirements, and potential legal liabilities associated with potential acquisitions.
For the current potential acquisition of {company}, your tasks include:
1. Identifying all relevant regulatory bodies and laws that govern the operations of {company}, including industry-specific regulations, labor laws, and environmental regulations
2. Reviewing {company}' current compliance policies, procedures, and track record to identify any potential gaps or areas of non-compliance
3. Assessing the potential impact of any pending or proposed changes to relevant regulations that could affect {company}' business or create additional compliance burdens
4. Evaluating the potential legal liabilities and risks associated with {company}' products, services, and operations, including product liability, intellectual property, and customer contracts
5. Providing recommendations on any regulatory or legal due diligence steps that should be taken as part of the acquisition process, as well as any post-acquisition integration considerations
Your analysis should provide a comprehensive assessment of the regulatory and legal landscape surrounding {company}, and identify any material risks or potential deal-breakers. Consider both the current state and future outlook, and provide practical recommendations to mitigate identified risks.
""",
llm=model,
max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="regulatory-specialist.json",
)
# Create a list of agents
agents = [
managing_director,
vp_finance,
industry_analyst,
tech_expert,
market_researcher,
regulatory_specialist,
]
swarm = SequentialWorkflow(
name="blackstone-private-equity-advisors",
agents=agents,
)
print(
swarm.run(
"Analyze nvidia if it's a good deal to invest in now 10B"
)
)
```
------
## `AgentRearrange`
The `AgentRearrange` orchestration technique, inspired by Einops and einsum, allows you to define and map out the relationships between various agents. It provides a powerful tool for orchestrating complex workflows, enabling you to specify linear and sequential relationships such as `a -> a1 -> a2 -> a3`, or concurrent relationships where the first agent sends a message to 3 agents simultaneously: `a -> a1, a2, a3`. This level of customization allows for the creation of highly efficient and dynamic workflows, where agents can work in parallel or in sequence as needed. The `AgentRearrange` technique is a valuable addition to the swarms library, providing a new level of flexibility and control over the orchestration of agents. For more detailed information and examples, please refer to the [official documentation](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/).
[Check out my video on agent rearrange!](https://youtu.be/Rq8wWQ073mg)
### Methods
| Method | Description | Parameters | Return Value |
|--------|-------------|------------|--------------|
| `__init__` | Initialize the AgentRearrange | `agents`: List of Agent objects<br>`flow`: String describing the agent flow | None |
| `run` | Execute the workflow | `input_data`: Initial input for the first agent | Final output after all agents have processed |
### Inputs
| Input | Type | Description |
|-------|------|-------------|
| `agents` | List[Agent] | List of Agent objects to be orchestrated |
| `flow` | str | String describing the flow of agents (e.g., "A -> B, C") |
### Output
The `run` method returns the final output after all agents have processed the input according to the specified flow.
```python
from datetime import datetime
from swarms import Agent, AgentRearrange, create_file_in_folder
chief_medical_officer = Agent(
agent_name="Chief Medical Officer",
system_prompt="""You are the Chief Medical Officer coordinating a team of medical specialists for viral disease diagnosis.
Your responsibilities include:
- Gathering initial patient symptoms and medical history
- Coordinating with specialists to form differential diagnoses
- Synthesizing different specialist opinions into a cohesive diagnosis
- Ensuring all relevant symptoms and test results are considered
- Making final diagnostic recommendations
- Suggesting treatment plans based on team input
- Identifying when additional specialists need to be consulted
Guidelines:
1. Always start with a comprehensive patient history
2. Consider both common and rare viral conditions
3. Factor in patient demographics and risk factors
4. Document your reasoning process clearly
5. Highlight any critical or emergency symptoms
6. Note any limitations or uncertainties in the diagnosis
Format all responses with clear sections for:
- Initial Assessment
- Differential Diagnoses
- Specialist Consultations Needed
- Recommended Next Steps""",
model_name="gpt-4o", # Models from litellm -> claude-2
max_loops=1,
)
# Viral Disease Specialist
virologist = Agent(
agent_name="Virologist",
system_prompt="""You are a specialist in viral diseases with expertise in:
- Respiratory viruses (Influenza, Coronavirus, RSV)
- Systemic viral infections (EBV, CMV, HIV)
- Childhood viral diseases (Measles, Mumps, Rubella)
- Emerging viral threats
Your role involves:
1. Analyzing symptoms specific to viral infections
2. Distinguishing between different viral pathogens
3. Assessing viral infection patterns and progression
4. Recommending specific viral tests
5. Evaluating epidemiological factors
For each case, consider:
- Incubation periods
- Transmission patterns
- Seasonal factors
- Geographic prevalence
- Patient immune status
- Current viral outbreaks
Provide detailed analysis of:
- Characteristic viral symptoms
- Disease progression timeline
- Risk factors for severe disease
- Potential complications""",
model_name="gpt-4o",
max_loops=1,
)
# Internal Medicine Specialist
internist = Agent(
agent_name="Internist",
system_prompt="""You are an Internal Medicine specialist responsible for:
- Comprehensive system-based evaluation
- Integration of symptoms across organ systems
- Identification of systemic manifestations
- Assessment of comorbidities
For each case, analyze:
1. Vital signs and their implications
2. System-by-system review (cardiovascular, respiratory, etc.)
3. Impact of existing medical conditions
4. Medication interactions and contraindications
5. Risk stratification
Consider these aspects:
- Age-related factors
- Chronic disease impact
- Medication history
- Social and environmental factors
Document:
- Physical examination findings
- System-specific symptoms
- Relevant lab abnormalities
- Risk factors for complications""",
model_name="gpt-4o",
max_loops=1,
)
# Diagnostic Synthesizer
synthesizer = Agent(
agent_name="Diagnostic Synthesizer",
system_prompt="""You are responsible for synthesizing all specialist inputs to create a final diagnostic assessment:
Core responsibilities:
1. Integrate findings from all specialists
2. Identify patterns and correlations
3. Resolve conflicting opinions
4. Generate probability-ranked differential diagnoses
5. Recommend additional testing if needed
Analysis framework:
- Weight evidence based on reliability and specificity
- Consider epidemiological factors
- Evaluate diagnostic certainty
- Account for test limitations
Provide structured output including:
1. Primary diagnosis with confidence level
2. Supporting evidence summary
3. Alternative diagnoses to consider
4. Recommended confirmatory tests
5. Red flags or warning signs
6. Follow-up recommendations
Documentation requirements:
- Clear reasoning chain
- Evidence quality assessment
- Confidence levels for each diagnosis
- Knowledge gaps identified
- Risk assessment""",
model_name="gpt-4o",
max_loops=1,
)
# Create agent list
agents = [chief_medical_officer, virologist, internist, synthesizer]
# Define diagnostic flow
flow = f"""{chief_medical_officer.agent_name} -> {virologist.agent_name} -> {internist.agent_name} -> {synthesizer.agent_name}"""
# Create the swarm system
diagnosis_system = AgentRearrange(
name="Medical-nlp-diagnosis-swarm",
description="natural language symptions to diagnosis report",
agents=agents,
flow=flow,
max_loops=1,
output_type="all",
)
# Example usage
if __name__ == "__main__":
# Example patient case
patient_case = """
Patient: 45-year-old female
Presenting symptoms:
- Fever (101.5Β°F) for 3 days
- Dry cough
- Fatigue
- Mild shortness of breath
Medical history:
- Controlled hypertension
- No recent travel
- Fully vaccinated for COVID-19
- No known sick contacts
"""
# Add timestamp to the patient case
case_info = f"Timestamp: {datetime.now()}\nPatient Information: {patient_case}"
# Run the diagnostic process
diagnosis = diagnosis_system.run(case_info)
# Create a folder and file called reports
create_file_in_folder(
"reports", "medical_analysis_agent_rearrange.md", diagnosis
)
```
## `HierarhicalSwarm`
Coming soon...
## `GraphSwarm`
The `GraphSwarm` is a workflow management system designed to orchestrate complex tasks by leveraging the power of graph theory. It enables the creation of a directed acyclic graph (DAG) to model dependencies between tasks and agents. This allows for efficient task assignment, execution, and monitoring.
Here's a breakdown of how the `GraphSwarm` works:
1. **Node Creation**: The `GraphSwarm` workflow is composed of nodes, which can be either agents or tasks. Agents are responsible for executing tasks, and tasks represent specific operations that need to be performed. In the example, two agents (`agent1` and `agent2`) and one task (`task1`) are created.
2. **Edge Definition**: Edges are used to define the relationships between nodes. In this case, edges are created to connect `agent1` and `agent2` to `task1`, indicating that both agents are capable of executing `task1`.
3. **Entry and End Points**: The `GraphSwarm` workflow requires the definition of entry points (where the workflow starts) and end points (where the workflow concludes). In this example, `agent1` and `agent2` are set as entry points, and `task1` is set as the end point.
4. **Visualization**: The `GraphSwarm` provides a visualization feature to graphically represent the workflow. This allows for easy understanding and debugging of the workflow structure.
5. **Execution**: The `GraphSwarm` workflow is executed by traversing the graph from the entry points to the end points. In this case, both `agent1` and `agent2` execute `task1` concurrently, and the results are collected.
6. **Results**: The final results of the workflow execution are aggregated and returned. In this example, the result of executing `task1` is "Task completed".
The `GraphSwarm` offers several benefits, including:
* **Concurrency**: Enables the execution of tasks concurrently, improving overall workflow efficiency.
* **Flexibility**: Allows for dynamic task assignment based on agent availability and task requirements.
* **Scalability**: Supports the addition of new agents and tasks as needed, making it suitable for large-scale workflows.
* **Visualization**: Provides a graphical representation of the workflow, facilitating understanding and debugging.
By leveraging the `GraphSwarm`, complex workflows can be efficiently managed, and tasks can be executed in a coordinated and scalable manner.
### Methods
| Method | Description | Parameters | Return Value |
|--------|-------------|------------|--------------|
| `add_node` | Add a node to the graph | `node`: Node object | None |
| `add_edge` | Add an edge to the graph | `edge`: Edge object | None |
| `set_entry_points` | Set the entry points of the graph | `entry_points`: List of node IDs | None |
| `set_end_points` | Set the end points of the graph | `end_points`: List of node IDs | None |
| `visualize` | Generate a visual representation of the graph | None | String representation of the graph |
| `run` | Execute the workflow | None | Dictionary of execution results |
### Inputs
| Input | Type | Description |
|-------|------|-------------|
| `Node` | Object | Represents a node in the graph (agent or task) |
| `Edge` | Object | Represents an edge connecting two nodes |
| `entry_points` | List[str] | List of node IDs where the workflow starts |
| `end_points` | List[str] | List of node IDs where the workflow ends |
### Output
The `run` method returns a dictionary containing the execution results of all nodes in the graph.
```python
import os
from dotenv import load_dotenv
from swarms import Agent, Edge, GraphWorkflow, Node, NodeType
from swarm_models import OpenAIChat
load_dotenv()
api_key = os.environ.get("OPENAI_API_KEY")
llm = OpenAIChat(
temperature=0.5, openai_api_key=api_key, max_tokens=4000
)
agent1 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True)
agent2 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True)
def sample_task():
print("Running sample task")
return "Task completed"
wf_graph = GraphWorkflow()
wf_graph.add_node(Node(id="agent1", type=NodeType.AGENT, agent=agent1))
wf_graph.add_node(Node(id="agent2", type=NodeType.AGENT, agent=agent2))
wf_graph.add_node(
Node(id="task1", type=NodeType.TASK, callable=sample_task)
)
wf_graph.add_edge(Edge(source="agent1", target="task1"))
wf_graph.add_edge(Edge(source="agent2", target="task1"))
wf_graph.set_entry_points(["agent1", "agent2"])
wf_graph.set_end_points(["task1"])
print(wf_graph.visualize())
# Run the workflow
results = wf_graph.run()
print("Execution results:", results)
```
## `MixtureOfAgents`
This is an implementation based on the paper: "Mixture-of-Agents Enhances Large Language Model Capabilities" by together.ai, available at [https://arxiv.org/abs/2406.04692](https://arxiv.org/abs/2406.04692). It achieves state-of-the-art (SOTA) results on AlpacaEval 2.0, MT-Bench, and FLASK, surpassing GPT-4 Omni. This architecture is particularly suitable for tasks that require parallelization followed by sequential processing in another loop.
### Methods
| Method | Description | Parameters | Return Value |
|--------|-------------|------------|--------------|
| `__init__` | Initialize the MixtureOfAgents | `name`: Name of the swarm<br>`agents`: List of Agent objects<br>`layers`: Number of processing layers<br>`final_agent`: Agent for final processing | None |
| `run` | Execute the swarm | `task`: Input task for the swarm | Final output after all agents have processed |
### Inputs
| Input | Type | Description |
|-------|------|-------------|
| `name` | str | Name of the swarm |
| `agents` | List[Agent] | List of Agent objects to be used in the swarm |
| `layers` | int | Number of processing layers in the swarm |
| `final_agent` | Agent | Agent responsible for final processing |
### Output
The `run` method returns the final output after all agents have processed the input according to the specified layers and final agent.
```python
import os
from swarms import Agent, MixtureOfAgents
# Agent 1: Financial Statement Analyzer
agent1 = Agent(
agent_name="FinancialStatementAnalyzer",
model_name="gpt-4o",
system_prompt="""You are a Financial Statement Analyzer specializing in 10-K SEC reports. Your primary focus is on analyzing the financial statements, including the balance sheet, income statement, and cash flow statement.
Key responsibilities:
1. Identify and explain significant changes in financial metrics year-over-year.
2. Calculate and interpret key financial ratios (e.g., liquidity ratios, profitability ratios, leverage ratios).
3. Analyze trends in revenue, expenses, and profitability.
4. Highlight any red flags or areas of concern in the financial statements.
5. Provide insights on the company's financial health and performance based on the data.
When analyzing, consider industry standards and compare the company's performance to its peers when possible. Your analysis should be thorough, data-driven, and provide actionable insights for investors and stakeholders.""",
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="financial_statement_analyzer_state.json",
user_name="swarms_corp",
retry_attempts=1,
context_length=200000,
return_step_meta=False,
)
# Agent 2: Risk Assessment Specialist
agent2 = Agent(
agent_name="RiskAssessmentSpecialist",
model_name="gpt-4o",
system_prompt="""You are a Risk Assessment Specialist focusing on 10-K SEC reports. Your primary role is to identify, analyze, and evaluate potential risks disclosed in the report.
Key responsibilities:
1. Thoroughly review the "Risk Factors" section of the 10-K report.
2. Identify and categorize different types of risks (e.g., operational, financial, legal, market, technological).
3. Assess the potential impact and likelihood of each identified risk.
4. Analyze the company's risk mitigation strategies and their effectiveness.
5. Identify any emerging risks not explicitly mentioned but implied by the company's operations or market conditions.
6. Compare the company's risk profile with industry peers when possible.
Your analysis should provide a comprehensive overview of the company's risk landscape, helping stakeholders understand the potential challenges and uncertainties facing the business. Be sure to highlight any critical risks that could significantly impact the company's future performance or viability.""",
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="risk_assessment_specialist_state.json",
user_name="swarms_corp",
retry_attempts=1,
context_length=200000,
return_step_meta=False,
)
# Agent 3: Business Strategy Evaluator
agent3 = Agent(
agent_name="BusinessStrategyEvaluator",
model_name="gpt-4o",
system_prompt="""You are a Business Strategy Evaluator specializing in analyzing 10-K SEC reports. Your focus is on assessing the company's overall strategy, market position, and future outlook.
Key responsibilities:
1. Analyze the company's business description, market opportunities, and competitive landscape.
2. Evaluate the company's products or services, including their market share and growth potential.
3. Assess the effectiveness of the company's current business strategy and its alignment with market trends.
4. Identify key performance indicators (KPIs) and evaluate the company's performance against these metrics.
5. Analyze management's discussion and analysis (MD&A) section to understand their perspective on the business.
6. Identify potential growth opportunities or areas for improvement in the company's strategy.
7. Compare the company's strategic position with key competitors in the industry.
Your analysis should provide insights into the company's strategic direction, its ability to create value, and its potential for future growth. Consider both short-term and long-term perspectives in your evaluation.""",
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="business_strategy_evaluator_state.json",
user_name="swarms_corp",
retry_attempts=1,
context_length=200000,
return_step_meta=False,
)
# Aggregator Agent
aggregator_agent = Agent(
agent_name="10KReportAggregator",
model_name="gpt-4o",
system_prompt="""You are the 10-K Report Aggregator, responsible for synthesizing and summarizing the analyses provided by the Financial Statement Analyzer, Risk Assessment Specialist, and Business Strategy Evaluator. Your goal is to create a comprehensive, coherent, and insightful summary of the 10-K SEC report.
Key responsibilities:
1. Integrate the financial analysis, risk assessment, and business strategy evaluation into a unified report.
2. Identify and highlight the most critical information and insights from each specialist's analysis.
3. Reconcile any conflicting information or interpretations among the specialists' reports.
4. Provide a balanced view of the company's overall performance, risks, and strategic position.
5. Summarize key findings and their potential implications for investors and stakeholders.
6. Identify any areas where further investigation or clarification may be needed.
Your final report should be well-structured, easy to understand, and provide a holistic view of the company based on the 10-K SEC report. It should offer valuable insights for decision-making while acknowledging any limitations or uncertainties in the analysis.""",
max_loops=1,
autosave=True,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="10k_report_aggregator_state.json",
user_name="swarms_corp",
retry_attempts=1,
context_length=200000,
return_step_meta=False,
)
# Create the Mixture of Agents class
moa = MixtureOfAgents(
agents=[agent1, agent2, agent3],
aggregator_agent=aggregator_agent,
aggregator_system_prompt="""As the 10-K Report Aggregator, your task is to synthesize the analyses provided by the Financial Statement Analyzer, Risk Assessment Specialist, and Business Strategy Evaluator into a comprehensive and coherent report.
Follow these steps:
1. Review and summarize the key points from each specialist's analysis.
2. Identify common themes and insights across the analyses.
3. Highlight any discrepancies or conflicting interpretations, if present.
4. Provide a balanced and integrated view of the company's financial health, risks, and strategic position.
5. Summarize the most critical findings and their potential impact on investors and stakeholders.
6. Suggest areas for further investigation or monitoring, if applicable.
Your final output should be a well-structured, insightful report that offers a holistic view of the company based on the 10-K SEC report analysis.""",
layers=3,
)
# Example usage
company_name = "NVIDIA"
out = moa.run(
f"Analyze the latest 10-K SEC report for {company_name}. Provide a comprehensive summary of the company's financial performance, risk profile, and business strategy."
)
print(out)
```
## SpreadSheetSwarm
The `SpreadSheetSwarm` is designed for concurrent management and oversight of thousands of agents, facilitating a one-to-many approach for efficient task processing and output analysis.
### Key Features
* **Concurrency**: Enables the simultaneous execution of multiple agents, significantly reducing processing time and increasing overall system efficiency.
* **One-to-Many**: Allows a single task to be dynamically distributed among multiple agents, ensuring that each agent is utilized to its full potential.
* **Scalability**: Supports the integration of thousands of agents, making it an ideal solution for large-scale task processing and data analysis.
### Methods
| Method | Description | Parameters | Return Value |
|--------|-------------|------------|--------------|
| `__init__` | Initialize the SpreadSheetSwarm | `name`: Name of the swarm<br>`description`: Description of the swarm<br>`agents`: List of Agent objects<br>`autosave_on`: Boolean to enable autosave<br>`save_file_path`: Path to save the spreadsheet<br>`run_all_agents`: Boolean to run all agents or not<br>`max_loops`: Maximum number of loops | None |
| `run` | Execute the swarm | `task`: Input task for the swarm | Dictionary of agent outputs |
### Inputs
| Input | Type | Description |
|-------|------|-------------|
| `name` | str | Name of the swarm |
| `description` | str | Description of the swarm's purpose |
| `agents` | List[Agent] | List of Agent objects to be used in the swarm |
| `autosave_on` | bool | Enable autosaving of results |
| `save_file_path` | str | Path to save the spreadsheet results |
| `run_all_agents` | bool | Whether to run all agents or select based on relevance |
| `max_loops` | int | Maximum number of processing loops |
### Output
The `run` method returns a dictionary containing the outputs of each agent that processed the task.
[Learn more at the docs here:](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/)
```python
import os
from swarms import Agent, SpreadSheetSwarm
from swarm_models import OpenAIChat
# Define custom system prompts for each social media platform
TWITTER_AGENT_SYS_PROMPT = """
You are a Twitter marketing expert specializing in real estate. Your task is to create engaging, concise tweets to promote properties, analyze trends to maximize engagement, and use appropriate hashtags and timing to reach potential buyers.
"""
INSTAGRAM_AGENT_SYS_PROMPT = """
You are an Instagram marketing expert focusing on real estate. Your task is to create visually appealing posts with engaging captions and hashtags to showcase properties, targeting specific demographics interested in real estate.
"""
FACEBOOK_AGENT_SYS_PROMPT = """
You are a Facebook marketing expert for real estate. Your task is to craft posts optimized for engagement and reach on Facebook, including using images, links, and targeted messaging to attract potential property buyers.
"""
LINKEDIN_AGENT_SYS_PROMPT = """
You are a LinkedIn marketing expert for the real estate industry. Your task is to create professional and informative posts, highlighting property features, market trends, and investment opportunities, tailored to professionals and investors.
"""
EMAIL_AGENT_SYS_PROMPT = """
You are an Email marketing expert specializing in real estate. Your task is to write compelling email campaigns to promote properties, focusing on personalization, subject lines, and effective call-to-action strategies to drive conversions.
"""
# Initialize your agents for different social media platforms
agents = [
Agent(
agent_name="Twitter-RealEstate-Agent",
system_prompt=TWITTER_AGENT_SYS_PROMPT,
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="twitter_realestate_agent.json",
user_name="realestate_swarms",
retry_attempts=1,
),
Agent(
agent_name="Instagram-RealEstate-Agent",
system_prompt=INSTAGRAM_AGENT_SYS_PROMPT,
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="instagram_realestate_agent.json",
user_name="realestate_swarms",
retry_attempts=1,
),
Agent(
agent_name="Facebook-RealEstate-Agent",
system_prompt=FACEBOOK_AGENT_SYS_PROMPT,
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="facebook_realestate_agent.json",
user_name="realestate_swarms",
retry_attempts=1,
),
Agent(
agent_name="LinkedIn-RealEstate-Agent",
system_prompt=LINKEDIN_AGENT_SYS_PROMPT,
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="linkedin_realestate_agent.json",
user_name="realestate_swarms",
retry_attempts=1,
),
Agent(
agent_name="Email-RealEstate-Agent",
system_prompt=EMAIL_AGENT_SYS_PROMPT,
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
saved_state_path="email_realestate_agent.json",
user_name="realestate_swarms",
retry_attempts=1,
),
]
# Create a Swarm with the list of agents
swarm = SpreadSheetSwarm(
name="Real-Estate-Marketing-Swarm",
description="A swarm that processes real estate marketing tasks using multiple agents on different threads.",
agents=agents,
autosave_on=True,
save_file_path="real_estate_marketing_spreadsheet.csv",
run_all_agents=False,
max_loops=2,
)
# Run the swarm
swarm.run(
task="""
Create posts to promote luxury properties in North Texas, highlighting their features, location, and investment potential. Include relevant hashtags, images, and engaging captions.
Property:
$10,399,000
1609 Meandering Way Dr, Roanoke, TX 76262
Link to the property: https://www.zillow.com/homedetails/1609-Meandering-Way-Dr-Roanoke-TX-76262/308879785_zpid/
What's special
Unveiling a new custom estate in the prestigious gated Quail Hollow Estates! This impeccable residence, set on a sprawling acre surrounded by majestic trees, features a gourmet kitchen equipped with top-tier Subzero and Wolf appliances. European soft-close cabinets and drawers, paired with a double Cambria Quartzite island, perfect for family gatherings. The first-floor game room&media room add extra layers of entertainment. Step into the outdoor sanctuary, where a sparkling pool and spa, and sunken fire pit, beckon leisure. The lavish master suite features stunning marble accents, custom his&her closets, and a secure storm shelter.Throughout the home,indulge in the visual charm of designer lighting and wallpaper, elevating every space. The property is complete with a 6-car garage and a sports court, catering to the preferences of basketball or pickleball enthusiasts. This residence seamlessly combines luxury&recreational amenities, making it a must-see for the discerning buyer.
Facts & features
Interior
Bedrooms & bathrooms
Bedrooms: 6
Bathrooms: 8
Full bathrooms: 7
1/2 bathrooms: 1
Primary bedroom
Bedroom
Features: Built-in Features, En Suite Bathroom, Walk-In Closet(s)
Cooling
Central Air, Ceiling Fan(s), Electric
Appliances
Included: Built-In Gas Range, Built-In Refrigerator, Double Oven, Dishwasher, Gas Cooktop, Disposal, Ice Maker, Microwave, Range, Refrigerator, Some Commercial Grade, Vented Exhaust Fan, Warming Drawer, Wine Cooler
Features
Wet Bar, Built-in Features, Dry Bar, Decorative/Designer Lighting Fixtures, Eat-in Kitchen, Elevator, High Speed Internet, Kitchen Island, Pantry, Smart Home, Cable TV, Walk-In Closet(s), Wired for Sound
Flooring: Hardwood
Has basement: No
Number of fireplaces: 3
Fireplace features: Living Room, Primary Bedroom
Interior area
Total interior livable area: 10,466 sqft
Total spaces: 12
Parking features: Additional Parking
Attached garage spaces: 6
Carport spaces: 6
Features
Levels: Two
Stories: 2
Patio & porch: Covered
Exterior features: Built-in Barbecue, Barbecue, Gas Grill, Lighting, Outdoor Grill, Outdoor Living Area, Private Yard, Sport Court, Fire Pit
Pool features: Heated, In Ground, Pool, Pool/Spa Combo
Fencing: Wrought Iron
Lot
Size: 1.05 Acres
Details
Additional structures: Outdoor Kitchen
Parcel number: 42232692
Special conditions: Standard
Construction
Type & style
Home type: SingleFamily
Architectural style: Contemporary/Modern,Detached
Property subtype: Single Family Residence
"""
)
```
## `ForestSwarm`
The `ForestSwarm` architecture is designed for efficient task assignment by dynamically selecting the most suitable agent from a collection of trees. This is achieved through asynchronous task processing, where agents are chosen based on their relevance to the task at hand. The relevance is determined by calculating the similarity between the system prompts associated with each agent and the keywords present in the task itself. For a more in-depth understanding of how `ForestSwarm` works, please refer to the [official documentation](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/).
### Methods
| Method | Description | Parameters | Return Value |
|--------|-------------|------------|--------------|
| `__init__` | Initialize the ForestSwarm | `trees`: List of Tree objects | None |
| `run` | Execute the ForestSwarm | `task`: Input task for the swarm | Output from the most relevant agent |
### Inputs
| Input | Type | Description |
|-------|------|-------------|
| `trees` | List[Tree] | List of Tree objects, each containing TreeAgent objects |
| `task` | str | The task to be processed by the ForestSwarm |
### Output
The `run` method returns the output from the most relevant agent selected based on the input task.
```python
from swarms import TreeAgent, Tree, ForestSwarm
# Create agents with varying system prompts and dynamically generated distances/keywords
agents_tree1 = [
TreeAgent(
system_prompt="""You are an expert Stock Analysis Agent with deep knowledge of financial markets, technical analysis, and fundamental analysis. Your primary function is to analyze stock performance, market trends, and provide actionable insights. When analyzing stocks:
1. Always start with a brief overview of the current market conditions.
2. Use a combination of technical indicators (e.g., moving averages, RSI, MACD) and fundamental metrics (e.g., P/E ratio, EPS growth, debt-to-equity).
3. Consider both short-term and long-term perspectives in your analysis.
4. Provide clear buy, hold, or sell recommendations with supporting rationale.
5. Highlight potential risks and opportunities specific to each stock or sector.
6. Use bullet points for clarity when listing key points or metrics.
7. If relevant, compare the stock to its peers or sector benchmarks.
Remember to maintain objectivity and base your analysis on factual data. If asked about future performance, always include a disclaimer about market unpredictability. Your goal is to provide comprehensive, accurate, and actionable stock analysis to inform investment decisions.""",
agent_name="Stock Analysis Agent",
),
TreeAgent(
system_prompt="""You are a highly skilled Financial Planning Agent, specializing in personal and corporate financial strategies. Your role is to provide comprehensive financial advice tailored to each client's unique situation. When creating financial plans:
1. Begin by asking key questions about the client's financial goals, current situation, and risk tolerance.
2. Develop a holistic view of the client's finances, including income, expenses, assets, and liabilities.
3. Create detailed, step-by-step action plans to achieve financial goals.
4. Provide specific recommendations for budgeting, saving, and investing.
5. Consider tax implications and suggest tax-efficient strategies.
6. Incorporate risk management and insurance planning into your recommendations.
7. Use charts or tables to illustrate financial projections and scenarios.
8. Regularly suggest reviewing and adjusting the plan as circumstances change.
Always prioritize the client's best interests and adhere to fiduciary standards. Explain complex financial concepts in simple terms, and be prepared to justify your recommendations with data and reasoning.""",
agent_name="Financial Planning Agent",
),
TreeAgent(
agent_name="Retirement Strategy Agent",
system_prompt="""You are a specialized Retirement Strategy Agent, focused on helping individuals and couples plan for a secure and comfortable retirement. Your expertise covers various aspects of retirement planning, including savings strategies, investment allocation, and income generation during retirement. When developing retirement strategies:
1. Start by assessing the client's current age, desired retirement age, and expected lifespan.
2. Calculate retirement savings goals based on desired lifestyle and projected expenses.
3. Analyze current retirement accounts (e.g., 401(k), IRA) and suggest optimization strategies.
4. Provide guidance on asset allocation and rebalancing as retirement approaches.
5. Explain various retirement income sources (e.g., Social Security, pensions, annuities).
6. Discuss healthcare costs and long-term care planning.
7. Offer strategies for tax-efficient withdrawals during retirement.
8. Consider estate planning and legacy goals in your recommendations.
Use Monte Carlo simulations or other statistical tools to illustrate the probability of retirement success. Always emphasize the importance of starting early and the power of compound interest. Be prepared to adjust strategies based on changing market conditions or personal circumstances.""",
),
]
agents_tree2 = [
TreeAgent(
system_prompt="""You are a knowledgeable Tax Filing Agent, specializing in personal and business tax preparation and strategy. Your role is to ensure accurate tax filings while maximizing legitimate deductions and credits. When assisting with tax matters:
1. Start by gathering all necessary financial information and documents.
2. Stay up-to-date with the latest tax laws and regulations, including state-specific rules.
3. Identify all applicable deductions and credits based on the client's situation.
4. Provide step-by-step guidance for completing tax forms accurately.
5. Explain tax implications of various financial decisions.
6. Offer strategies for tax-efficient investing and income management.
7. Assist with estimated tax payments for self-employed individuals or businesses.
8. Advise on record-keeping practices for tax purposes.
Always prioritize compliance with tax laws while ethically minimizing tax liability. Be prepared to explain complex tax concepts in simple terms and provide rationale for your recommendations. If a situation is beyond your expertise, advise consulting a certified tax professional or IRS resources.""",
agent_name="Tax Filing Agent",
),
TreeAgent(
system_prompt="""You are a sophisticated Investment Strategy Agent, adept at creating and managing investment portfolios to meet diverse financial goals. Your expertise covers various asset classes, market analysis, and risk management techniques. When developing investment strategies:
1. Begin by assessing the client's investment goals, time horizon, and risk tolerance.
2. Provide a comprehensive overview of different asset classes and their risk-return profiles.
3. Create diversified portfolio recommendations based on modern portfolio theory.
4. Explain the benefits and risks of various investment vehicles (e.g., stocks, bonds, ETFs, mutual funds).
5. Incorporate both passive and active investment strategies as appropriate.
6. Discuss the importance of regular portfolio rebalancing and provide a rebalancing strategy.
7. Consider tax implications of investment decisions and suggest tax-efficient strategies.
8. Provide ongoing market analysis and suggest portfolio adjustments as needed.
Use historical data and forward-looking projections to illustrate potential outcomes. Always emphasize the importance of long-term investing and the risks of market timing. Be prepared to explain complex investment concepts in clear, accessible language.""",
agent_name="Investment Strategy Agent",
),
TreeAgent(
system_prompt="""You are a specialized ROTH IRA Agent, focusing on the intricacies of Roth Individual Retirement Accounts. Your role is to provide expert guidance on Roth IRA rules, benefits, and strategies to maximize their value for retirement planning. When advising on Roth IRAs:
1. Explain the fundamental differences between traditional and Roth IRAs.
2. Clarify Roth IRA contribution limits and income eligibility requirements.
3. Discuss the tax advantages of Roth IRAs, including tax-free growth and withdrawals.
4. Provide guidance on Roth IRA conversion strategies and their tax implications.
5. Explain the five-year rule and how it affects Roth IRA withdrawals.
6. Offer strategies for maximizing Roth IRA contributions, such as the backdoor Roth IRA method.
7. Discuss how Roth IRAs fit into overall retirement and estate planning strategies.
8. Provide insights on investment choices within a Roth IRA to maximize tax-free growth.
Always stay current with IRS regulations regarding Roth IRAs. Be prepared to provide numerical examples to illustrate the long-term benefits of Roth IRAs. Emphasize the importance of considering individual financial situations when making Roth IRA decisions.""",
agent_name="ROTH IRA Agent",
),
]
# Create trees
tree1 = Tree(tree_name="Financial Tree", agents=agents_tree1)
tree2 = Tree(tree_name="Investment Tree", agents=agents_tree2)
# Create the ForestSwarm
multi_agent_structure = ForestSwarm(trees=[tree1, tree2])
# Run a task
task = "What are the best platforms to do our taxes on"
output = multi_agent_structure.run(task)
print(output)
```
## `SwarmRouter`
The `SwarmRouter` class is a flexible routing system designed to manage different types of swarms for task execution. It provides a unified interface to interact with various swarm types, including `AgentRearrange`, `MixtureOfAgents`, `SpreadSheetSwarm`, `SequentialWorkflow`, and `ConcurrentWorkflow`. We will be continuously adding more and more swarm architectures here as we progress with new architectures.
#### Attributes:
- `name` (str): Name of the SwarmRouter instance.
- `description` (str): Description of the SwarmRouter instance.
- `max_loops` (int): Maximum number of loops to perform.
- `agents` (List[Agent]): List of Agent objects to be used in the swarm.
- `swarm_type` (SwarmType): Type of swarm to be used.
- `swarm` (Union[AgentRearrange, MixtureOfAgents, SpreadSheetSwarm, SequentialWorkflow, ConcurrentWorkflow]): Instantiated swarm object.
- `logs` (List[SwarmLog]): List of log entries captured during operations.
#### Methods:
- `__init__(self, name: str, description: str, max_loops: int, agents: List[Agent], swarm_type: SwarmType, *args, **kwargs)`: Initialize the SwarmRouter.
- `_create_swarm(self, *args, **kwargs)`: Create and return the specified swarm type.
- `_log(self, level: str, message: str, task: str, metadata: Dict[str, Any])`: Create a log entry and add it to the logs list.
- `run(self, task: str, *args, **kwargs)`: Run the specified task on the selected swarm.
- `get_logs(self)`: Retrieve all logged entries.
```python
import os
from dotenv import load_dotenv
from swarms import Agent
from swarm_models import OpenAIChat
from swarms.structs.swarm_router import SwarmRouter, SwarmType
load_dotenv()
# Get the OpenAI API key from the environment variable
api_key = os.getenv("GROQ_API_KEY")
# Model
model = OpenAIChat(
openai_api_base="https://api.groq.com/openai/v1",
openai_api_key=api_key,
model_name="llama-3.1-70b-versatile",
temperature=0.1,
)
# Define specialized system prompts for each agent
DATA_EXTRACTOR_PROMPT = """You are a highly specialized private equity agent focused on data extraction from various documents. Your expertise includes:
1. Extracting key financial metrics (revenue, EBITDA, growth rates, etc.) from financial statements and reports
2. Identifying and extracting important contract terms from legal documents
3. Pulling out relevant market data from industry reports and analyses
4. Extracting operational KPIs from management presentations and internal reports
5. Identifying and extracting key personnel information from organizational charts and bios
Provide accurate, structured data extracted from various document types to support investment analysis."""
SUMMARIZER_PROMPT = """You are an expert private equity agent specializing in summarizing complex documents. Your core competencies include:
1. Distilling lengthy financial reports into concise executive summaries
2. Summarizing legal documents, highlighting key terms and potential risks
3. Condensing industry reports to capture essential market trends and competitive dynamics
4. Summarizing management presentations to highlight key strategic initiatives and projections
5. Creating brief overviews of technical documents, emphasizing critical points for non-technical stakeholders
Deliver clear, concise summaries that capture the essence of various documents while highlighting information crucial for investment decisions."""
FINANCIAL_ANALYST_PROMPT = """You are a specialized private equity agent focused on financial analysis. Your key responsibilities include:
1. Analyzing historical financial statements to identify trends and potential issues
2. Evaluating the quality of earnings and potential adjustments to EBITDA
3. Assessing working capital requirements and cash flow dynamics
4. Analyzing capital structure and debt capacity
5. Evaluating financial projections and underlying assumptions
Provide thorough, insightful financial analysis to inform investment decisions and valuation."""
MARKET_ANALYST_PROMPT = """You are a highly skilled private equity agent specializing in market analysis. Your expertise covers:
1. Analyzing industry trends, growth drivers, and potential disruptors
2. Evaluating competitive landscape and market positioning
3. Assessing market size, segmentation, and growth potential
4. Analyzing customer dynamics, including concentration and loyalty
5. Identifying potential regulatory or macroeconomic impacts on the market
Deliver comprehensive market analysis to assess the attractiveness and risks of potential investments."""
OPERATIONAL_ANALYST_PROMPT = """You are an expert private equity agent focused on operational analysis. Your core competencies include:
1. Evaluating operational efficiency and identifying improvement opportunities
2. Analyzing supply chain and procurement processes
3. Assessing sales and marketing effectiveness
4. Evaluating IT systems and digital capabilities
5. Identifying potential synergies in merger or add-on acquisition scenarios
Provide detailed operational analysis to uncover value creation opportunities and potential risks."""
# Initialize specialized agents
data_extractor_agent = Agent(
agent_name="Data-Extractor",
system_prompt=DATA_EXTRACTOR_PROMPT,
llm=model,
max_loops=1,
autosave=True,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="data_extractor_agent.json",
user_name="pe_firm",
retry_attempts=1,
context_length=200000,
output_type="string",
)
summarizer_agent = Agent(
agent_name="Document-Summarizer",
system_prompt=SUMMARIZER_PROMPT,
llm=model,
max_loops=1,
autosave=True,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="summarizer_agent.json",
user_name="pe_firm",
retry_attempts=1,
context_length=200000,
output_type="string",
)
financial_analyst_agent = Agent(
agent_name="Financial-Analyst",
system_prompt=FINANCIAL_ANALYST_PROMPT,
llm=model,
max_loops=1,
autosave=True,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="financial_analyst_agent.json",
user_name="pe_firm",
retry_attempts=1,
context_length=200000,
output_type="string",
)
market_analyst_agent = Agent(
agent_name="Market-Analyst",
system_prompt=MARKET_ANALYST_PROMPT,
llm=model,
max_loops=1,
autosave=True,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="market_analyst_agent.json",
user_name="pe_firm",
retry_attempts=1,
context_length=200000,
output_type="string",
)
operational_analyst_agent = Agent(
agent_name="Operational-Analyst",
system_prompt=OPERATIONAL_ANALYST_PROMPT,
llm=model,
max_loops=1,
autosave=True,
verbose=True,
dynamic_temperature_enabled=True,
saved_state_path="operational_analyst_agent.json",
user_name="pe_firm",
retry_attempts=1,
context_length=200000,
output_type="string",
)
# Initialize the SwarmRouter
router = SwarmRouter(
name="pe-document-analysis-swarm",
description="Analyze documents for private equity due diligence and investment decision-making",
max_loops=1,
agents=[
data_extractor_agent,
summarizer_agent,
financial_analyst_agent,
market_analyst_agent,
operational_analyst_agent,
],
swarm_type="ConcurrentWorkflow", # or "SequentialWorkflow" or "ConcurrentWorkflow" or
)
# Example usage
if __name__ == "__main__":
# Run a comprehensive private equity document analysis task
result = router.run(
"Where is the best place to find template term sheets for series A startups. Provide links and references"
)
print(result)
# Retrieve and print logs
for log in router.get_logs():
print(f"{log.timestamp} - {log.level}: {log.message}")
```
### Changing Swarm Types
You can create multiple SwarmRouter instances with different swarm types:
```python
sequential_router = SwarmRouter(
name="SequentialRouter",
agents=[
data_extractor_agent,
summarizer_agent,
financial_analyst_agent,
market_analyst_agent,
operational_analyst_agent,
],
swarm_type=SwarmType.SequentialWorkflow
)
concurrent_router = SwarmRouter(
name="ConcurrentRouter",
agents=[
data_extractor_agent,
summarizer_agent,
financial_analyst_agent,
market_analyst_agent,
operational_analyst_agent,
],
swarm_type=SwarmType.ConcurrentWorkflow
)
```
### AgentRearrange
Use Case: Optimizing agent order for complex multi-step tasks.
```python
rearrange_router = SwarmRouter(
name="TaskOptimizer",
description="Optimize agent order for multi-step tasks",
max_loops=3,
agents=[
data_extractor_agent,
summarizer_agent,
financial_analyst_agent,
market_analyst_agent,
operational_analyst_agent,
],
swarm_type=SwarmType.AgentRearrange,
flow = f"{data_extractor.name} -> {analyzer.name} -> {summarizer.name}"
)
result = rearrange_router.run("Analyze and summarize the quarterly financial report")
```
### MixtureOfAgents
Use Case: Combining diverse expert agents for comprehensive analysis.
```python
mixture_router = SwarmRouter(
name="ExpertPanel",
description="Combine insights from various expert agents",
max_loops=1,
agents=[
data_extractor_agent,
summarizer_agent,
financial_analyst_agent,
market_analyst_agent,
operational_analyst_agent,
],
swarm_type=SwarmType.MixtureOfAgents
)
result = mixture_router.run("Evaluate the potential acquisition of TechStartup Inc.")
```
-------
## GroupChat
A production-grade multi-agent system enabling sophisticated group conversations between AI agents with customizable speaking patterns, parallel processing capabilities, and comprehensive conversation tracking.
```python
import os
from dotenv import load_dotenv
from swarm_models import OpenAIChat
from swarms import Agent, GroupChat, expertise_based
if __name__ == "__main__":
load_dotenv()
# Get the OpenAI API key from the environment variable
api_key = os.getenv("OPENAI_API_KEY")
# Create an instance of the OpenAIChat class
model = OpenAIChat(
openai_api_key=api_key,
model_name="gpt-4o-mini",
temperature=0.1,
)
# Example agents
agent1 = Agent(
agent_name="Financial-Analysis-Agent",
system_prompt="You are a financial analyst specializing in investment strategies.",
llm=model,
max_loops=1,
autosave=False,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
user_name="swarms_corp",
retry_attempts=1,
context_length=200000,
output_type="string",
streaming_on=False,
)
agent2 = Agent(
agent_name="Tax-Adviser-Agent",
system_prompt="You are a tax adviser who provides clear and concise guidance on tax-related queries.",
llm=model,
max_loops=1,
autosave=False,
dashboard=False,
verbose=True,
dynamic_temperature_enabled=True,
user_name="swarms_corp",
retry_attempts=1,
context_length=200000,
output_type="string",
streaming_on=False,
)
agents = [agent1, agent2]
chat = GroupChat(
name="Investment Advisory",
description="Financial and tax analysis group",
agents=agents,
speaker_fn=expertise_based,
)
history = chat.run(
"How to optimize tax strategy for investments?"
)
print(history.model_dump_json(indent=2))
```
----------
## Onboarding Session
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 meticlously crafted for extreme use-ability 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 3 most important are `structs`, `models`, and `agents`.
```sh
βββ __init__.py
βββ agents
βββ artifacts
βββ memory
βββ schemas
βββ models -> swarm_models
βββ prompts
βββ structs
βββ telemetry
βββ tools
βββ utils
βββ workers
```
----
## π«Ά 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)
Swarms is an open-source project, and contributions are VERY welcome. If you want to contribute, you can create new features, fix bugs, or improve the infrastructure. Please refer to the [CONTRIBUTING.md](https://github.com/kyegomez/swarms/blob/master/CONTRIBUTING.md) and our [contributing board](https://github.com/users/kyegomez/projects/1) to participate in Roadmap discussions!
----
## Accelerate Backlog
Accelerate Bugs, Features, and Demos to implement by supporting us here:
<a href="https://polar.sh/kyegomez"><img src="https://polar.sh/embed/fund-our-backlog.svg?org=kyegomez" /></a>
## Community
Join our growing community around the world, for real-time support, ideas, and discussions on Swarms π
- View our official [Blog](https://docs.swarms.world)
- Chat live with us on [Discord](https://discord.gg/kS3rwKs3ZC)
- Follow us on [Twitter](https://twitter.com/kyegomez)
- Connect with us on [LinkedIn](https://www.linkedin.com/company/the-swarm-corporation)
- Visit us on [YouTube](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ)
- [Join the Swarms community on Discord!](https://discord.gg/AJazBmhKnr)
- Join our Swarms Community Gathering every Thursday at 1pm NYC Time to unlock the potential of autonomous agents in automating your daily tasks [Sign up here](https://lu.ma/5p2jnc2v)
# License
GNU AFFERO GENERAL PUBLIC LICENSE
Raw data
{
"_id": null,
"home_page": "https://github.com/kyegomez/swarms",
"name": "swarms",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.10",
"maintainer_email": null,
"keywords": "artificial intelligence, deep learning, optimizers, Prompt Engineering, swarms, agents, llms, transformers, multi-agent, swarms of agents, Enterprise-Grade Agents, Production-Grade Agents, Agents, Multi-Grade-Agents, Swarms, Transformers, LLMs, Prompt Engineering, Agents, Generative Agents, Generative AI, Agent Marketplace, Agent Store, quant, finance, algorithmic trading, portfolio optimization, risk management, financial modeling, machine learning for finance, natural language processing for finance",
"author": "Kye Gomez",
"author_email": "kye@apac.ai",
"download_url": "https://files.pythonhosted.org/packages/ee/0c/ccf73fa998048a726f7a3707c6bb1678317b9f96eb4280ba1a211172ad1e/swarms-6.7.9.tar.gz",
"platform": null,
"description": "<div align=\"center\">\n <a href=\"https://swarms.world\">\n <img src=\"https://github.com/kyegomez/swarms/blob/master/images/swarmslogobanner.png\" style=\"margin: 15px; max-width: 300px\" width=\"50%\" alt=\"Logo\">\n </a>\n</div>\n<p align=\"center\">\n <em>The Enterprise-Grade Production-Ready Multi-Agent Orchestration Framework </em>\n</p>\n\n<p align=\"center\">\n <a href=\"https://pypi.org/project/swarms/\" target=\"_blank\">\n <img alt=\"Python\" src=\"https://img.shields.io/badge/python-3670A0?style=for-the-badge&logo=python&logoColor=ffdd54\" />\n <img alt=\"Version\" src=\"https://img.shields.io/pypi/v/swarms?style=for-the-badge&color=3670A0\">\n </a>\n</p>\n<p align=\"center\">\n<a href=\"https://twitter.com/swarms_corp/\">\ud83d\udc26 Twitter</a>\n<span> \u2022 </span>\n<a href=\"https://discord.gg/agora-999382051935506503\">\ud83d\udce2 Discord</a>\n<span> \u2022 </span>\n<a href=\"https://swarms.world\">Swarms Platform</a>\n<span> \u2022 </span>\n<a href=\"https://docs.swarms.world\">\ud83d\udcd9 Documentation</a>\n</p>\n\n\n\n\n[![Join our Discord](https://img.shields.io/badge/Discord-Join%20our%20server-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/agora-999382051935506503) [![Subscribe on YouTube](https://img.shields.io/badge/YouTube-Subscribe-red?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/@kyegomez3242) [![Connect on LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/kye-g-38759a207/) [![Follow on X.com](https://img.shields.io/badge/X.com-Follow-1DA1F2?style=for-the-badge&logo=x&logoColor=white)](https://x.com/kyegomezb)\n\n\n\n[![GitHub issues](https://img.shields.io/github/issues/kyegomez/swarms)](https://github.com/kyegomez/swarms/issues) [![GitHub forks](https://img.shields.io/github/forks/kyegomez/swarms)](https://github.com/kyegomez/swarms/network) [![GitHub stars](https://img.shields.io/github/stars/kyegomez/swarms)](https://github.com/kyegomez/swarms/stargazers) [![GitHub license](https://img.shields.io/github/license/kyegomez/swarms)](https://github.com/kyegomez/swarms/blob/main/LICENSE)[![GitHub star chart](https://img.shields.io/github/stars/kyegomez/swarms?style=social)](https://star-history.com/#kyegomez/swarms)[![Dependency Status](https://img.shields.io/librariesio/github/kyegomez/swarms)](https://libraries.io/github/kyegomez/swarms) [![Downloads](https://static.pepy.tech/badge/swarms/month)](https://pepy.tech/project/swarms)\n\n[![Share on Twitter](https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social&label=Share%20%40kyegomez/swarms)](https://twitter.com/intent/tweet?text=Check%20out%20this%20amazing%20AI%20project:%20&url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms) [![Share on Facebook](https://img.shields.io/badge/Share-%20facebook-blue)](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms) [![Share on LinkedIn](https://img.shields.io/badge/Share-%20linkedin-blue)](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&title=&summary=&source=)\n\n[![Share on Reddit](https://img.shields.io/badge/-Share%20on%20Reddit-orange)](https://www.reddit.com/submit?url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&title=Swarms%20-%20the%20future%20of%20AI) [![Share on Hacker News](https://img.shields.io/badge/-Share%20on%20Hacker%20News-orange)](https://news.ycombinator.com/submitlink?u=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&t=Swarms%20-%20the%20future%20of%20AI) [![Share on Pinterest](https://img.shields.io/badge/-Share%20on%20Pinterest-red)](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms&media=https%3A%2F%2Fexample.com%2Fimage.jpg&description=Swarms%20-%20the%20future%20of%20AI) [![Share on WhatsApp](https://img.shields.io/badge/-Share%20on%20WhatsApp-green)](https://api.whatsapp.com/send?text=Check%20out%20Swarms%20-%20the%20future%20of%20AI%20%23swarms%20%23AI%0A%0Ahttps%3A%2F%2Fgithub.com%2Fkyegomez%2Fswarms)\n\n\n## \u2728 Features\n\n| Category | Features | Benefits |\n|----------|----------|-----------|\n| \ud83c\udfe2 Enterprise Architecture | \u2022 Production-Ready Infrastructure<br>\u2022 High Reliability Systems<br>\u2022 Modular Design<br>\u2022 Comprehensive Logging | \u2022 Reduced downtime<br>\u2022 Easier maintenance<br>\u2022 Better debugging<br>\u2022 Enhanced monitoring |\n| \ud83e\udd16 Agent Orchestration | \u2022 Hierarchical Swarms<br>\u2022 Parallel Processing<br>\u2022 Sequential Workflows<br>\u2022 Graph-based Workflows<br>\u2022 Dynamic Agent Rearrangement | \u2022 Complex task handling<br>\u2022 Improved performance<br>\u2022 Flexible workflows<br>\u2022 Optimized execution |\n| \ud83d\udd04 Integration Capabilities | \u2022 Multi-Model Support<br>\u2022 Custom Agent Creation<br>\u2022 Extensive Tool Library<br>\u2022 Multiple Memory Systems | \u2022 Provider flexibility<br>\u2022 Custom solutions<br>\u2022 Extended functionality<br>\u2022 Enhanced memory management |\n| \ud83d\udcc8 Scalability | \u2022 Concurrent Processing<br>\u2022 Resource Management<br>\u2022 Load Balancing<br>\u2022 Horizontal Scaling | \u2022 Higher throughput<br>\u2022 Efficient resource use<br>\u2022 Better performance<br>\u2022 Easy scaling |\n| \ud83d\udee0\ufe0f Developer Tools | \u2022 Simple API<br>\u2022 Extensive Documentation<br>\u2022 Active Community<br>\u2022 CLI Tools | \u2022 Faster development<br>\u2022 Easy learning curve<br>\u2022 Community support<br>\u2022 Quick deployment |\n| \ud83d\udd10 Security Features | \u2022 Error Handling<br>\u2022 Rate Limiting<br>\u2022 Monitoring Integration<br>\u2022 Audit Logging | \u2022 Improved reliability<br>\u2022 API protection<br>\u2022 Better monitoring<br>\u2022 Enhanced tracking |\n| \ud83d\udcca Advanced Features | \u2022 SpreadsheetSwarm<br>\u2022 Group Chat<br>\u2022 Agent Registry<br>\u2022 Mixture of Agents | \u2022 Mass agent management<br>\u2022 Collaborative AI<br>\u2022 Centralized control<br>\u2022 Complex solutions |\n| \ud83d\udd0c Provider Support | \u2022 OpenAI<br>\u2022 Anthropic<br>\u2022 ChromaDB<br>\u2022 Custom Providers | \u2022 Provider flexibility<br>\u2022 Storage options<br>\u2022 Custom integration<br>\u2022 Vendor independence |\n| \ud83d\udcaa Production Features | \u2022 Automatic Retries<br>\u2022 Async Support<br>\u2022 Environment Management<br>\u2022 Type Safety | \u2022 Better reliability<br>\u2022 Improved performance<br>\u2022 Easy configuration<br>\u2022 Safer code |\n| \ud83c\udfaf Use Case Support | \u2022 Task-Specific Agents<br>\u2022 Custom Workflows<br>\u2022 Industry Solutions<br>\u2022 Extensible Framework | \u2022 Quick deployment<br>\u2022 Flexible solutions<br>\u2022 Industry readiness<br>\u2022 Easy customization |\n\n\n----\n\n## Requirements\n- `python3.10` or above!\n- `$ pip install -U swarms` And, don't forget to install swarms!\n- `.env` file with API keys from your providers like `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`\n- Set an `.env` Variable with your desired workspace dir: `WORKSPACE_DIR=\"agent_workspace\"` or do it in your terminal with `export WORKSPACE_DIR=\"agent_workspace\"`\n- Finally, `swarms onboarding` to get you started.\n\n## Guides and Walkthroughs\nRefer to our documentation for production grade implementation details.\n\n\n| Section | Links |\n|----------------------|--------------------------------------------------------------------------------------------|\n| Installation | [Installation](https://docs.swarms.world/en/latest/swarms/install/install/) |\n| Quickstart | [Get Started](https://docs.swarms.world/en/latest/swarms/install/quickstart/) |\n| Agent Internal Mechanisms | [Agent Architecture](https://docs.swarms.world/en/latest/swarms/framework/agents_explained/) |\n| Agent API | [Agent API](https://docs.swarms.world/en/latest/swarms/structs/agent/) |\n| Integrating External Agents Griptape, Autogen, etc | [Integrating External APIs](https://docs.swarms.world/en/latest/swarms/agents/external_party_agents/) |\n| Creating Agents from YAML | [Creating Agents from YAML](https://docs.swarms.world/en/latest/swarms/agents/create_agents_yaml/) |\n| Why You Need Swarms | [Why MultiAgent Collaboration is Necessary](https://docs.swarms.world/en/latest/swarms/concept/why/) |\n| Swarm Architectures Analysis | [Swarm Architectures](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/) |\n| Choosing the Right Swarm for Your Business Problem\u00b6 | [CLICK HERE](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/) |\n| AgentRearrange Docs| [CLICK HERE](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/) |\n\n\n## Install \ud83d\udcbb\nInstall the following packages with copy and paste\n\n```bash\n$ pip3 install -U swarms swarm-models swarms-memory\n```\n\n\n## Onboarding\n\nNow that you have downloaded swarms with `pip3 install -U swarms`, we get access to the `CLI`. Get Onboarded with CLI Now with:\n\n```bash\nswarms onboarding\n```\n\nYou can also run this command for help:\n\n```bash\nswarms help\n```\n\nFor more documentation on the CLI [CLICK HERE](https://docs.swarms.world/en/latest/swarms/cli/main/)\n\n---\n\n# Usage Examples \ud83e\udd16\nHere are some example scripts to get you started. For more comprehensive documentation, visit our [docs](https://docs.swarms.world/en/latest/).\n\n| Example Name | Description | Type of Examples | Link |\n| --- | --- | --- | --- |\n| Swarms Examples | A collection of simple examples to demonstrate Swarms capabilities. | Basic Usage | [https://github.com/The-Swarm-Corporation/swarms-examples?tab=readme-ov-file](https://github.com/The-Swarm-Corporation/swarms-examples?tab=readme-ov-file) |\n| Cookbook | A comprehensive guide with recipes for various use cases and scenarios. | Advanced Usage | [https://github.com/The-Swarm-Corporation/Cookbook](https://github.com/The-Swarm-Corporation/Cookbook) |\n\n\n\n\n---\n\n## `Agent` Class\nThe `Agent` class is a fundamental component of the Swarms framework, designed to execute tasks autonomously. It fuses llms, tools and long-term memory capabilities to create a full stack agent. The `Agent` class is highly customizable, allowing for fine-grained control over its behavior and interactions.\n\n\n### `run` Method\nThe `run` method is the primary entry point for executing tasks with an `Agent` instance. It accepts a task string as the main input task and processes it according to the agent's configuration. And, it can also accept an `img` parameter such as `img=\"image_filepath.png` to process images if you have a VLM attached such as `GPT4VisionAPI`\n\n\n\n## Simple Example\n\n```python\nfrom swarms import Agent\n\nagent = Agent(\n agent_name=\"Stock-Analysis-Agent\",\n model_name=\"gpt-4o-mini\",\n max_loops=\"auto\",\n interactive=True,\n streaming_on=True,\n)\n\nagent.run(\"What is the current market trend for tech stocks?\")\n\n```\n\n### Settings and Customization\nThe `Agent` class offers a range of settings to tailor its behavior to specific needs. Some key settings include:\n\n| Setting | Description | Default Value |\n| --- | --- | --- |\n| `agent_name` | The name of the agent. | \"DefaultAgent\" |\n| `system_prompt` | The system prompt to use for the agent. | \"Default system prompt.\" |\n| `llm` | The language model to use for processing tasks. | `OpenAIChat` instance |\n| `max_loops` | The maximum number of loops to execute for a task. | 1 |\n| `autosave` | Enables or disables autosaving of the agent's state. | False |\n| `dashboard` | Enables or disables the dashboard for the agent. | False |\n| `verbose` | Controls the verbosity of the agent's output. | False |\n| `dynamic_temperature_enabled` | Enables or disables dynamic temperature adjustment for the language model. | False |\n| `saved_state_path` | The path to save the agent's state. | \"agent_state.json\" |\n| `user_name` | The username associated with the agent. | \"default_user\" |\n| `retry_attempts` | The number of retry attempts for failed tasks. | 1 |\n| `context_length` | The maximum length of the context to consider for tasks. | 200000 |\n| `return_step_meta` | Controls whether to return step metadata in the output. | False |\n| `output_type` | The type of output to return (e.g., \"json\", \"string\"). | \"string\" |\n\n\n```python\nimport os\nfrom swarms import Agent\n\nfrom swarms.prompts.finance_agent_sys_prompt import (\n FINANCIAL_AGENT_SYS_PROMPT,\n)\n# Initialize the agent\nagent = Agent(\n agent_name=\"Financial-Analysis-Agent\",\n system_prompt=FINANCIAL_AGENT_SYS_PROMPT,\n model_name=\"gpt-4o-mini\",\n max_loops=1,\n autosave=True,\n dashboard=False,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"finance_agent.json\",\n user_name=\"swarms_corp\",\n retry_attempts=1,\n context_length=200000,\n return_step_meta=False,\n output_type=\"string\",\n streaming_on=False,\n)\n\n\nagent.run(\n \"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria\"\n)\n\n```\n-----\n\n### Integrating RAG with Swarms for Enhanced Long-Term Memory\n`Agent` equipped with quasi-infinite long term memory using RAG (Relational Agent Graph) for advanced document understanding, analysis, and retrieval capabilities.\n\n**Mermaid Diagram for RAG Integration**\n```mermaid\ngraph TD\n A[Initialize Agent with RAG] --> B[Receive Task]\n B --> C[Query Long-Term Memory]\n C --> D[Process Task with Context]\n D --> E[Generate Response]\n E --> F[Update Long-Term Memory]\n F --> G[Return Output]\n```\n\n```python\nfrom swarms import Agent\nfrom swarms.prompts.finance_agent_sys_prompt import (\n FINANCIAL_AGENT_SYS_PROMPT,\n)\nimport os\n\nfrom swarms_memory import ChromaDB\n\n# Initialize the ChromaDB client for long-term memory management\nchromadb = ChromaDB(\n metric=\"cosine\", # Metric for similarity measurement\n output_dir=\"finance_agent_rag\", # Directory for storing RAG data\n # docs_folder=\"artifacts\", # Uncomment and specify the folder containing your documents\n)\n\n# Initialize the agent with RAG capabilities\nagent = Agent(\n agent_name=\"Financial-Analysis-Agent\",\n system_prompt=FINANCIAL_AGENT_SYS_PROMPT,\n agent_description=\"Agent creates a comprehensive financial analysis\",\n model_name=\"gpt-4o-mini\",\n max_loops=\"auto\", # Auto-adjusts loops based on task complexity\n autosave=True, # Automatically saves agent state\n dashboard=False, # Disables dashboard for this example\n verbose=True, # Enables verbose mode for detailed output\n streaming_on=True, # Enables streaming for real-time processing\n dynamic_temperature_enabled=True, # Dynamically adjusts temperature for optimal performance\n saved_state_path=\"finance_agent.json\", # Path to save agent state\n user_name=\"swarms_corp\", # User name for the agent\n retry_attempts=3, # Number of retry attempts for failed tasks\n context_length=200000, # Maximum length of the context to consider\n long_term_memory=chromadb, # Integrates ChromaDB for long-term memory management\n return_step_meta=False,\n output_type=\"string\",\n)\n\n# Run the agent with a sample task\nagent.run(\n \"What are the components of a startups stock incentive equity plan\"\n)\n```\n\n\n-------\n\n### Misc Agent Settings\nWe provide vast array of features to save agent states using json, yaml, toml, upload pdfs, batched jobs, and much more!\n\n\n**Method Table**\n\n| Method | Description |\n| --- | --- |\n| `to_dict()` | Converts the agent object to a dictionary. |\n| `to_toml()` | Converts the agent object to a TOML string. |\n| `model_dump_json()` | Dumps the model to a JSON file. |\n| `model_dump_yaml()` | Dumps the model to a YAML file. |\n| `ingest_docs()` | Ingests documents into the agent's knowledge base. |\n| `receive_message()` | Receives a message from a user and processes it. |\n| `send_agent_message()` | Sends a message from the agent to a user. |\n| `filtered_run()` | Runs the agent with a filtered system prompt. |\n| `bulk_run()` | Runs the agent with multiple system prompts. |\n| `add_memory()` | Adds a memory to the agent. |\n| `check_available_tokens()` | Checks the number of available tokens for the agent. |\n| `tokens_checks()` | Performs token checks for the agent. |\n| `print_dashboard()` | Prints the dashboard of the agent. |\n| `get_docs_from_doc_folders()` | Fetches all the documents from the doc folders. |\n| `activate_agentops()` | Activates agent operations. |\n| `check_end_session_agentops()` | Checks the end of the session for agent operations. |\n\n\n\n```python\n# # Convert the agent object to a dictionary\nprint(agent.to_dict())\nprint(agent.to_toml())\nprint(agent.model_dump_json())\nprint(agent.model_dump_yaml())\n\n# Ingest documents into the agent's knowledge base\nagent.ingest_docs(\"your_pdf_path.pdf\")\n\n# Receive a message from a user and process it\nagent.receive_message(name=\"agent_name\", message=\"message\")\n\n# Send a message from the agent to a user\nagent.send_agent_message(agent_name=\"agent_name\", message=\"message\")\n\n# Ingest multiple documents into the agent's knowledge base\nagent.ingest_docs(\"your_pdf_path.pdf\", \"your_csv_path.csv\")\n\n# Run the agent with a filtered system prompt\nagent.filtered_run(\n \"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria?\"\n)\n\n# Run the agent with multiple system prompts\nagent.bulk_run(\n [\n \"How can I establish a ROTH IRA to buy stocks and get a tax break? What are the criteria?\",\n \"Another system prompt\",\n ]\n)\n\n# Add a memory to the agent\nagent.add_memory(\"Add a memory to the agent\")\n\n# Check the number of available tokens for the agent\nagent.check_available_tokens()\n\n# Perform token checks for the agent\nagent.tokens_checks()\n\n# Print the dashboard of the agent\nagent.print_dashboard()\n\n# Fetch all the documents from the doc folders\nagent.get_docs_from_doc_folders()\n\n# Activate agent ops\nagent.activate_agentops()\nagent.check_end_session_agentops()\n\n# Dump the model to a JSON file\nagent.model_dump_json()\nprint(agent.to_toml())\n\n```\n\n\n\n### `Agent`with Pydantic BaseModel as Output Type\nThe following is an example of an agent that intakes a pydantic basemodel and outputs it at the same time:\n\n```python\nfrom pydantic import BaseModel, Field\nfrom swarms import Agent\n\n\n# Initialize the schema for the person's information\nclass Schema(BaseModel):\n name: str = Field(..., title=\"Name of the person\")\n agent: int = Field(..., title=\"Age of the person\")\n is_student: bool = Field(..., title=\"Whether the person is a student\")\n courses: list[str] = Field(\n ..., title=\"List of courses the person is taking\"\n )\n\n\n# Convert the schema to a JSON string\ntool_schema = Schema(\n name=\"Tool Name\",\n agent=1,\n is_student=True,\n courses=[\"Course1\", \"Course2\"],\n)\n\n# Define the task to generate a person's information\ntask = \"Generate a person's information based on the following schema:\"\n\n# Initialize the agent\nagent = Agent(\n agent_name=\"Person Information Generator\",\n system_prompt=(\n \"Generate a person's information based on the following schema:\"\n ),\n # Set the tool schema to the JSON string -- this is the key difference\n tool_schema=tool_schema,\n model_name=\"gpt-4o\",\n max_loops=3,\n autosave=True,\n dashboard=False,\n streaming_on=True,\n verbose=True,\n interactive=True,\n # Set the output type to the tool schema which is a BaseModel\n output_type=tool_schema, # or dict, or str\n metadata_output_type=\"json\",\n # List of schemas that the agent can handle\n list_base_models=[tool_schema],\n function_calling_format_type=\"OpenAI\",\n function_calling_type=\"json\", # or soon yaml\n)\n\n# Run the agent to generate the person's information\ngenerated_data = agent.run(task)\n\n# Print the generated data\nprint(f\"Generated data: {generated_data}\")\n\n\n```\n\n### Multi Modal Autonomous Agent\nRun the agent with multiple modalities useful for various real-world tasks in manufacturing, logistics, and health.\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom swarms import Agent\n\nfrom swarm_models import GPT4VisionAPI\n\n# Load the environment variables\nload_dotenv()\n\n\n# Initialize the language model\nllm = GPT4VisionAPI(\n openai_api_key=os.environ.get(\"OPENAI_API_KEY\"),\n max_tokens=500,\n)\n\n# Initialize the task\ntask = (\n \"Analyze this image of an assembly line and identify any issues such as\"\n \" misaligned parts, defects, or deviations from the standard assembly\"\n \" process. IF there is anything unsafe in the image, explain why it is\"\n \" unsafe and how it could be improved.\"\n)\nimg = \"assembly_line.jpg\"\n\n## Initialize the workflow\nagent = Agent(\n agent_name = \"Multi-ModalAgent\",\n llm=llm, \n max_loops=\"auto\", \n autosave=True, \n dashboard=True, \n multi_modal=True\n)\n\n# Run the workflow on a task\nagent.run(task, img)\n```\n----\n\n\n### Local Agent `ToolAgent`\nToolAgent is an fully local agent that can use tools through JSON function calling. It intakes any open source model from huggingface and is extremely modular and plug in and play. We need help adding general support to all models soon.\n\n\n```python\nfrom pydantic import BaseModel, Field\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nfrom swarms import ToolAgent\nfrom swarms.tools.json_utils import base_model_to_json\n\n# Load the pre-trained model and tokenizer\nmodel = AutoModelForCausalLM.from_pretrained(\n \"databricks/dolly-v2-12b\",\n load_in_4bit=True,\n device_map=\"auto\",\n)\ntokenizer = AutoTokenizer.from_pretrained(\"databricks/dolly-v2-12b\")\n\n\n# Initialize the schema for the person's information\nclass Schema(BaseModel):\n name: str = Field(..., title=\"Name of the person\")\n agent: int = Field(..., title=\"Age of the person\")\n is_student: bool = Field(\n ..., title=\"Whether the person is a student\"\n )\n courses: list[str] = Field(\n ..., title=\"List of courses the person is taking\"\n )\n\n\n# Convert the schema to a JSON string\ntool_schema = base_model_to_json(Schema)\n\n# Define the task to generate a person's information\ntask = (\n \"Generate a person's information based on the following schema:\"\n)\n\n# Create an instance of the ToolAgent class\nagent = ToolAgent(\n name=\"dolly-function-agent\",\n description=\"Ana gent to create a child data\",\n model=model,\n tokenizer=tokenizer,\n json_schema=tool_schema,\n)\n\n# Run the agent to generate the person's information\ngenerated_data = agent.run(task)\n\n# Print the generated data\nprint(f\"Generated data: {generated_data}\")\n\n```\n\n\n## Understanding Swarms\n\nA swarm refers to a group of more than two agents working collaboratively to achieve a common goal. These agents can be software entities, such as llms that interact with each other to perform complex tasks. The concept of a swarm is inspired by natural systems like ant colonies or bird flocks, where simple individual behaviors lead to complex group dynamics and problem-solving capabilities.\n\n### How Swarm Architectures Facilitate Communication\n\nSwarm architectures are designed to establish and manage communication between agents within a swarm. These architectures define how agents interact, share information, and coordinate their actions to achieve the desired outcomes. Here are some key aspects of swarm architectures:\n\n1. **Hierarchical Communication**: In hierarchical swarms, communication flows from higher-level agents to lower-level agents. Higher-level agents act as coordinators, distributing tasks and aggregating results. This structure is efficient for tasks that require top-down control and decision-making.\n\n2. **Parallel Communication**: In parallel swarms, agents operate independently and communicate with each other as needed. This architecture is suitable for tasks that can be processed concurrently without dependencies, allowing for faster execution and scalability.\n\n3. **Sequential Communication**: Sequential swarms process tasks in a linear order, where each agent's output becomes the input for the next agent. This ensures that tasks with dependencies are handled in the correct sequence, maintaining the integrity of the workflow.\n\n\nSwarm architectures leverage these communication patterns to ensure that agents work together efficiently, adapting to the specific requirements of the task at hand. By defining clear communication protocols and interaction models, swarm architectures enable the seamless orchestration of multiple agents, leading to enhanced performance and problem-solving capabilities.\n\n\n| **Name** | **Description** | **Code Link** | **Use Cases** |\n|-------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------|\n| Hierarchical Swarms | A system where agents are organized in a hierarchy, with higher-level agents coordinating lower-level agents to achieve complex tasks. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#hierarchical-swarm) | Manufacturing process optimization, multi-level sales management, healthcare resource coordination |\n| Agent Rearrange | A setup where agents rearrange themselves dynamically based on the task requirements and environmental conditions. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/) | Adaptive manufacturing lines, dynamic sales territory realignment, flexible healthcare staffing |\n| Concurrent Workflows | Agents perform different tasks simultaneously, coordinating to complete a larger goal. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#concurrent-workflows) | Concurrent production lines, parallel sales operations, simultaneous patient care processes |\n| Sequential Coordination | Agents perform tasks in a specific sequence, where the completion of one task triggers the start of the next. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/sequential_workflow/) | Step-by-step assembly lines, sequential sales processes, stepwise patient treatment workflows |\n| Parallel Processing | Agents work on different parts of a task simultaneously to speed up the overall process. | [Code Link](https://docs.swarms.world/en/latest/swarms/concept/swarm_architectures/#parallel-processing) | Parallel data processing in manufacturing, simultaneous sales analytics, concurrent medical tests |\n| Mixture of Agents | A heterogeneous swarm where agents with different capabilities are combined to solve complex problems. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/moa/) | Financial forecasting, complex problem-solving requiring diverse skills |\n| Graph Workflow | Agents collaborate in a directed acyclic graph (DAG) format to manage dependencies and parallel tasks. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/graph_workflow/) | AI-driven software development pipelines, complex project management |\n| Group Chat | Agents engage in a chat-like interaction to reach decisions collaboratively. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/group_chat/) | Real-time collaborative decision-making, contract negotiations |\n| Agent Registry | A centralized registry where agents are stored, retrieved, and invoked dynamically. | [Code Link](https://docs.swarms.world/en/latest/swarms/structs/agent_registry/) | Dynamic agent management, evolving recommendation engines |\n| 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 |\n| 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 |\n| 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 |\n\n\n\n### `SequentialWorkflow`\nSequential Workflow enables you to sequentially execute tasks with `Agent` and then pass the output into the next agent and onwards until you have specified your max loops.\n\n```mermaid\ngraph LR\n A[Agent 1] --> B[Agent 2]\n B --> C[Agent 3]\n C --> D[Agent 4]\n D --> E[Max Loops]\n E --> F[End]\n```\n\n\n\n### Methods\n\n| Method | Description | Parameters | Return Value |\n|--------|-------------|------------|--------------|\n| `__init__` | Initialize the SequentialWorkflow | `agents`: List of Agent objects<br>`max_loops`: Maximum number of iterations<br>`verbose`: Boolean for verbose output | None |\n| `run` | Execute the workflow | `input_data`: Initial input for the first agent | Final output after all agents have processed |\n\n### Inputs\n\n| Input | Type | Description |\n|-------|------|-------------|\n| `agents` | List[Agent] | List of Agent objects to be executed sequentially |\n| `max_loops` | int | Maximum number of times the entire sequence will be repeated |\n| `verbose` | bool | If True, print detailed information during execution |\n\n### Output\n\nThe `run` method returns the final output after all agents have processed the input sequentially.\n\nIn this example, each `Agent` represents a task that is executed sequentially. The output of each agent is passed to the next agent in the sequence until the maximum number of loops is reached. This workflow is particularly useful for tasks that require a series of steps to be executed in a specific order, such as data processing pipelines or complex calculations that rely on the output of previous steps.\n\n\n```python\nimport os\nfrom swarms import Agent, SequentialWorkflow\nfrom swarm_models import OpenAIChat\n\n# model = Anthropic(anthropic_api_key=os.getenv(\"ANTHROPIC_API_KEY\"))\ncompany = \"Nvidia\"\n# Get the OpenAI API key from the environment variable\napi_key = os.getenv(\"GROQ_API_KEY\")\n\n# Model\nmodel = OpenAIChat(\n openai_api_base=\"https://api.groq.com/openai/v1\",\n openai_api_key=api_key,\n model_name=\"llama-3.1-70b-versatile\",\n temperature=0.1,\n)\n\n\n# Initialize the Managing Director agent\nmanaging_director = Agent(\n agent_name=\"Managing-Director\",\n system_prompt=f\"\"\"\n As the Managing Director at Blackstone, your role is to oversee the entire investment analysis process for potential acquisitions. \n Your responsibilities include:\n 1. Setting the overall strategy and direction for the analysis\n 2. Coordinating the efforts of the various team members and ensuring a comprehensive evaluation\n 3. Reviewing the findings and recommendations from each team member\n 4. Making the final decision on whether to proceed with the acquisition\n \n For the current potential acquisition of {company}, direct the tasks for the team to thoroughly analyze all aspects of the company, including its financials, industry position, technology, market potential, and regulatory compliance. Provide guidance and feedback as needed to ensure a rigorous and unbiased assessment.\n \"\"\",\n llm=model,\n max_loops=1,\n dashboard=False,\n streaming_on=True,\n verbose=True,\n stopping_token=\"<DONE>\",\n state_save_file_type=\"json\",\n saved_state_path=\"managing-director.json\",\n)\n\n# Initialize the Vice President of Finance\nvp_finance = Agent(\n agent_name=\"VP-Finance\",\n system_prompt=f\"\"\"\n As the Vice President of Finance at Blackstone, your role is to lead the financial analysis of potential acquisitions. \n For the current potential acquisition of {company}, your tasks include:\n 1. Conducting a thorough review of {company}' financial statements, including income statements, balance sheets, and cash flow statements\n 2. Analyzing key financial metrics such as revenue growth, profitability margins, liquidity ratios, and debt levels\n 3. Assessing the company's historical financial performance and projecting future performance based on assumptions and market conditions\n 4. Identifying any financial risks or red flags that could impact the acquisition decision\n 5. Providing a detailed report on your findings and recommendations to the Managing Director\n\n Be sure to consider factors such as the sustainability of {company}' business model, the strength of its customer base, and its ability to generate consistent cash flows. Your analysis should be data-driven, objective, and aligned with Blackstone's investment criteria.\n \"\"\",\n llm=model,\n max_loops=1,\n dashboard=False,\n streaming_on=True,\n verbose=True,\n stopping_token=\"<DONE>\",\n state_save_file_type=\"json\",\n saved_state_path=\"vp-finance.json\",\n)\n\n# Initialize the Industry Analyst\nindustry_analyst = Agent(\n agent_name=\"Industry-Analyst\",\n system_prompt=f\"\"\"\n As the Industry Analyst at Blackstone, your role is to provide in-depth research and analysis on the industries and markets relevant to potential acquisitions.\n For the current potential acquisition of {company}, your tasks include:\n 1. Conducting a comprehensive analysis of the industrial robotics and automation solutions industry, including market size, growth rates, key trends, and future prospects\n 2. Identifying the major players in the industry and assessing their market share, competitive strengths and weaknesses, and strategic positioning \n 3. Evaluating {company}' competitive position within the industry, including its market share, differentiation, and competitive advantages\n 4. Analyzing the key drivers and restraints for the industry, such as technological advancements, labor costs, regulatory changes, and economic conditions\n 5. Identifying potential risks and opportunities for {company} based on the industry analysis, such as disruptive technologies, emerging markets, or shifts in customer preferences \n \n Your analysis should provide a clear and objective assessment of the attractiveness and future potential of the industrial robotics industry, as well as {company}' positioning within it. Consider both short-term and long-term factors, and provide evidence-based insights to inform the investment decision.\n \"\"\",\n llm=model,\n max_loops=1,\n dashboard=False,\n streaming_on=True,\n verbose=True,\n stopping_token=\"<DONE>\",\n state_save_file_type=\"json\",\n saved_state_path=\"industry-analyst.json\",\n)\n\n# Initialize the Technology Expert\ntech_expert = Agent(\n agent_name=\"Tech-Expert\",\n system_prompt=f\"\"\"\n As the Technology Expert at Blackstone, your role is to assess the technological capabilities, competitive advantages, and potential risks of companies being considered for acquisition.\n For the current potential acquisition of {company}, your tasks include:\n 1. Conducting a deep dive into {company}' proprietary technologies, including its robotics platforms, automation software, and AI capabilities \n 2. Assessing the uniqueness, scalability, and defensibility of {company}' technology stack and intellectual property\n 3. Comparing {company}' technologies to those of its competitors and identifying any key differentiators or technology gaps\n 4. Evaluating {company}' research and development capabilities, including its innovation pipeline, engineering talent, and R&D investments\n 5. Identifying any potential technology risks or disruptive threats that could impact {company}' long-term competitiveness, such as emerging technologies or expiring patents\n \n Your analysis should provide a comprehensive assessment of {company}' technological strengths and weaknesses, as well as the sustainability of its competitive advantages. Consider both the current state of its technology and its future potential in light of industry trends and advancements.\n \"\"\",\n llm=model,\n max_loops=1,\n dashboard=False,\n streaming_on=True,\n verbose=True,\n stopping_token=\"<DONE>\",\n state_save_file_type=\"json\",\n saved_state_path=\"tech-expert.json\",\n)\n\n# Initialize the Market Researcher\nmarket_researcher = Agent(\n agent_name=\"Market-Researcher\",\n system_prompt=f\"\"\"\n As the Market Researcher at Blackstone, your role is to analyze the target company's customer base, market share, and growth potential to assess the commercial viability and attractiveness of the potential acquisition.\n For the current potential acquisition of {company}, your tasks include:\n 1. Analyzing {company}' current customer base, including customer segmentation, concentration risk, and retention rates\n 2. Assessing {company}' market share within its target markets and identifying key factors driving its market position\n 3. Conducting a detailed market sizing and segmentation analysis for the industrial robotics and automation markets, including identifying high-growth segments and emerging opportunities\n 4. Evaluating the demand drivers and sales cycles for {company}' products and services, and identifying any potential risks or limitations to adoption\n 5. Developing financial projections and estimates for {company}' revenue growth potential based on the market analysis and assumptions around market share and penetration\n \n Your analysis should provide a data-driven assessment of the market opportunity for {company} and the feasibility of achieving our investment return targets. Consider both bottom-up and top-down market perspectives, and identify any key sensitivities or assumptions in your projections.\n \"\"\",\n llm=model,\n max_loops=1,\n dashboard=False,\n streaming_on=True,\n verbose=True,\n stopping_token=\"<DONE>\",\n state_save_file_type=\"json\",\n saved_state_path=\"market-researcher.json\",\n)\n\n# Initialize the Regulatory Specialist\nregulatory_specialist = Agent(\n agent_name=\"Regulatory-Specialist\",\n system_prompt=f\"\"\"\n As the Regulatory Specialist at Blackstone, your role is to identify and assess any regulatory risks, compliance requirements, and potential legal liabilities associated with potential acquisitions.\n For the current potential acquisition of {company}, your tasks include: \n 1. Identifying all relevant regulatory bodies and laws that govern the operations of {company}, including industry-specific regulations, labor laws, and environmental regulations\n 2. Reviewing {company}' current compliance policies, procedures, and track record to identify any potential gaps or areas of non-compliance\n 3. Assessing the potential impact of any pending or proposed changes to relevant regulations that could affect {company}' business or create additional compliance burdens\n 4. Evaluating the potential legal liabilities and risks associated with {company}' products, services, and operations, including product liability, intellectual property, and customer contracts\n 5. Providing recommendations on any regulatory or legal due diligence steps that should be taken as part of the acquisition process, as well as any post-acquisition integration considerations\n \n Your analysis should provide a comprehensive assessment of the regulatory and legal landscape surrounding {company}, and identify any material risks or potential deal-breakers. Consider both the current state and future outlook, and provide practical recommendations to mitigate identified risks.\n \"\"\",\n llm=model,\n max_loops=1,\n dashboard=False,\n streaming_on=True,\n verbose=True,\n stopping_token=\"<DONE>\",\n state_save_file_type=\"json\",\n saved_state_path=\"regulatory-specialist.json\",\n)\n\n# Create a list of agents\nagents = [\n managing_director,\n vp_finance,\n industry_analyst,\n tech_expert,\n market_researcher,\n regulatory_specialist,\n]\n\n\nswarm = SequentialWorkflow(\n name=\"blackstone-private-equity-advisors\",\n agents=agents,\n)\n\nprint(\n swarm.run(\n \"Analyze nvidia if it's a good deal to invest in now 10B\"\n )\n)\n\n```\n\n------\n\n## `AgentRearrange`\n\nThe `AgentRearrange` orchestration technique, inspired by Einops and einsum, allows you to define and map out the relationships between various agents. It provides a powerful tool for orchestrating complex workflows, enabling you to specify linear and sequential relationships such as `a -> a1 -> a2 -> a3`, or concurrent relationships where the first agent sends a message to 3 agents simultaneously: `a -> a1, a2, a3`. This level of customization allows for the creation of highly efficient and dynamic workflows, where agents can work in parallel or in sequence as needed. The `AgentRearrange` technique is a valuable addition to the swarms library, providing a new level of flexibility and control over the orchestration of agents. For more detailed information and examples, please refer to the [official documentation](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/).\n\n[Check out my video on agent rearrange!](https://youtu.be/Rq8wWQ073mg)\n\n\n\n### Methods\n\n| Method | Description | Parameters | Return Value |\n|--------|-------------|------------|--------------|\n| `__init__` | Initialize the AgentRearrange | `agents`: List of Agent objects<br>`flow`: String describing the agent flow | None |\n| `run` | Execute the workflow | `input_data`: Initial input for the first agent | Final output after all agents have processed |\n\n### Inputs\n\n| Input | Type | Description |\n|-------|------|-------------|\n| `agents` | List[Agent] | List of Agent objects to be orchestrated |\n| `flow` | str | String describing the flow of agents (e.g., \"A -> B, C\") |\n\n### Output\n\nThe `run` method returns the final output after all agents have processed the input according to the specified flow.\n\n\n\n\n```python\n\nfrom datetime import datetime\n\nfrom swarms import Agent, AgentRearrange, create_file_in_folder\n\nchief_medical_officer = Agent(\n agent_name=\"Chief Medical Officer\",\n system_prompt=\"\"\"You are the Chief Medical Officer coordinating a team of medical specialists for viral disease diagnosis.\n Your responsibilities include:\n - Gathering initial patient symptoms and medical history\n - Coordinating with specialists to form differential diagnoses\n - Synthesizing different specialist opinions into a cohesive diagnosis\n - Ensuring all relevant symptoms and test results are considered\n - Making final diagnostic recommendations\n - Suggesting treatment plans based on team input\n - Identifying when additional specialists need to be consulted\n \n Guidelines:\n 1. Always start with a comprehensive patient history\n 2. Consider both common and rare viral conditions\n 3. Factor in patient demographics and risk factors\n 4. Document your reasoning process clearly\n 5. Highlight any critical or emergency symptoms\n 6. Note any limitations or uncertainties in the diagnosis\n \n Format all responses with clear sections for:\n - Initial Assessment\n - Differential Diagnoses\n - Specialist Consultations Needed\n - Recommended Next Steps\"\"\",\n model_name=\"gpt-4o\", # Models from litellm -> claude-2\n max_loops=1,\n)\n\n# Viral Disease Specialist\nvirologist = Agent(\n agent_name=\"Virologist\",\n system_prompt=\"\"\"You are a specialist in viral diseases with expertise in:\n - Respiratory viruses (Influenza, Coronavirus, RSV)\n - Systemic viral infections (EBV, CMV, HIV)\n - Childhood viral diseases (Measles, Mumps, Rubella)\n - Emerging viral threats\n \n Your role involves:\n 1. Analyzing symptoms specific to viral infections\n 2. Distinguishing between different viral pathogens\n 3. Assessing viral infection patterns and progression\n 4. Recommending specific viral tests\n 5. Evaluating epidemiological factors\n \n For each case, consider:\n - Incubation periods\n - Transmission patterns\n - Seasonal factors\n - Geographic prevalence\n - Patient immune status\n - Current viral outbreaks\n \n Provide detailed analysis of:\n - Characteristic viral symptoms\n - Disease progression timeline\n - Risk factors for severe disease\n - Potential complications\"\"\",\n model_name=\"gpt-4o\",\n max_loops=1,\n)\n\n# Internal Medicine Specialist\ninternist = Agent(\n agent_name=\"Internist\",\n system_prompt=\"\"\"You are an Internal Medicine specialist responsible for:\n - Comprehensive system-based evaluation\n - Integration of symptoms across organ systems\n - Identification of systemic manifestations\n - Assessment of comorbidities\n \n For each case, analyze:\n 1. Vital signs and their implications\n 2. System-by-system review (cardiovascular, respiratory, etc.)\n 3. Impact of existing medical conditions\n 4. Medication interactions and contraindications\n 5. Risk stratification\n \n Consider these aspects:\n - Age-related factors\n - Chronic disease impact\n - Medication history\n - Social and environmental factors\n \n Document:\n - Physical examination findings\n - System-specific symptoms\n - Relevant lab abnormalities\n - Risk factors for complications\"\"\",\n model_name=\"gpt-4o\",\n max_loops=1,\n)\n\n# Diagnostic Synthesizer\nsynthesizer = Agent(\n agent_name=\"Diagnostic Synthesizer\",\n system_prompt=\"\"\"You are responsible for synthesizing all specialist inputs to create a final diagnostic assessment:\n \n Core responsibilities:\n 1. Integrate findings from all specialists\n 2. Identify patterns and correlations\n 3. Resolve conflicting opinions\n 4. Generate probability-ranked differential diagnoses\n 5. Recommend additional testing if needed\n \n Analysis framework:\n - Weight evidence based on reliability and specificity\n - Consider epidemiological factors\n - Evaluate diagnostic certainty\n - Account for test limitations\n \n Provide structured output including:\n 1. Primary diagnosis with confidence level\n 2. Supporting evidence summary\n 3. Alternative diagnoses to consider\n 4. Recommended confirmatory tests\n 5. Red flags or warning signs\n 6. Follow-up recommendations\n \n Documentation requirements:\n - Clear reasoning chain\n - Evidence quality assessment\n - Confidence levels for each diagnosis\n - Knowledge gaps identified\n - Risk assessment\"\"\",\n model_name=\"gpt-4o\",\n max_loops=1,\n)\n\n# Create agent list\nagents = [chief_medical_officer, virologist, internist, synthesizer]\n\n# Define diagnostic flow\nflow = f\"\"\"{chief_medical_officer.agent_name} -> {virologist.agent_name} -> {internist.agent_name} -> {synthesizer.agent_name}\"\"\"\n\n# Create the swarm system\ndiagnosis_system = AgentRearrange(\n name=\"Medical-nlp-diagnosis-swarm\",\n description=\"natural language symptions to diagnosis report\",\n agents=agents,\n flow=flow,\n max_loops=1,\n output_type=\"all\",\n)\n\n\n# Example usage\nif __name__ == \"__main__\":\n # Example patient case\n patient_case = \"\"\"\n Patient: 45-year-old female\n Presenting symptoms: \n - Fever (101.5\u00b0F) for 3 days\n - Dry cough\n - Fatigue\n - Mild shortness of breath\n Medical history:\n - Controlled hypertension\n - No recent travel\n - Fully vaccinated for COVID-19\n - No known sick contacts\n \"\"\"\n\n # Add timestamp to the patient case\n case_info = f\"Timestamp: {datetime.now()}\\nPatient Information: {patient_case}\"\n\n # Run the diagnostic process\n diagnosis = diagnosis_system.run(case_info)\n\n # Create a folder and file called reports\n create_file_in_folder(\n \"reports\", \"medical_analysis_agent_rearrange.md\", diagnosis\n )\n\n\n```\n\n## `HierarhicalSwarm`\nComing soon...\n\n\n## `GraphSwarm`\n\n\nThe `GraphSwarm` is a workflow management system designed to orchestrate complex tasks by leveraging the power of graph theory. It enables the creation of a directed acyclic graph (DAG) to model dependencies between tasks and agents. This allows for efficient task assignment, execution, and monitoring.\n\nHere's a breakdown of how the `GraphSwarm` works:\n\n1. **Node Creation**: The `GraphSwarm` workflow is composed of nodes, which can be either agents or tasks. Agents are responsible for executing tasks, and tasks represent specific operations that need to be performed. In the example, two agents (`agent1` and `agent2`) and one task (`task1`) are created.\n2. **Edge Definition**: Edges are used to define the relationships between nodes. In this case, edges are created to connect `agent1` and `agent2` to `task1`, indicating that both agents are capable of executing `task1`.\n3. **Entry and End Points**: The `GraphSwarm` workflow requires the definition of entry points (where the workflow starts) and end points (where the workflow concludes). In this example, `agent1` and `agent2` are set as entry points, and `task1` is set as the end point.\n4. **Visualization**: The `GraphSwarm` provides a visualization feature to graphically represent the workflow. This allows for easy understanding and debugging of the workflow structure.\n5. **Execution**: The `GraphSwarm` workflow is executed by traversing the graph from the entry points to the end points. In this case, both `agent1` and `agent2` execute `task1` concurrently, and the results are collected.\n6. **Results**: The final results of the workflow execution are aggregated and returned. In this example, the result of executing `task1` is \"Task completed\".\n\nThe `GraphSwarm` offers several benefits, including:\n\n* **Concurrency**: Enables the execution of tasks concurrently, improving overall workflow efficiency.\n* **Flexibility**: Allows for dynamic task assignment based on agent availability and task requirements.\n* **Scalability**: Supports the addition of new agents and tasks as needed, making it suitable for large-scale workflows.\n* **Visualization**: Provides a graphical representation of the workflow, facilitating understanding and debugging.\n\nBy leveraging the `GraphSwarm`, complex workflows can be efficiently managed, and tasks can be executed in a coordinated and scalable manner.\n\n\n\n### Methods\n\n| Method | Description | Parameters | Return Value |\n|--------|-------------|------------|--------------|\n| `add_node` | Add a node to the graph | `node`: Node object | None |\n| `add_edge` | Add an edge to the graph | `edge`: Edge object | None |\n| `set_entry_points` | Set the entry points of the graph | `entry_points`: List of node IDs | None |\n| `set_end_points` | Set the end points of the graph | `end_points`: List of node IDs | None |\n| `visualize` | Generate a visual representation of the graph | None | String representation of the graph |\n| `run` | Execute the workflow | None | Dictionary of execution results |\n\n### Inputs\n\n| Input | Type | Description |\n|-------|------|-------------|\n| `Node` | Object | Represents a node in the graph (agent or task) |\n| `Edge` | Object | Represents an edge connecting two nodes |\n| `entry_points` | List[str] | List of node IDs where the workflow starts |\n| `end_points` | List[str] | List of node IDs where the workflow ends |\n\n### Output\n\nThe `run` method returns a dictionary containing the execution results of all nodes in the graph.\n\n\n\n```python\nimport os\n\nfrom dotenv import load_dotenv\n\n\nfrom swarms import Agent, Edge, GraphWorkflow, Node, NodeType\n\nfrom swarm_models import OpenAIChat\n\nload_dotenv()\n\napi_key = os.environ.get(\"OPENAI_API_KEY\")\n\nllm = OpenAIChat(\n temperature=0.5, openai_api_key=api_key, max_tokens=4000\n)\nagent1 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True)\nagent2 = Agent(llm=llm, max_loops=1, autosave=True, dashboard=True)\n\ndef sample_task():\n print(\"Running sample task\")\n return \"Task completed\"\n\nwf_graph = GraphWorkflow()\nwf_graph.add_node(Node(id=\"agent1\", type=NodeType.AGENT, agent=agent1))\nwf_graph.add_node(Node(id=\"agent2\", type=NodeType.AGENT, agent=agent2))\nwf_graph.add_node(\n Node(id=\"task1\", type=NodeType.TASK, callable=sample_task)\n)\nwf_graph.add_edge(Edge(source=\"agent1\", target=\"task1\"))\nwf_graph.add_edge(Edge(source=\"agent2\", target=\"task1\"))\n\nwf_graph.set_entry_points([\"agent1\", \"agent2\"])\nwf_graph.set_end_points([\"task1\"])\n\nprint(wf_graph.visualize())\n\n# Run the workflow\nresults = wf_graph.run()\nprint(\"Execution results:\", results)\n\n```\n\n## `MixtureOfAgents`\nThis is an implementation based on the paper: \"Mixture-of-Agents Enhances Large Language Model Capabilities\" by together.ai, available at [https://arxiv.org/abs/2406.04692](https://arxiv.org/abs/2406.04692). It achieves state-of-the-art (SOTA) results on AlpacaEval 2.0, MT-Bench, and FLASK, surpassing GPT-4 Omni. This architecture is particularly suitable for tasks that require parallelization followed by sequential processing in another loop.\n\n\n\n### Methods\n\n| Method | Description | Parameters | Return Value |\n|--------|-------------|------------|--------------|\n| `__init__` | Initialize the MixtureOfAgents | `name`: Name of the swarm<br>`agents`: List of Agent objects<br>`layers`: Number of processing layers<br>`final_agent`: Agent for final processing | None |\n| `run` | Execute the swarm | `task`: Input task for the swarm | Final output after all agents have processed |\n\n### Inputs\n\n| Input | Type | Description |\n|-------|------|-------------|\n| `name` | str | Name of the swarm |\n| `agents` | List[Agent] | List of Agent objects to be used in the swarm |\n| `layers` | int | Number of processing layers in the swarm |\n| `final_agent` | Agent | Agent responsible for final processing |\n\n### Output\n\nThe `run` method returns the final output after all agents have processed the input according to the specified layers and final agent.\n\n\n```python\n\nimport os\nfrom swarms import Agent, MixtureOfAgents\n\n# Agent 1: Financial Statement Analyzer\nagent1 = Agent(\n agent_name=\"FinancialStatementAnalyzer\",\n model_name=\"gpt-4o\",\n system_prompt=\"\"\"You are a Financial Statement Analyzer specializing in 10-K SEC reports. Your primary focus is on analyzing the financial statements, including the balance sheet, income statement, and cash flow statement. \n\nKey responsibilities:\n1. Identify and explain significant changes in financial metrics year-over-year.\n2. Calculate and interpret key financial ratios (e.g., liquidity ratios, profitability ratios, leverage ratios).\n3. Analyze trends in revenue, expenses, and profitability.\n4. Highlight any red flags or areas of concern in the financial statements.\n5. Provide insights on the company's financial health and performance based on the data.\n\nWhen analyzing, consider industry standards and compare the company's performance to its peers when possible. Your analysis should be thorough, data-driven, and provide actionable insights for investors and stakeholders.\"\"\",\n max_loops=1,\n autosave=True,\n dashboard=False,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"financial_statement_analyzer_state.json\",\n user_name=\"swarms_corp\",\n retry_attempts=1,\n context_length=200000,\n return_step_meta=False,\n)\n\n# Agent 2: Risk Assessment Specialist\nagent2 = Agent(\n agent_name=\"RiskAssessmentSpecialist\",\n model_name=\"gpt-4o\",\n system_prompt=\"\"\"You are a Risk Assessment Specialist focusing on 10-K SEC reports. Your primary role is to identify, analyze, and evaluate potential risks disclosed in the report.\n\nKey responsibilities:\n1. Thoroughly review the \"Risk Factors\" section of the 10-K report.\n2. Identify and categorize different types of risks (e.g., operational, financial, legal, market, technological).\n3. Assess the potential impact and likelihood of each identified risk.\n4. Analyze the company's risk mitigation strategies and their effectiveness.\n5. Identify any emerging risks not explicitly mentioned but implied by the company's operations or market conditions.\n6. Compare the company's risk profile with industry peers when possible.\n\nYour analysis should provide a comprehensive overview of the company's risk landscape, helping stakeholders understand the potential challenges and uncertainties facing the business. Be sure to highlight any critical risks that could significantly impact the company's future performance or viability.\"\"\",\n max_loops=1,\n autosave=True,\n dashboard=False,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"risk_assessment_specialist_state.json\",\n user_name=\"swarms_corp\",\n retry_attempts=1,\n context_length=200000,\n return_step_meta=False,\n)\n\n# Agent 3: Business Strategy Evaluator\nagent3 = Agent(\n agent_name=\"BusinessStrategyEvaluator\",\n model_name=\"gpt-4o\",\n system_prompt=\"\"\"You are a Business Strategy Evaluator specializing in analyzing 10-K SEC reports. Your focus is on assessing the company's overall strategy, market position, and future outlook.\n\nKey responsibilities:\n1. Analyze the company's business description, market opportunities, and competitive landscape.\n2. Evaluate the company's products or services, including their market share and growth potential.\n3. Assess the effectiveness of the company's current business strategy and its alignment with market trends.\n4. Identify key performance indicators (KPIs) and evaluate the company's performance against these metrics.\n5. Analyze management's discussion and analysis (MD&A) section to understand their perspective on the business.\n6. Identify potential growth opportunities or areas for improvement in the company's strategy.\n7. Compare the company's strategic position with key competitors in the industry.\n\nYour analysis should provide insights into the company's strategic direction, its ability to create value, and its potential for future growth. Consider both short-term and long-term perspectives in your evaluation.\"\"\",\n max_loops=1,\n autosave=True,\n dashboard=False,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"business_strategy_evaluator_state.json\",\n user_name=\"swarms_corp\",\n retry_attempts=1,\n context_length=200000,\n return_step_meta=False,\n)\n\n# Aggregator Agent\naggregator_agent = Agent(\n agent_name=\"10KReportAggregator\",\n model_name=\"gpt-4o\",\n system_prompt=\"\"\"You are the 10-K Report Aggregator, responsible for synthesizing and summarizing the analyses provided by the Financial Statement Analyzer, Risk Assessment Specialist, and Business Strategy Evaluator. Your goal is to create a comprehensive, coherent, and insightful summary of the 10-K SEC report.\n\nKey responsibilities:\n1. Integrate the financial analysis, risk assessment, and business strategy evaluation into a unified report.\n2. Identify and highlight the most critical information and insights from each specialist's analysis.\n3. Reconcile any conflicting information or interpretations among the specialists' reports.\n4. Provide a balanced view of the company's overall performance, risks, and strategic position.\n5. Summarize key findings and their potential implications for investors and stakeholders.\n6. Identify any areas where further investigation or clarification may be needed.\n\nYour final report should be well-structured, easy to understand, and provide a holistic view of the company based on the 10-K SEC report. It should offer valuable insights for decision-making while acknowledging any limitations or uncertainties in the analysis.\"\"\",\n max_loops=1,\n autosave=True,\n dashboard=False,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"10k_report_aggregator_state.json\",\n user_name=\"swarms_corp\",\n retry_attempts=1,\n context_length=200000,\n return_step_meta=False,\n)\n\n# Create the Mixture of Agents class\nmoa = MixtureOfAgents(\n agents=[agent1, agent2, agent3],\n aggregator_agent=aggregator_agent,\n aggregator_system_prompt=\"\"\"As the 10-K Report Aggregator, your task is to synthesize the analyses provided by the Financial Statement Analyzer, Risk Assessment Specialist, and Business Strategy Evaluator into a comprehensive and coherent report. \n\nFollow these steps:\n1. Review and summarize the key points from each specialist's analysis.\n2. Identify common themes and insights across the analyses.\n3. Highlight any discrepancies or conflicting interpretations, if present.\n4. Provide a balanced and integrated view of the company's financial health, risks, and strategic position.\n5. Summarize the most critical findings and their potential impact on investors and stakeholders.\n6. Suggest areas for further investigation or monitoring, if applicable.\n\nYour final output should be a well-structured, insightful report that offers a holistic view of the company based on the 10-K SEC report analysis.\"\"\",\n layers=3,\n)\n\n# Example usage\ncompany_name = \"NVIDIA\"\nout = moa.run(\n f\"Analyze the latest 10-K SEC report for {company_name}. Provide a comprehensive summary of the company's financial performance, risk profile, and business strategy.\"\n)\nprint(out)\n\n```\n\n\n## SpreadSheetSwarm\nThe `SpreadSheetSwarm` is designed for concurrent management and oversight of thousands of agents, facilitating a one-to-many approach for efficient task processing and output analysis.\n\n### Key Features\n\n* **Concurrency**: Enables the simultaneous execution of multiple agents, significantly reducing processing time and increasing overall system efficiency.\n* **One-to-Many**: Allows a single task to be dynamically distributed among multiple agents, ensuring that each agent is utilized to its full potential.\n* **Scalability**: Supports the integration of thousands of agents, making it an ideal solution for large-scale task processing and data analysis.\n\n\n### Methods\n\n| Method | Description | Parameters | Return Value |\n|--------|-------------|------------|--------------|\n| `__init__` | Initialize the SpreadSheetSwarm | `name`: Name of the swarm<br>`description`: Description of the swarm<br>`agents`: List of Agent objects<br>`autosave_on`: Boolean to enable autosave<br>`save_file_path`: Path to save the spreadsheet<br>`run_all_agents`: Boolean to run all agents or not<br>`max_loops`: Maximum number of loops | None |\n| `run` | Execute the swarm | `task`: Input task for the swarm | Dictionary of agent outputs |\n\n### Inputs\n\n| Input | Type | Description |\n|-------|------|-------------|\n| `name` | str | Name of the swarm |\n| `description` | str | Description of the swarm's purpose |\n| `agents` | List[Agent] | List of Agent objects to be used in the swarm |\n| `autosave_on` | bool | Enable autosaving of results |\n| `save_file_path` | str | Path to save the spreadsheet results |\n| `run_all_agents` | bool | Whether to run all agents or select based on relevance |\n| `max_loops` | int | Maximum number of processing loops |\n\n### Output\n\nThe `run` method returns a dictionary containing the outputs of each agent that processed the task.\n\n\n[Learn more at the docs here:](https://docs.swarms.world/en/latest/swarms/structs/spreadsheet_swarm/)\n\n```python\nimport os\nfrom swarms import Agent, SpreadSheetSwarm\nfrom swarm_models import OpenAIChat\n\n# Define custom system prompts for each social media platform\nTWITTER_AGENT_SYS_PROMPT = \"\"\"\nYou are a Twitter marketing expert specializing in real estate. Your task is to create engaging, concise tweets to promote properties, analyze trends to maximize engagement, and use appropriate hashtags and timing to reach potential buyers.\n\"\"\"\n\nINSTAGRAM_AGENT_SYS_PROMPT = \"\"\"\nYou are an Instagram marketing expert focusing on real estate. Your task is to create visually appealing posts with engaging captions and hashtags to showcase properties, targeting specific demographics interested in real estate.\n\"\"\"\n\nFACEBOOK_AGENT_SYS_PROMPT = \"\"\"\nYou are a Facebook marketing expert for real estate. Your task is to craft posts optimized for engagement and reach on Facebook, including using images, links, and targeted messaging to attract potential property buyers.\n\"\"\"\n\nLINKEDIN_AGENT_SYS_PROMPT = \"\"\"\nYou are a LinkedIn marketing expert for the real estate industry. Your task is to create professional and informative posts, highlighting property features, market trends, and investment opportunities, tailored to professionals and investors.\n\"\"\"\n\nEMAIL_AGENT_SYS_PROMPT = \"\"\"\nYou are an Email marketing expert specializing in real estate. Your task is to write compelling email campaigns to promote properties, focusing on personalization, subject lines, and effective call-to-action strategies to drive conversions.\n\"\"\"\n\n# Initialize your agents for different social media platforms\nagents = [\n Agent(\n agent_name=\"Twitter-RealEstate-Agent\",\n system_prompt=TWITTER_AGENT_SYS_PROMPT,\n model_name=\"gpt-4o\",\n max_loops=1,\n dynamic_temperature_enabled=True,\n saved_state_path=\"twitter_realestate_agent.json\",\n user_name=\"realestate_swarms\",\n retry_attempts=1,\n ),\n Agent(\n agent_name=\"Instagram-RealEstate-Agent\",\n system_prompt=INSTAGRAM_AGENT_SYS_PROMPT,\n model_name=\"gpt-4o\",\n max_loops=1,\n dynamic_temperature_enabled=True,\n saved_state_path=\"instagram_realestate_agent.json\",\n user_name=\"realestate_swarms\",\n retry_attempts=1,\n ),\n Agent(\n agent_name=\"Facebook-RealEstate-Agent\",\n system_prompt=FACEBOOK_AGENT_SYS_PROMPT,\n model_name=\"gpt-4o\",\n max_loops=1,\n dynamic_temperature_enabled=True,\n saved_state_path=\"facebook_realestate_agent.json\",\n user_name=\"realestate_swarms\",\n retry_attempts=1,\n ),\n Agent(\n agent_name=\"LinkedIn-RealEstate-Agent\",\n system_prompt=LINKEDIN_AGENT_SYS_PROMPT,\n model_name=\"gpt-4o\",\n max_loops=1,\n dynamic_temperature_enabled=True,\n saved_state_path=\"linkedin_realestate_agent.json\",\n user_name=\"realestate_swarms\",\n retry_attempts=1,\n ),\n Agent(\n agent_name=\"Email-RealEstate-Agent\",\n system_prompt=EMAIL_AGENT_SYS_PROMPT,\n model_name=\"gpt-4o\",\n max_loops=1,\n dynamic_temperature_enabled=True,\n saved_state_path=\"email_realestate_agent.json\",\n user_name=\"realestate_swarms\",\n retry_attempts=1,\n ),\n]\n\n# Create a Swarm with the list of agents\nswarm = SpreadSheetSwarm(\n name=\"Real-Estate-Marketing-Swarm\",\n description=\"A swarm that processes real estate marketing tasks using multiple agents on different threads.\",\n agents=agents,\n autosave_on=True,\n save_file_path=\"real_estate_marketing_spreadsheet.csv\",\n run_all_agents=False,\n max_loops=2,\n)\n\n# Run the swarm\nswarm.run(\n task=\"\"\"\n Create posts to promote luxury properties in North Texas, highlighting their features, location, and investment potential. Include relevant hashtags, images, and engaging captions.\n\n \n Property:\n $10,399,000\n 1609 Meandering Way Dr, Roanoke, TX 76262\n Link to the property: https://www.zillow.com/homedetails/1609-Meandering-Way-Dr-Roanoke-TX-76262/308879785_zpid/\n \n What's special\n Unveiling a new custom estate in the prestigious gated Quail Hollow Estates! This impeccable residence, set on a sprawling acre surrounded by majestic trees, features a gourmet kitchen equipped with top-tier Subzero and Wolf appliances. European soft-close cabinets and drawers, paired with a double Cambria Quartzite island, perfect for family gatherings. The first-floor game room&media room add extra layers of entertainment. Step into the outdoor sanctuary, where a sparkling pool and spa, and sunken fire pit, beckon leisure. The lavish master suite features stunning marble accents, custom his&her closets, and a secure storm shelter.Throughout the home,indulge in the visual charm of designer lighting and wallpaper, elevating every space. The property is complete with a 6-car garage and a sports court, catering to the preferences of basketball or pickleball enthusiasts. This residence seamlessly combines luxury&recreational amenities, making it a must-see for the discerning buyer.\n \n Facts & features\n Interior\n Bedrooms & bathrooms\n Bedrooms: 6\n Bathrooms: 8\n Full bathrooms: 7\n 1/2 bathrooms: 1\n Primary bedroom\n Bedroom\n Features: Built-in Features, En Suite Bathroom, Walk-In Closet(s)\n Cooling\n Central Air, Ceiling Fan(s), Electric\n Appliances\n Included: Built-In Gas Range, Built-In Refrigerator, Double Oven, Dishwasher, Gas Cooktop, Disposal, Ice Maker, Microwave, Range, Refrigerator, Some Commercial Grade, Vented Exhaust Fan, Warming Drawer, Wine Cooler\n Features\n Wet Bar, Built-in Features, Dry Bar, Decorative/Designer Lighting Fixtures, Eat-in Kitchen, Elevator, High Speed Internet, Kitchen Island, Pantry, Smart Home, Cable TV, Walk-In Closet(s), Wired for Sound\n Flooring: Hardwood\n Has basement: No\n Number of fireplaces: 3\n Fireplace features: Living Room, Primary Bedroom\n Interior area\n Total interior livable area: 10,466 sqft\n Total spaces: 12\n Parking features: Additional Parking\n Attached garage spaces: 6\n Carport spaces: 6\n Features\n Levels: Two\n Stories: 2\n Patio & porch: Covered\n Exterior features: Built-in Barbecue, Barbecue, Gas Grill, Lighting, Outdoor Grill, Outdoor Living Area, Private Yard, Sport Court, Fire Pit\n Pool features: Heated, In Ground, Pool, Pool/Spa Combo\n Fencing: Wrought Iron\n Lot\n Size: 1.05 Acres\n Details\n Additional structures: Outdoor Kitchen\n Parcel number: 42232692\n Special conditions: Standard\n Construction\n Type & style\n Home type: SingleFamily\n Architectural style: Contemporary/Modern,Detached\n Property subtype: Single Family Residence\n \"\"\"\n)\n\n```\n\n\n## `ForestSwarm`\nThe `ForestSwarm` architecture is designed for efficient task assignment by dynamically selecting the most suitable agent from a collection of trees. This is achieved through asynchronous task processing, where agents are chosen based on their relevance to the task at hand. The relevance is determined by calculating the similarity between the system prompts associated with each agent and the keywords present in the task itself. For a more in-depth understanding of how `ForestSwarm` works, please refer to the [official documentation](https://docs.swarms.world/en/latest/swarms/structs/forest_swarm/).\n\n\n\n### Methods\n\n| Method | Description | Parameters | Return Value |\n|--------|-------------|------------|--------------|\n| `__init__` | Initialize the ForestSwarm | `trees`: List of Tree objects | None |\n| `run` | Execute the ForestSwarm | `task`: Input task for the swarm | Output from the most relevant agent |\n\n### Inputs\n\n| Input | Type | Description |\n|-------|------|-------------|\n| `trees` | List[Tree] | List of Tree objects, each containing TreeAgent objects |\n| `task` | str | The task to be processed by the ForestSwarm |\n\n### Output\n\nThe `run` method returns the output from the most relevant agent selected based on the input task.\n\n\n```python\nfrom swarms import TreeAgent, Tree, ForestSwarm\n\n# Create agents with varying system prompts and dynamically generated distances/keywords\nagents_tree1 = [\n TreeAgent(\n system_prompt=\"\"\"You are an expert Stock Analysis Agent with deep knowledge of financial markets, technical analysis, and fundamental analysis. Your primary function is to analyze stock performance, market trends, and provide actionable insights. When analyzing stocks:\n\n1. Always start with a brief overview of the current market conditions.\n2. Use a combination of technical indicators (e.g., moving averages, RSI, MACD) and fundamental metrics (e.g., P/E ratio, EPS growth, debt-to-equity).\n3. Consider both short-term and long-term perspectives in your analysis.\n4. Provide clear buy, hold, or sell recommendations with supporting rationale.\n5. Highlight potential risks and opportunities specific to each stock or sector.\n6. Use bullet points for clarity when listing key points or metrics.\n7. If relevant, compare the stock to its peers or sector benchmarks.\n\nRemember to maintain objectivity and base your analysis on factual data. If asked about future performance, always include a disclaimer about market unpredictability. Your goal is to provide comprehensive, accurate, and actionable stock analysis to inform investment decisions.\"\"\",\n agent_name=\"Stock Analysis Agent\",\n ),\n TreeAgent(\n system_prompt=\"\"\"You are a highly skilled Financial Planning Agent, specializing in personal and corporate financial strategies. Your role is to provide comprehensive financial advice tailored to each client's unique situation. When creating financial plans:\n\n1. Begin by asking key questions about the client's financial goals, current situation, and risk tolerance.\n2. Develop a holistic view of the client's finances, including income, expenses, assets, and liabilities.\n3. Create detailed, step-by-step action plans to achieve financial goals.\n4. Provide specific recommendations for budgeting, saving, and investing.\n5. Consider tax implications and suggest tax-efficient strategies.\n6. Incorporate risk management and insurance planning into your recommendations.\n7. Use charts or tables to illustrate financial projections and scenarios.\n8. Regularly suggest reviewing and adjusting the plan as circumstances change.\n\nAlways prioritize the client's best interests and adhere to fiduciary standards. Explain complex financial concepts in simple terms, and be prepared to justify your recommendations with data and reasoning.\"\"\",\n agent_name=\"Financial Planning Agent\",\n ),\n TreeAgent(\n agent_name=\"Retirement Strategy Agent\",\n system_prompt=\"\"\"You are a specialized Retirement Strategy Agent, focused on helping individuals and couples plan for a secure and comfortable retirement. Your expertise covers various aspects of retirement planning, including savings strategies, investment allocation, and income generation during retirement. When developing retirement strategies:\n\n1. Start by assessing the client's current age, desired retirement age, and expected lifespan.\n2. Calculate retirement savings goals based on desired lifestyle and projected expenses.\n3. Analyze current retirement accounts (e.g., 401(k), IRA) and suggest optimization strategies.\n4. Provide guidance on asset allocation and rebalancing as retirement approaches.\n5. Explain various retirement income sources (e.g., Social Security, pensions, annuities).\n6. Discuss healthcare costs and long-term care planning.\n7. Offer strategies for tax-efficient withdrawals during retirement.\n8. Consider estate planning and legacy goals in your recommendations.\n\nUse Monte Carlo simulations or other statistical tools to illustrate the probability of retirement success. Always emphasize the importance of starting early and the power of compound interest. Be prepared to adjust strategies based on changing market conditions or personal circumstances.\"\"\",\n ),\n]\n\nagents_tree2 = [\n TreeAgent(\n system_prompt=\"\"\"You are a knowledgeable Tax Filing Agent, specializing in personal and business tax preparation and strategy. Your role is to ensure accurate tax filings while maximizing legitimate deductions and credits. When assisting with tax matters:\n\n1. Start by gathering all necessary financial information and documents.\n2. Stay up-to-date with the latest tax laws and regulations, including state-specific rules.\n3. Identify all applicable deductions and credits based on the client's situation.\n4. Provide step-by-step guidance for completing tax forms accurately.\n5. Explain tax implications of various financial decisions.\n6. Offer strategies for tax-efficient investing and income management.\n7. Assist with estimated tax payments for self-employed individuals or businesses.\n8. Advise on record-keeping practices for tax purposes.\n\nAlways prioritize compliance with tax laws while ethically minimizing tax liability. Be prepared to explain complex tax concepts in simple terms and provide rationale for your recommendations. If a situation is beyond your expertise, advise consulting a certified tax professional or IRS resources.\"\"\",\n agent_name=\"Tax Filing Agent\",\n ),\n TreeAgent(\n system_prompt=\"\"\"You are a sophisticated Investment Strategy Agent, adept at creating and managing investment portfolios to meet diverse financial goals. Your expertise covers various asset classes, market analysis, and risk management techniques. When developing investment strategies:\n\n1. Begin by assessing the client's investment goals, time horizon, and risk tolerance.\n2. Provide a comprehensive overview of different asset classes and their risk-return profiles.\n3. Create diversified portfolio recommendations based on modern portfolio theory.\n4. Explain the benefits and risks of various investment vehicles (e.g., stocks, bonds, ETFs, mutual funds).\n5. Incorporate both passive and active investment strategies as appropriate.\n6. Discuss the importance of regular portfolio rebalancing and provide a rebalancing strategy.\n7. Consider tax implications of investment decisions and suggest tax-efficient strategies.\n8. Provide ongoing market analysis and suggest portfolio adjustments as needed.\n\nUse historical data and forward-looking projections to illustrate potential outcomes. Always emphasize the importance of long-term investing and the risks of market timing. Be prepared to explain complex investment concepts in clear, accessible language.\"\"\",\n agent_name=\"Investment Strategy Agent\",\n ),\n TreeAgent(\n system_prompt=\"\"\"You are a specialized ROTH IRA Agent, focusing on the intricacies of Roth Individual Retirement Accounts. Your role is to provide expert guidance on Roth IRA rules, benefits, and strategies to maximize their value for retirement planning. When advising on Roth IRAs:\n\n1. Explain the fundamental differences between traditional and Roth IRAs.\n2. Clarify Roth IRA contribution limits and income eligibility requirements.\n3. Discuss the tax advantages of Roth IRAs, including tax-free growth and withdrawals.\n4. Provide guidance on Roth IRA conversion strategies and their tax implications.\n5. Explain the five-year rule and how it affects Roth IRA withdrawals.\n6. Offer strategies for maximizing Roth IRA contributions, such as the backdoor Roth IRA method.\n7. Discuss how Roth IRAs fit into overall retirement and estate planning strategies.\n8. Provide insights on investment choices within a Roth IRA to maximize tax-free growth.\n\nAlways stay current with IRS regulations regarding Roth IRAs. Be prepared to provide numerical examples to illustrate the long-term benefits of Roth IRAs. Emphasize the importance of considering individual financial situations when making Roth IRA decisions.\"\"\",\n agent_name=\"ROTH IRA Agent\",\n ),\n]\n\n# Create trees\ntree1 = Tree(tree_name=\"Financial Tree\", agents=agents_tree1)\ntree2 = Tree(tree_name=\"Investment Tree\", agents=agents_tree2)\n\n# Create the ForestSwarm\nmulti_agent_structure = ForestSwarm(trees=[tree1, tree2])\n\n# Run a task\ntask = \"What are the best platforms to do our taxes on\"\noutput = multi_agent_structure.run(task)\nprint(output)\n\n```\n\n\n\n\n## `SwarmRouter`\nThe `SwarmRouter` class is a flexible routing system designed to manage different types of swarms for task execution. It provides a unified interface to interact with various swarm types, including `AgentRearrange`, `MixtureOfAgents`, `SpreadSheetSwarm`, `SequentialWorkflow`, and `ConcurrentWorkflow`. We will be continuously adding more and more swarm architectures here as we progress with new architectures.\n\n#### Attributes:\n- `name` (str): Name of the SwarmRouter instance.\n- `description` (str): Description of the SwarmRouter instance.\n- `max_loops` (int): Maximum number of loops to perform.\n- `agents` (List[Agent]): List of Agent objects to be used in the swarm.\n- `swarm_type` (SwarmType): Type of swarm to be used.\n- `swarm` (Union[AgentRearrange, MixtureOfAgents, SpreadSheetSwarm, SequentialWorkflow, ConcurrentWorkflow]): Instantiated swarm object.\n- `logs` (List[SwarmLog]): List of log entries captured during operations.\n\n#### Methods:\n- `__init__(self, name: str, description: str, max_loops: int, agents: List[Agent], swarm_type: SwarmType, *args, **kwargs)`: Initialize the SwarmRouter.\n- `_create_swarm(self, *args, **kwargs)`: Create and return the specified swarm type.\n- `_log(self, level: str, message: str, task: str, metadata: Dict[str, Any])`: Create a log entry and add it to the logs list.\n- `run(self, task: str, *args, **kwargs)`: Run the specified task on the selected swarm.\n- `get_logs(self)`: Retrieve all logged entries.\n\n\n```python\nimport os\nfrom dotenv import load_dotenv\nfrom swarms import Agent\nfrom swarm_models import OpenAIChat\nfrom swarms.structs.swarm_router import SwarmRouter, SwarmType\n\nload_dotenv()\n\n# Get the OpenAI API key from the environment variable\napi_key = os.getenv(\"GROQ_API_KEY\")\n\n# Model\nmodel = OpenAIChat(\n openai_api_base=\"https://api.groq.com/openai/v1\",\n openai_api_key=api_key,\n model_name=\"llama-3.1-70b-versatile\",\n temperature=0.1,\n)\n# Define specialized system prompts for each agent\nDATA_EXTRACTOR_PROMPT = \"\"\"You are a highly specialized private equity agent focused on data extraction from various documents. Your expertise includes:\n1. Extracting key financial metrics (revenue, EBITDA, growth rates, etc.) from financial statements and reports\n2. Identifying and extracting important contract terms from legal documents\n3. Pulling out relevant market data from industry reports and analyses\n4. Extracting operational KPIs from management presentations and internal reports\n5. Identifying and extracting key personnel information from organizational charts and bios\nProvide accurate, structured data extracted from various document types to support investment analysis.\"\"\"\n\nSUMMARIZER_PROMPT = \"\"\"You are an expert private equity agent specializing in summarizing complex documents. Your core competencies include:\n1. Distilling lengthy financial reports into concise executive summaries\n2. Summarizing legal documents, highlighting key terms and potential risks\n3. Condensing industry reports to capture essential market trends and competitive dynamics\n4. Summarizing management presentations to highlight key strategic initiatives and projections\n5. Creating brief overviews of technical documents, emphasizing critical points for non-technical stakeholders\nDeliver clear, concise summaries that capture the essence of various documents while highlighting information crucial for investment decisions.\"\"\"\n\nFINANCIAL_ANALYST_PROMPT = \"\"\"You are a specialized private equity agent focused on financial analysis. Your key responsibilities include:\n1. Analyzing historical financial statements to identify trends and potential issues\n2. Evaluating the quality of earnings and potential adjustments to EBITDA\n3. Assessing working capital requirements and cash flow dynamics\n4. Analyzing capital structure and debt capacity\n5. Evaluating financial projections and underlying assumptions\nProvide thorough, insightful financial analysis to inform investment decisions and valuation.\"\"\"\n\nMARKET_ANALYST_PROMPT = \"\"\"You are a highly skilled private equity agent specializing in market analysis. Your expertise covers:\n1. Analyzing industry trends, growth drivers, and potential disruptors\n2. Evaluating competitive landscape and market positioning\n3. Assessing market size, segmentation, and growth potential\n4. Analyzing customer dynamics, including concentration and loyalty\n5. Identifying potential regulatory or macroeconomic impacts on the market\nDeliver comprehensive market analysis to assess the attractiveness and risks of potential investments.\"\"\"\n\nOPERATIONAL_ANALYST_PROMPT = \"\"\"You are an expert private equity agent focused on operational analysis. Your core competencies include:\n1. Evaluating operational efficiency and identifying improvement opportunities\n2. Analyzing supply chain and procurement processes\n3. Assessing sales and marketing effectiveness\n4. Evaluating IT systems and digital capabilities\n5. Identifying potential synergies in merger or add-on acquisition scenarios\nProvide detailed operational analysis to uncover value creation opportunities and potential risks.\"\"\"\n\n# Initialize specialized agents\ndata_extractor_agent = Agent(\n agent_name=\"Data-Extractor\",\n system_prompt=DATA_EXTRACTOR_PROMPT,\n llm=model,\n max_loops=1,\n autosave=True,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"data_extractor_agent.json\",\n user_name=\"pe_firm\",\n retry_attempts=1,\n context_length=200000,\n output_type=\"string\",\n)\n\nsummarizer_agent = Agent(\n agent_name=\"Document-Summarizer\",\n system_prompt=SUMMARIZER_PROMPT,\n llm=model,\n max_loops=1,\n autosave=True,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"summarizer_agent.json\",\n user_name=\"pe_firm\",\n retry_attempts=1,\n context_length=200000,\n output_type=\"string\",\n)\n\nfinancial_analyst_agent = Agent(\n agent_name=\"Financial-Analyst\",\n system_prompt=FINANCIAL_ANALYST_PROMPT,\n llm=model,\n max_loops=1,\n autosave=True,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"financial_analyst_agent.json\",\n user_name=\"pe_firm\",\n retry_attempts=1,\n context_length=200000,\n output_type=\"string\",\n)\n\nmarket_analyst_agent = Agent(\n agent_name=\"Market-Analyst\",\n system_prompt=MARKET_ANALYST_PROMPT,\n llm=model,\n max_loops=1,\n autosave=True,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"market_analyst_agent.json\",\n user_name=\"pe_firm\",\n retry_attempts=1,\n context_length=200000,\n output_type=\"string\",\n)\n\noperational_analyst_agent = Agent(\n agent_name=\"Operational-Analyst\",\n system_prompt=OPERATIONAL_ANALYST_PROMPT,\n llm=model,\n max_loops=1,\n autosave=True,\n verbose=True,\n dynamic_temperature_enabled=True,\n saved_state_path=\"operational_analyst_agent.json\",\n user_name=\"pe_firm\",\n retry_attempts=1,\n context_length=200000,\n output_type=\"string\",\n)\n\n# Initialize the SwarmRouter\nrouter = SwarmRouter(\n name=\"pe-document-analysis-swarm\",\n description=\"Analyze documents for private equity due diligence and investment decision-making\",\n max_loops=1,\n agents=[\n data_extractor_agent,\n summarizer_agent,\n financial_analyst_agent,\n market_analyst_agent,\n operational_analyst_agent,\n ],\n swarm_type=\"ConcurrentWorkflow\", # or \"SequentialWorkflow\" or \"ConcurrentWorkflow\" or\n)\n\n# Example usage\nif __name__ == \"__main__\":\n # Run a comprehensive private equity document analysis task\n result = router.run(\n \"Where is the best place to find template term sheets for series A startups. Provide links and references\"\n )\n print(result)\n\n # Retrieve and print logs\n for log in router.get_logs():\n print(f\"{log.timestamp} - {log.level}: {log.message}\")\n\n```\n\n### Changing Swarm Types\n\nYou can create multiple SwarmRouter instances with different swarm types:\n\n```python\nsequential_router = SwarmRouter(\n name=\"SequentialRouter\",\n agents=[\n data_extractor_agent,\n summarizer_agent,\n financial_analyst_agent,\n market_analyst_agent,\n operational_analyst_agent,\n ],\n swarm_type=SwarmType.SequentialWorkflow\n)\n\nconcurrent_router = SwarmRouter(\n name=\"ConcurrentRouter\",\n agents=[\n data_extractor_agent,\n summarizer_agent,\n financial_analyst_agent,\n market_analyst_agent,\n operational_analyst_agent,\n ],\n swarm_type=SwarmType.ConcurrentWorkflow\n)\n```\n\n### AgentRearrange\n\nUse Case: Optimizing agent order for complex multi-step tasks.\n\n```python\nrearrange_router = SwarmRouter(\n name=\"TaskOptimizer\",\n description=\"Optimize agent order for multi-step tasks\",\n max_loops=3,\n agents=[\n data_extractor_agent,\n summarizer_agent,\n financial_analyst_agent,\n market_analyst_agent,\n operational_analyst_agent,\n ],\n swarm_type=SwarmType.AgentRearrange,\n flow = f\"{data_extractor.name} -> {analyzer.name} -> {summarizer.name}\"\n)\n\nresult = rearrange_router.run(\"Analyze and summarize the quarterly financial report\")\n```\n\n### MixtureOfAgents\n\nUse Case: Combining diverse expert agents for comprehensive analysis.\n\n```python\nmixture_router = SwarmRouter(\n name=\"ExpertPanel\",\n description=\"Combine insights from various expert agents\",\n max_loops=1,\n agents=[\n data_extractor_agent,\n summarizer_agent,\n financial_analyst_agent,\n market_analyst_agent,\n operational_analyst_agent,\n ],\n swarm_type=SwarmType.MixtureOfAgents\n)\n\nresult = mixture_router.run(\"Evaluate the potential acquisition of TechStartup Inc.\")\n```\n\n\n-------\n\n## GroupChat\n\nA production-grade multi-agent system enabling sophisticated group conversations between AI agents with customizable speaking patterns, parallel processing capabilities, and comprehensive conversation tracking.\n\n\n```python\n\nimport os\nfrom dotenv import load_dotenv\nfrom swarm_models import OpenAIChat\nfrom swarms import Agent, GroupChat, expertise_based\n\n\nif __name__ == \"__main__\":\n\n load_dotenv()\n\n # Get the OpenAI API key from the environment variable\n api_key = os.getenv(\"OPENAI_API_KEY\")\n\n # Create an instance of the OpenAIChat class\n model = OpenAIChat(\n openai_api_key=api_key,\n model_name=\"gpt-4o-mini\",\n temperature=0.1,\n )\n\n # Example agents\n agent1 = Agent(\n agent_name=\"Financial-Analysis-Agent\",\n system_prompt=\"You are a financial analyst specializing in investment strategies.\",\n llm=model,\n max_loops=1,\n autosave=False,\n dashboard=False,\n verbose=True,\n dynamic_temperature_enabled=True,\n user_name=\"swarms_corp\",\n retry_attempts=1,\n context_length=200000,\n output_type=\"string\",\n streaming_on=False,\n )\n\n agent2 = Agent(\n agent_name=\"Tax-Adviser-Agent\",\n system_prompt=\"You are a tax adviser who provides clear and concise guidance on tax-related queries.\",\n llm=model,\n max_loops=1,\n autosave=False,\n dashboard=False,\n verbose=True,\n dynamic_temperature_enabled=True,\n user_name=\"swarms_corp\",\n retry_attempts=1,\n context_length=200000,\n output_type=\"string\",\n streaming_on=False,\n )\n\n agents = [agent1, agent2]\n\n chat = GroupChat(\n name=\"Investment Advisory\",\n description=\"Financial and tax analysis group\",\n agents=agents,\n speaker_fn=expertise_based,\n )\n\n history = chat.run(\n \"How to optimize tax strategy for investments?\"\n )\n print(history.model_dump_json(indent=2))\n\n```\n\n\n----------\n\n## Onboarding Session\nGet 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)\n\n\n---\n\n## Documentation\nDocumentation is located here at: [docs.swarms.world](https://docs.swarms.world)\n\n-----\n\n## Folder Structure\nThe swarms package has been meticlously crafted for extreme use-ability and understanding, the swarms package is split up into various modules such as `swarms.agents` that holds pre-built agents, `swarms.structs`\u00a0that holds a vast array of structures like `Agent` and multi agent structures. The 3 most important are `structs`, `models`, and `agents`.\n\n```sh\n\u251c\u2500\u2500 __init__.py\n\u251c\u2500\u2500 agents\n\u251c\u2500\u2500 artifacts\n\u251c\u2500\u2500 memory\n\u251c\u2500\u2500 schemas\n\u251c\u2500\u2500 models -> swarm_models\n\u251c\u2500\u2500 prompts\n\u251c\u2500\u2500 structs\n\u251c\u2500\u2500 telemetry\n\u251c\u2500\u2500 tools\n\u251c\u2500\u2500 utils\n\u2514\u2500\u2500 workers\n```\n\n----\n\n## \ud83e\udef6 Contributions:\n\nThe easiest way to contribute is to pick any issue with the `good first issue` tag \ud83d\udcaa. 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)\n\nSwarms is an open-source project, and contributions are VERY welcome. If you want to contribute, you can create new features, fix bugs, or improve the infrastructure. Please refer to the [CONTRIBUTING.md](https://github.com/kyegomez/swarms/blob/master/CONTRIBUTING.md) and our [contributing board](https://github.com/users/kyegomez/projects/1) to participate in Roadmap discussions!\n\n----\n\n\n\n## Accelerate Backlog\nAccelerate Bugs, Features, and Demos to implement by supporting us here:\n\n<a href=\"https://polar.sh/kyegomez\"><img src=\"https://polar.sh/embed/fund-our-backlog.svg?org=kyegomez\" /></a>\n\n## Community\n\nJoin our growing community around the world, for real-time support, ideas, and discussions on Swarms \ud83d\ude0a \n\n- View our official [Blog](https://docs.swarms.world)\n- Chat live with us on [Discord](https://discord.gg/kS3rwKs3ZC)\n- Follow us on [Twitter](https://twitter.com/kyegomez)\n- Connect with us on [LinkedIn](https://www.linkedin.com/company/the-swarm-corporation)\n- Visit us on [YouTube](https://www.youtube.com/channel/UC9yXyitkbU_WSy7bd_41SqQ)\n- [Join the Swarms community on Discord!](https://discord.gg/AJazBmhKnr)\n- Join our Swarms Community Gathering every Thursday at 1pm NYC Time to unlock the potential of autonomous agents in automating your daily tasks [Sign up here](https://lu.ma/5p2jnc2v)\n\n# License\n\nGNU AFFERO GENERAL PUBLIC LICENSE\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Swarms - TGSC",
"version": "6.7.9",
"project_urls": {
"Documentation": "https://docs.swarms.world",
"Homepage": "https://github.com/kyegomez/swarms",
"Repository": "https://github.com/kyegomez/swarms"
},
"split_keywords": [
"artificial intelligence",
" deep learning",
" optimizers",
" prompt engineering",
" swarms",
" agents",
" llms",
" transformers",
" multi-agent",
" swarms of agents",
" enterprise-grade agents",
" production-grade agents",
" agents",
" multi-grade-agents",
" swarms",
" transformers",
" llms",
" prompt engineering",
" agents",
" generative agents",
" generative ai",
" agent marketplace",
" agent store",
" quant",
" finance",
" algorithmic trading",
" portfolio optimization",
" risk management",
" financial modeling",
" machine learning for finance",
" natural language processing for finance"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "8565deb97334efcd3b3487a4aeb2d8b21c6c6f32a40b4d6d62a299121bb4fbaa",
"md5": "947e55286b0147a0f4323fa07b156732",
"sha256": "fe5f939a302bc94f5bafd0f4114aec69e3ad19e9e04ec88d718f56f55a33aaec"
},
"downloads": -1,
"filename": "swarms-6.7.9-py3-none-any.whl",
"has_sig": false,
"md5_digest": "947e55286b0147a0f4323fa07b156732",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.10",
"size": 376509,
"upload_time": "2024-12-23T21:42:51",
"upload_time_iso_8601": "2024-12-23T21:42:51.064424Z",
"url": "https://files.pythonhosted.org/packages/85/65/deb97334efcd3b3487a4aeb2d8b21c6c6f32a40b4d6d62a299121bb4fbaa/swarms-6.7.9-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "ee0cccf73fa998048a726f7a3707c6bb1678317b9f96eb4280ba1a211172ad1e",
"md5": "412e60162c1d46107c8846742d325acc",
"sha256": "3e24d2b893418569716c489fd9a236f1b426f789acc453baf7867fc21f4ad7bb"
},
"downloads": -1,
"filename": "swarms-6.7.9.tar.gz",
"has_sig": false,
"md5_digest": "412e60162c1d46107c8846742d325acc",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.10",
"size": 335134,
"upload_time": "2024-12-23T21:42:54",
"upload_time_iso_8601": "2024-12-23T21:42:54.298660Z",
"url": "https://files.pythonhosted.org/packages/ee/0c/ccf73fa998048a726f7a3707c6bb1678317b9f96eb4280ba1a211172ad1e/swarms-6.7.9.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-12-23 21:42:54",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "kyegomez",
"github_project": "swarms",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [
{
"name": "torch",
"specs": [
[
">=",
"2.1.1"
],
[
"<",
"3.0"
]
]
},
{
"name": "transformers",
"specs": [
[
"<",
"5.0.0"
],
[
">=",
"4.39.0"
]
]
},
{
"name": "asyncio",
"specs": [
[
">=",
"3.4.3"
],
[
"<",
"4.0"
]
]
},
{
"name": "toml",
"specs": []
},
{
"name": "pypdf",
"specs": [
[
"==",
"5.1.0"
]
]
},
{
"name": "ratelimit",
"specs": [
[
"==",
"2.2.1"
]
]
},
{
"name": "loguru",
"specs": []
},
{
"name": "pydantic",
"specs": [
[
"==",
"2.8.2"
]
]
},
{
"name": "tenacity",
"specs": []
},
{
"name": "rich",
"specs": []
},
{
"name": "psutil",
"specs": []
},
{
"name": "sentry-sdk",
"specs": []
},
{
"name": "python-dotenv",
"specs": []
},
{
"name": "PyYAML",
"specs": []
},
{
"name": "docstring_parser",
"specs": [
[
"==",
"0.16"
]
]
},
{
"name": "black",
"specs": [
[
">=",
"23.1"
],
[
"<",
"25.0"
]
]
},
{
"name": "ruff",
"specs": [
[
">=",
"0.0.249"
],
[
"<",
"0.4.5"
]
]
},
{
"name": "types-toml",
"specs": [
[
">=",
"0.10.8.1"
]
]
},
{
"name": "types-pytz",
"specs": [
[
">=",
"2023.3"
],
[
"<",
"2025.0"
]
]
},
{
"name": "types-chardet",
"specs": [
[
">=",
"5.0.4.6"
]
]
},
{
"name": "mypy-protobuf",
"specs": [
[
">=",
"3.0.0"
]
]
},
{
"name": "pytest",
"specs": [
[
">=",
"8.1.1"
]
]
},
{
"name": "pandas",
"specs": [
[
">=",
"2.2.2"
]
]
},
{
"name": "networkx",
"specs": []
},
{
"name": "aiofiles",
"specs": []
},
{
"name": "clusterops",
"specs": []
},
{
"name": "reportlab",
"specs": []
},
{
"name": "doc-master",
"specs": []
},
{
"name": "termcolor",
"specs": []
}
],
"lcname": "swarms"
}